Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Psycopg2 causing ImportError with reason: image not found
I have been running Django and PostgresSQLand have been getting this error when running the migrations: ImportError: dlopen(/Users/tristanwhite/PycharmProjects/Pixel_Pals/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libssl.1.1.dylib Referenced from: /Users/tristanwhite/PycharmProjects/Pixel_Pals/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so Reason: image not found This is using pycharm on a macOS Mojave machine -
override django - oscar payment
I want to save the payment data into admin section of BankCard in Django oscar . I overrided the paypal code like below ,but I get an error , saying : ValueError at /checkout/preview/ The Bankcard could not be created because the data didn't validate. Request Method: POST The Bankcard could not be created because the data didn't validate. How can I override the validation? from oscar.apps.checkout.views import PaymentDetailsView as CorePaymentDetailsView #from .models import PaymentCard as Bankcard from django.shortcuts import redirect from django.shortcuts import render from oscar.apps.payment.forms import BankcardForm from oscar.apps.checkout import views from oscar.apps.payment import forms, models from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse class PaymentDetailsView(CorePaymentDetailsView): template_name = 'paymen_details.html' def get_context_data(self, **kwargs): """ Add data for Paypal Express flow. """ # Override method so the bankcard and billing address forms can be # added to the context. template_name = 'checkout/payment_details.html' ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) ctx['bankcard_form'] = kwargs.get( 'bankcard_form', forms.BankcardForm()) """ ctx['billing_address_form'] = kwargs.get( 'billing_address_form', forms.BillingAddressForm()) """ return ctx def post(self, request, *args, **kwargs): # Override so we can validate the bankcard/billingaddress submission. # If it is valid, we render the preview screen with the forms hidden # within it. When the preview is submitted, … -
Django - request to API in the same project
I have 2 apps in my project. One of them contains the API. The second app sends a request. class PlayLongView(TemplateView): template_name = 'play/homepage.html' def get_price_info(self): url = reverse('myAPI:play_data') return requests.get(url).json() def get_context_data(self, **kwargs): context = super().get_context_data() data = self.get_price_info() context['price'] = data[0]['price'] return context It gives me a mistake: Invalid URL '/myAPI/play_data': No schema supplied. Perhaps you meant http:///myAPI/play_data? Of course I can replace: url = reverse('myAPI:play_data') with a: url = 'http://localhost:8000/myAPI/play_data' and then it works correctly, but my code is "local". How should I write it so that the code also works after host on the server? -
How to access image file that is stored in local machine by clicking on link in a web application using Django?
I am new to django and running into an issue. I am using Django to generate/display test results from python-appium framework. Here I am trying to display a screenshot(saved by the python-appium framework) from my local machine when clicking on a link in dango web application. This is how my HTML page looks This is my code in the template/html file in django. <td><a href="file:///{{ScreenshotLocation}}">Click to view Screenshot</a></td> The variable ScreenshotLocation variable holds the file location(/Users/abc/PycharmProjects/Project1/Screenshots/FileName_timestamp.png The file name is generated dynamically by Python based on timestamp. When I click on the link, nothing happens. The screenshot is not displayed. How can I display the screenshot when clicking on the "Click to view screenshot" link using django? -
How to use pandas fast to_sql method correctly?
Pandas 0.24.0 have a fast implementation to load data into a PostgreSQL database in their website. I copied the method into my django application and use it like so: def insertData(): # download some data into a dataframe df... engine = create_engine('postgresql://user:password@host:port/name') df.to_sql(name='HistData', con=engine, if_exists="append", method=psql_insert_copy) This is how the django model looks like: class HistData(models.Model): """A model representing a stock's data on a specific date""" # Fields stock = models.ForeignKey('Stock', on_delete=models.CASCADE, related_name='histData', null=False) date = models.DateField(verbose_name='Date Correspondence', name='date', null=False) openVal = models.FloatField(verbose_name='Open Value', name='open', null=True) closeVal = models.FloatField(verbose_name='Close Value', name='close', null=True) adjCloseVal = models.FloatField(verbose_name='Adjacent Close Value', name='adjClose', null=True) highVal = models.FloatField(verbose_name='Highest Value', name='high', null=True) lowVal = models.FloatField(verbose_name='Lowest Value', name='low', null=True) volume = models.FloatField(verbose_name='Volume', name='volume', null=True) When I run the application and try to activate the method insertData() I get one of the following errors: either Table "histdata" already exists or relation "histdata" does not exist, however I made sure that the table exists. I have looked through other methods of doing this, mainly from here, and yet I can't seem to make it work. Does anyone know what I'm doing wrong? -
0001_initial migrations Wont Create
So I'm new to django and recently tried to create some migrations for a project. I created the project, created the application name, and set the application name in the Installed apps section in settings. Whenever I run 'python manage.py makemigrations ' it gives me an output of: 'No changes detected in app' Then when i run 'python manage.py migrate' it gives me: Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. There is a migrations folder within the application module, it just has an empty 'init.py' file inside. Any suggestions? -
How to SELECT from multiple tables in Django ORM?
I have two tables, oneup_backend_design and Django's default auth_user. First table have following columns (simplified): human_readable_id, manager, worker. Worker column contains a username from auth_user. So I want to get human_readable_id plus first_name and last_name of worker associated with username in one query. In raw SQL it would look like this: SELECT d.human_readable_id, u.first_name, u.last_name FROM oneup_backend_design as d, auth_user as u WHERE d.worker = u.username; I've tried hard reading the docs and Django ORM cookbook, but did not found anything. It's such a simple query, I should be missing something. How one can make it with single database hit? -
Django Image upload in project with two apps
I am trying to upload images in a Django with two apps home and main my project name is register. Just to test if the media root is being added correctly I am displaying an image in my html template using: <img src="{{ MEDIA_URL }}profile_image/profile_default.png " alt="HAHA"> However, I am getting a 404 error saying: Not Found: /home/profile_image/profile_default.png [02/Apr/2020 16:58:50] "GET /home/profile_image/profile_default.png HTTP/1.1" 404 8402 I already have this in my settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And I also have this in my project urls: urlpatterns = [ #my urls ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I am also facing an issue that images are not being uploaded at all in my views this is my image model: class Images(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images') image = models.FileField(upload_to=upload_to_uuid('post_images', make_dir=True),verbose_name='Image') date_added = models.DateTimeField(auto_now_add=True) I am using the django_uuid_upload package. For your reference my folders are register -home -main -register --settings.py --urls.py -media --post_images --profile_image ---profile_default.png -static Thanks for all the help in advance! -
Django - Dynamic filtering in class based views
I am trying to write a Class Based View from an already filtered view. However I couldn't find out how to pass arguments to CBV. I am using django 3.0.4 with pipenv python 3.8 as an example assume I have 2 models: class Customer(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() class WorkOrder(models.Model): date_created = models.DateField('Date', default=datetime.now) due_date = models.DateField('Due Date') customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Customer') STATUS_CHOICES = [ ('pending', 'Pending'), ('approved', 'Approved'), ('completed', 'Completed'), ('cancelled', 'Cancelled'), ] status = models.CharField('Status of the work order', max_length=10, choices=STATUS_CHOICES, default='pending') description = models.TextField('Description of the work') I wrote a FBV for listing the work orders of a customer filtered by status. Something like that: def customer_workorders(request, pk): customer = CustomUser.objects.get(pk=pk) pending_workorders = WorkOrder.objects.filter(customer=pk).filter(status='pending') approved_workorders = WorkOrder.objects.filter(customer=pk).filter(status='approved') completed_workorders = WorkOrder.objects.filter(customer=pk).filter(status='completed') cancelled_workorders = WorkOrder.objects.filter(customer=pk).filter(status='cancelled') context = { 'customer': customer, 'pending': pending_workorders, 'approved': approved_workorders, 'completed': completed_workorders, 'cancelled': cancelled_workorders } return render(request, 'reports/cusomer_workorders.html', context) I am trying to make a CBV list view of every work orders according to their status. I know my Class Based View should be like this class CustomerWorkOrderPendingView(LoginRequiredMixin, ListView): template_name = 'reports/customer_workorders_list.html' def get_queryset(self): return WorkOrder.objects.filter(customer=customer).filter(status='pending') My question is how can I get the customer object according to that … -
Recommendation System Web App using Flask or Django
I want to create create a movie recommendation web app using python with flask or django. Web app should first ask the user to select 3 movies and then recommend him 5 movies related to his input. I have limited knowledge about flask and django. How can I proceed ? -
fcm push notification registeration id not registered
I'm using fcm api in push notification, my backend is django rest framework. fcm api: "https://fcm.googleapis.com/fcm/send" most of the time push notifications failed and the error is "Not Registered". I looked into it and it might be different cases as mentioned in docs I made sure that registration id is updated whenever firebase refreshed it. but it also give me that error. But the weird part is, i take a test user, when i sent an push notification it succeeded, and after 2 hours it gave me "Not Registered", and the user not uninstalled or reinstalled the app. Any Explanation ?! -
Stop Django Invalid HTTP_HOST header errors at the Elastic Load Balancer level
I am running a Django app on Elastic Container Service behind Elastic Load Balancer. I am seeing a ton of Invalid HTTP_HOST header errors at the Django App level that look like: Invalid HTTP_HOST header: '34.237.89.13'. You may need to add '34.237.89.13' to ALLOWED_HOSTS. How do I block these invalid requests at the load balancer level in Elastic Load Balancer? -
Apache throws ERROR 500: Internal Server Error when GET from localhost/internal network
I have a production server with apache and django installed using mod_wsgi. The django application has a REST API that serves some info when a GET request is sent. This has always worked fine on the develop server, were we ran django using manage.py in a screen. Now we created a production server with apache running django but this API returns Error 500 when running wget from localhost or other machines in the same network (using 192.168.X.X IP). Here's the output from wget: ~$ wget localhost:80/someinfo --2020-04-02 16:26:59-- http://localhost/someinfo Resolving localhost (localhost)... 127.0.0.1 Connecting to localhost (localhost)|127.0.0.1|:80... connected. HTTP request sent, awaiting response... 500 Internal Server Error 2020-04-02 16:26:59 ERROR 500: Internal Server Error. It seems that the connection succeeds, so I guess it's not an apache problem. The error comes from the API response. The error in apache error.log looks like this: 127.0.0.1 - - [02/Apr/2020:14:24:36 +0000] "GET /someinfo HTTP/1.1" 500 799 "-" "Wget/1.19.4 (linux-gnu)" question: what is the number after 500? Sometimes is 799 and other times is 803. But if the request is done using the public IP of the server from outside (i.e. from the browser) the API works fine and I see the correct information. … -
Start Django project and open Visual Studio Code using batch file
I want to create a batch file where I can start a Django project and open visual studio code at the same time while creating a new file inside the terminal command (Window 10). This is how it goes when I want to start a Django project: Command: >C:\Users\bvsia\Documents\Programming\Python\Django >django-admin startproject mysite >cd mysite >python manage.py startapp main >python manage.py runserver then I open Visual Studio Code from the terminal command typing code . on the file that was created. Then I will have my Django project to work on. I want the one click file for all what I did step by step. This is what I got so far in batch file. @echo off start cmd.exe /C "django-admin startproject mysite && cd mysite && python manage.py startapp main && python manage.py runserver && cd C:\Users\bvsia\Documents\Programming\Python\Django" start cmd.exe /C "C:\Users\bvsia\Documents\Programming\Python\Django && code ." start http://127.0.0.1:8000/ I have tried several ways to execute this but nothing worked. I hope you can see what I am trying to do here and help me with this. Thanks -
Fill value on hidden django input field
I have a model form and I'm manually entering the fields into my template. Model form: class ProductEntryForm(forms.ModelForm): class Meta: model = Product fields = [ 'image', 'product_name', 'price', 'options', ] Manually rendering fields in Template: <form method="POST" enctype="multipart/form-data"> <h2>New Product</h2> {% csrf_token %} {{ form.non_field_errors }} <p> <label for="">Image</label> {{ form.image.errors }} {{ form.image }} </p> <p> <label for="">Product name</label> {{ form.product_name.errors }} {{ form.product_name }} </p> <p> <label for="">Description</label> {{ form.description.errors }} {{ form.description }} </p> ... The options field of the form is hidden in the template because the user doesn't fill this field directly. They fill it from a different input field. <form method="POST" enctype="multipart/form-data"> ... <p style="display: none"> {{ form.options }} </p> <input type="text" name="visible_option_input" :value="[[make_this_value_of_{{form.options}}_when_submitted]]"> ... </form> I want the value of "visible_option_input" to be the value of {{ form.options }} when submitted -
Django model TypeError at /writeReview/1 __str__ returned non-string (type int)
I am facing issues related to the above error (also shown in picture 4). Can someone help me out here? I am seeing this error while trying to submit the form which saves the data to the ReviewTable as shown in the picture 2. enter image description here enter image description here enter image description here enter image description here -
How can I upload and edit images to a post? - Django
I am building a blog app using Django and I would like the ability for users to add images to each post in a template. I have already added the image upload and everything works fine. The problem, however, is that the default Django image form (upload, edit and delete) doesn't look very pleasing and I am having too much difficulty customizing this. If anyone knows of a cabable and good looking solution or integration/service that works, please let me know. -
OSError: [Errno 30] Read-only file system when unzipping files in Django
I'm trying to implement unzipping files function to my Django app. Basically users will upload data and some process will start with Celery. But I get OSError: [Errno 30] Read-only file system: '/media' error (from settings.MEDIA_URL, probably). At the moment, I'm developing the app on my Mac. How can I fix this? Unzipping Code @app.task(bind=True) def extract_zip(self, returns_from_first, user_id): user = Profile.objects.get(user_id=user_id) with zipfile.ZipFile(user.file, 'r') as zip_ref: zip_ref.extractall(str(settings.MEDIA_URL) + str(user.file)) Thanks! -
protecting a json endpoint in django as part of an ajax call
I have a conceptual question. I am currently using an ajax call to send data from my database to the django template to populate a chart on the page urls.py urlpatterns = [ path('chartdata1/', tracker.get_chart_data_json1, name="global_trend_chart"), ] views.py def get_chart_data_json1(request): data = {} cd = ChartData.get_global_trend() data['chart_data'] = cd return HttpResponse(json.dumps(data, default=str), content_type='application/json') HTML / JAVASCRIPT var chartDataUrl = "{% url 'global_trend_chart' %}" $.getJSON(chartDataUrl, function(data) { chartOptions.xAxis.categories = data['chart_data']['date']; chartOptions.series[0].data = data['chart_data']['confirmedcases']; var chart = new Highcharts.Chart(chartOptions); }) While this is working fine, I don’t want people to be able to access the url directly (i.e. I don’t want them to be able to access the json data by going to myurl.com/chartdata1). I just want this view/data to be accessible by my django template to populate the charts there. I also don’t require users to login to see the main page so don’t want to create a @login_required restriction to the view Is there any way for me to protect the myurl.com/chartdata1 endpoint so it’s only consumable by the charts? Thanks -
TemplateDoesNotExist even though the file exists
I get this error even though the file exists - why? -
Why and how does Django send HTTP 200OK for example.com to AWS Scanner
I'm running Django 3.0 on Ubuntu in AWS cloud and in my Nginx logs I see the following: 44.224.22.196 - - [02/Apr/2020:18:49:13 +0530] "GET http://example.com/ HTTP/1.1" **200** 396 "-" "AWS Security Scanner" example.com is their in my Django sites but I haven't put it in allowed hosts (in settings.py). Neither example.com exists in my Nginx's server block, then why does Nginx send HTTP 200 to AWS Scanner? -
UpdateView for ModelForm with custom field form
I have two model Model A: fieldA1 fieldA2 Model B: fieldA = ForeignKey(A) fieldB1 fieldB2 I need to create ModelFormB but i need also insert value to Model B via form. So i create ModelForm B: fielda1 = form.CharField() fielda2 = form.CharField() class Meta: model = ModelB field = [fielda1, fielda2, fieldb1, fieldb2] Mu UpdateView code: class ModelBUpdateView(LoginRequiredMixin, UpdateView): model = ModelB form_class = ModelFormB template_name = "....." success_url = reverse_lazy('...') The problem is, in template i can see only ModelB(fieldb1,fieldb2) instance initial value but fielda1 and fielda2 are completely blank. How i send the value to fielda1 and fielda2 during updateview? -
django.setup() in every python test file needed?
I execute one particular test via PyCharm (ctrl-shift-F10). I get this error: Testing started at 18:12 ... /home/guettli/simple21env/bin/python /snap/pycharm-community/188/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py --target simple21.tests.TermTests.test_str_of_sub_term Launching unittests with arguments python -m unittest simple21.tests.TermTests.test_str_of_sub_term in /home/guettli/simple21env/src/simple21tree Traceback (most recent call last): File "/snap/pycharm-community/188/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) File "/usr/lib/python3.6/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/lib/python3.6/unittest/main.py", line 141, in parseArgs self.createTests() File "/usr/lib/python3.6/unittest/main.py", line 148, in createTests self.module) File "/usr/lib/python3.6/unittest/loader.py", line 219, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.6/unittest/loader.py", line 219, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/home/guettli/simple21env/src/simple21tree/simple21/tests.py", line 7, in <module> from . import views File "/home/guettli/simple21env/src/simple21tree/simple21/views.py", line 5, in <module> from simple21.models import Term, SearchLog, GlobalConfig File "/home/guettli/simple21env/src/simple21tree/simple21/models.py", line 1, in <module> from django.contrib.auth.models import User File "/home/guettli/simple21env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/guettli/simple21env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/guettli/simple21env/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/home/guettli/simple21env/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/home/guettli/simple21env/lib/python3.6/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process finished with exit code 1 Empty suite I guess I need … -
How can I resolve or fix Django cyclic model field dependencies?
I've a database design corresponding to the following pseudo-code: class AModel(models.Model): c_model_instances = models.OneToOne(CModel, ...) # "is a" relationship class BModel(models.Model): a_model_instances = models.ManyToMany(AModel, ...) # "contains" relationship class CModel(models.Model): b_model_instances = models.ManyToMany(BModel, ...) # "contains" relationship Belief it or not... this design makes total sense from a business perspective :) However of course I get an error NameError: name 'CModel' is not defined when I try to migrate the database. How can I resolve or fix (via different design) the issue? -
Django - not generating an automatic reverse relation
I want to enable my users to add bookmarks to there account but sadly each time I try to add a new bookmark I get the following error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. models.py bookmarkable_models = models.Q(app_label='App', model='model-a') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: verbose_name = "Bookmark" verbose_name_plural = "Bookmark(s)" ordering = ['-date_added']