Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mimic Python's open(filename, 'r') in Django context on uploaded file?
I have tried parsing same GPX file both in and outside of Django context. In a standalone script everything works fine while reading the file in the default text mode: import gpxpy def coordinates_from_GPX(gpx_file): gpx = gpxpy.parse(gpx_file) coordinates = [] for track in gpx.tracks: for segment in track.segments: for point in segment.points: latlng = point.latitude, point.longitude coordinates.append(latlng) return coordinates gpx_file = open('oldrichov.gpx', 'r') # note the 'r' mode coordinates = coordinates_from_GPX(gpx_file) print(coordinates) However, in Django context, I am getting an error while trying to parse the same GPX file uploaded via model form: import gpxpy def have_I_been_there(request): '''Shows the intersection between activities polylines and uploaded GPX ''' if request.method == 'GET': form = GPXFileForm() elif request.method == 'POST': form = GPXFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_gpx = form.save() gpx = gpxpy.parse(uploaded_gpx.file.open(mode='rt')) # ERROR HERE coordinates = coordinates_from_GPX(uploaded_gpx) print(coordinates) context = { 'form': form, } return render(request, 'explorer/have_I_been_there.html', context) Traceback (most recent call last): File "M:\django\newenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "M:\django\newenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "M:\django\strava_explorer\explorer\views.py", line 504, in have_I_been_there coordinates = coordinates_from_GPX(uploaded_gpx) File "M:\django\strava_explorer\explorer\views.py", line 514, in coordinates_from_GPX gpx = gpxpy.parse(gpx_file) … -
How to use JavaScript variable as django tags template parameter?
f I use the code as follows it works: function filter() { var assuntos = document.getElementById("assuntos").value var data = '{{ "CONTRATOS"|filter_assuntos }}'; change(data); }; but how do I use my assuntos variable instead ofCONTRATOS? -
Django DRF, changing authentication schemes from JWT to basic token
I have a Django app that was originally using drf token authentication. Everything was working perfectly. Then I decided to switch to JWT's. I made all the changes and everything was working perfectly. I changed a bunch of code, updated my git and all that, then decided that the drf token auth actually was the better choice. So I changed the authentication classes back, and removed the JWT-specific urls, but every postman request still gives me the JWT denied message: "detail": "Authentication credentials were not provided." It seems that something internally is not being reset by just changing the authentication classes back. I deleted my sqlite file and ran both makemigrations and migrate but still I get the same error. How can I fix this without checking out the old branch of my git (which would lose a bunch of changes I made to the app)? Here is the relevant section of my settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'prototype', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } -
Nginx: No such file or directory
I have a vps server by Reg.ru and domain by freenom. On the Reg.ru I added domain via dnsadmin. All right. Notes are created. Status - synchronized. On the freenom in the management panel of domain are next fields: Name, Type, TTL, Target. Name - empty, TTL - 3600, Type - A, Target - ip of vps server. Status - active. Nginx /etc/nginx/sites-available/myproject and /etc/nginx/sites-enabled/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/nginx/nginx.conf ... http { ... include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.*; } nginx -t - successful systemctl status nginx - active ufw status Status: active To Action From -- ------ ---- 8000 ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000 (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) When I open ip of vps-server in browser I get home page of nginx. gunicorn /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/myproject ExecStart=/home/myproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled# cat /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target systemctl status gunicorn … -
How to save two forms in one model in Django?
I have two Django forms of the same model in the same view, so when I try to save them I get two objects of the model and my goal is to get one single object with the data of both forms. I've tried to save both forms separately, which lead to creating two objects. Also, I've thought of saving one form and then updating the second one but I just don't know how to do that. if request.method == 'POST': animal_form_required = AddAnimalFormRequired(data=request.POST) animal_form_optional = AddAnimalFormOptional(data=request.POST) if animal_form_required.is_valid() and animal_form_optional.is_valid(): animal_required = animal_form_required.save(commit=False) animal_required.save() animal_optional = animal_form_optional.save() animal_optional.save() return render(...) animal_required and animal_optional are the two forms and animal is the model. Both forms have different attributes of the animal. After doing this, I get two objets of animal: one with the animal_requiredattributes and one with the animal_optional attributes. How can I get one single object of animalwith all the attributes? Thanks so much in advance! -
(Django) Displaying multiple generated forms (unknown quantity) in the view, and retrieving their results?
I'm currently attempting to display a set of generated forms into the view. So take the following view, for example (as part of a TemplateView class): def get(self, request, id): df = create_dataframe(User.objects.get(user=request.user.username)) context = generate_context_forms(df=df, user=request.user.username) return authentication_check( request=request, template_name=self.template_name, context=context ) In essence, the create_dataframe function generates some relevant calculations using some user-inputted data, and that data designates how many forms I will be generating for the user. The generate_context_forms function utilizes that DataFrame to generate the context for the user. Typically, a context will look like so: context = { 'general': GeneralForm, 'specific1': SpecificForm, 'specific2': SpecificForm, ... } To n amounts of SpecificForm. What I am trying to do is display all of the specific forms to the user without causing loss of control. All the forms will be submitted by a single "submit" button, and after submission, I must gather all of the data they individually submitted. With the context above, I do not know how I would iterate through all the specific forms in the context. Another attempt I did was to simply add the specific forms to a list: context = { 'general': GeneralForm, 'specific': [SpecificForm, SpecificForm, ...], } But it seems that when … -
Django Forms - Get object if exist - Unique Field - M2M
I'm still a junior with django. Please explain in detail :D I'm developing a system to manage Full Days for restaurants. A full day can have many guests, and a guest can have many full days. M2M Relationship. ============== My model's class Full_day(models.Model): by = models.ForeignKey('users.System_user', on_delete=models.CASCADE) guests = models.ManyToManyField('users.Guest', verbose_name='Huespedes') bussines_unit = models.ForeignKey( 'administration.Bussines_unit', on_delete=models.CASCADE, verbose_name='Unidad de Negocio') type_full_day = models.ForeignKey(cat_full_day, on_delete=models.CASCADE) created = models.DateField( auto_now=True, auto_now_add=False, verbose_name='Creado el') modified = models.DateField( auto_now=False, auto_now_add=True, verbose_name='Modificado el') class Guest(models.Model): stature_choices=( ('+ 1.20', '+ 1.20 M'), ('- 1.20', '- 1.20 M') ) name = models.CharField(max_length=50, verbose_name='Nombre') document_id = models.PositiveIntegerField(unique=True, verbose_name='Cedula/Documento Identidad', blank=True, null=True) stature = models.CharField(verbose_name='Estatura', choices = stature_choices, max_length=6) created = models.DateField(auto_now=True, auto_now_add=False, verbose_name='Creado el') modified = models.DateField(auto_now=False, auto_now_add=True, verbose_name='Modificado el') The Problem As you can see the "document_id" must be unique, I want to make the view get to the guest if it already exists and the name entered is identical to the DB, to assign it to the full day. The number of guests for the Full day depends on the type of full day, I have already solved it with a GET (see it in the View), and I have rendered the amount of GuestForm's according to … -
Why user.save() don't save into database
I want to save customer_id from stripe into my user model, but when call user.save() nothing happen. Here my user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, ) first_name = models.CharField(_('First name'), max_length=20) last_name = models.CharField(_('Last name'), max_length=20) is_active = models.BooleanField(_('Active'), default=True) date_joined = models.DateTimeField(_('Date joined'), auto_now_add=True) is_deleted = models.BooleanField(_('Deleted'), default=False) stripe_customer_id = models.CharField(_('Stripe customer id'), max_length=19, null=True, default=None) Here fragment of code where I create Customer in Stripe and want save id into model: user = User.objects.get(pk=request.user.pk) ... if not user.stripe_customer_id: customer = stripe.Customer.create( email=user.email, name=user.first_name + " " + user.last_name, source=stripe_token ) user.stripe_customer_id = customer.stripe_id user.save() Any ideas why it's not saving ? -
Django - Invalid block tag..'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm having trouble loading this. I'm fairly new to python and it's formatting. I've checked previous questions where it seems to be a syntax error but I can't see any formatting issues. The code is taken straight from the Django tutorial https://docs.djangoproject.com/en/2.2/intro/tutorial06/ {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li></ul> {% else %} <p>No polls are available.</p> {% endif %} -
No connection adapters were found for '<QuerySet
Models class URL_monitor(models.Model): url = models.TextField(unique=True, verbose_name='URL') interval = models.PositiveIntegerField(verbose_name='Interval (in seconds)') def __str__(self): return self.url def get_absolute_url(self): return reverse('index') View def IndexView(request): urls = URL_monitor.objects.all() response = requests.get(urls) status = response.status_code context = { 'urls' : urls, 'status' : status, } return render(request, 'index.html', context) Template {% if urls %} {% for url in urls %} <p>Status: {{ status }} {{ url.url }} <a href="{% url 'delete_url' url.pk %}">Delete</a></p> {% endfor %} {% else %} <p>No URL's added, <a href="{% url 'add_url' %}">add some</a></p> {% endif %} I just want to get an url from my model and get a status code for it. My url field in database has a value: http://google.com/ -
Getting model instances in view DRF
I have a Cart model like this class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='items', null=True) quantity = models.PositiveIntegerField(default=1) here quantity is default value is one so, everytime user does not need to add quantity to the cart. If user does not add quantity it should take default But I cannot get this default value in the view class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer def post(self, request, pk=None, *args, **kwargs): serializer = CartSerializer(data=request.data) if serializer.is_valid(): try: product = Product.objects.get(pk=request.data['product']) quantity = int(self.request.GET.get('quantity')) print(quantity) except Exception as e: print(e) return Response({'status': 'fail'}) if product.inventory <= 0 or product.inventory - quantity < 0: print('There is no inventory to fill this request') return Response({'status': 'out of stock'}) here what I have tried so far but it does not working I did request.data, self.kwargs.get() with these it also did not work. Any idea plz? -
How does the requests object find the username associated with a particular token passed through Django REST Framework TokenAuthentication
I am using the TokenAuthentication provided by Django REST Framework and following this article https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html When sending the token in the header, I am not specifying the user for which I generated the token but it is automatically picking the right user. I am wondering how is that working? This is the call I am making (Notice I only pass the token and not the username associated with the token) r = requests.post(url, headers={Authentication: 'Token my_token'}, data=data) I am creating the token using the manage.py command passing a particular username. -
Filter objects if one to many relationship not exists
I have two models: ModelA: id = models.AutoField(primary_key=True) ModelB: id = models.AutoField(primary_key=True) titlecomponent = models.ForeignKey('ModelA',on_delete=models.PROTECT) How can i get all objects of ModelA which have not any record relationsip in ModelB. -
django 1.0.4 current transaction is aborted, commands ignored until end of transaction block
I work with Django 1.0.4 and Python 2.7 - yes, I know, the old version. I wanted to import the database from the production environment. I got an error: InternalError at / current transaction is aborted, commands ignored until end of transaction block I tried solution from: https://forums.wikitechy.com/question/djangopostgres-current-transaction-is-aborted-commands-ignored-until-end-of-transaction-block/ but without success. -
Problem with domain in vagrant + ansible, trying with example.com and getting example.local instead
i have serious problems provisioning and configuring a django web server (with nginx) with vagrant + ansible, everything is ok except one thin, i'm trying to setup a domain 'example.com' to run tests with google oauth but every aproach i do ends up only working in 'example.local', i have no references in all my config files to that .local, is some kind of default or something? what am i missing? im also trying to mount it on a fixed ip with no success. This is my vagrant setup: Vagrant.configure(2) do |config| config.vm.box = "ubuntu/bionic64" config.ssh.forward_agent = false config.vm.define "example.com", primary: true do |app| app.vm.hostname = "example.com" app.vm.network "private_network", type: "dhcp" end config.vm.provider "virtualbox" do |vb| vb.customize ["modifyvm", :id, "--name", "example", "--memory", "1024"] end config.vm.provision "ansible" do |ansible| ansible.playbook = "vagrant.yml" ansible.host_key_checking = false ansible.verbose = "vv" end end Also i looked up on the guest machien created with vagrant ssh, and looked into nginx sites-enabled and in hte config the setup is correct with example.com domain on it Part of example nginx config: server { listen 80; server_name example.com; rewrite ^ https://$server_name$request_uri? permanent; } server { listen 443 ssl; server_name example.com; ssl_certificate /etc/ssl/example.crt; ssl_certificate_key /etc/ssl/example.key; ssl_protocols TLSv1.2; } -
How to query a django model by shared values
I have a django model for user accounts, with a foreign key for user and a choice field for account type. It looks a bit like this: class Account(models.Model): user = models.ForeignKey(User) account_type = ChoiceField(models.TextField( choices=zip(ACCOUNT_TYPES, ACCOUNT_TYPES) ) I now want to add uniqueness to the model so each user can only have one account of each type, so I have added a unique_together in the meta with user and account type. Unfortunately this model is quite old and already has a huge table, so I need to find duplicated objects (duplicated in that there is more than one object with the same user-account_type combo) so i can do something with them. My question is - how can i query the Account table to find all the duplicated instances? I want something like "Give me all objects where the user and account type is the same as the user and account type of any other object." -
Loading in static files from S3 using django storages - Failed to construct worker error
I'm currently trying to run potree (see http://potree.org/index.html) on an EC2 instance. The EC2 instance was created with elastic beanstalk and my static files are loaded in from a S3 bucket. All of my JS and CSS etc seems to load fine but I'm constantly getting an error in the developer console in chrome and the pointclouds I'm trying to load do not work correctly. The error I'm consistently encountering is: potree.js:2542 Uncaught DOMException: Failed to construct 'Worker': Script at 'https://MYS3BUCKET.s3.amazonaws.com/libs/potree/workers/BinaryDecoderWorker.js' cannot be accessed from origin 'http://MYURL.eu-west-2.elasticbeanstalk.com'. at WorkerPool.getWorker (https://MYS3BUCKET.s3.amazonaws.com/libs/potree/potree.js:2542:17) at BinaryLoader.parse (https://MYS3BUCKET.s3.amazonaws.com/libs/potree/potree.js:4305:34) at XMLHttpRequest.xhr.onreadystatechange (MYS3BUCKET.s3.amazonaws.com/libs/potree/potree.js:4282:11) After reading around I thought it might be a CORS issue so my S3 bucket is currently setup with the following CORS configuration and is set to public: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> However I have also tried it with the CORS setting: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://MYURL.eu-west-2.elasticbeanstalk.com*</AllowedOrigin> <AllowedMethod>HEAD</AllowedMethod> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <ExposeHeader>ETag</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Any help would be greatly appreciated. -
Serving Django using Azure Functions
I have been trying to find ways to run Django on a Serverless environment on Azure Functions. Assuming the constraint that I can only use Azure services, I want to make sure that the Django code that we will write should be portable(can be deployed anywhere else). I have been trying a couple of methods including Python on Azure: Part 4—Running serverless Django and the Serverless Framework, still, I am not able to get the environment running error-free. I wanted to be sure that even if someone has a working idea on running Django serverless and some guidance towards a good resource? -
Is there a way to create a unique id over 2 fields?
Here is my model: class GroupedModels(models.Model): other_model_one = models.ForeignKey('app.other_model') other_model_two = models.ForeignKey('app.other_model') Essentially, what I want is is for other_model to be unique in this table. That means that if there is a record where other_model_one id is 123, I should not allow another record to be created with other_model_two id as 123. I can override save I guess but I was wondering if django has something built in. -
Docker application timing out in browser
I have a Django application that I'm running in a Docker container. I have changed nothing since the last time I built this exact container. When I start running the Docker, it builds and runs just fine. I don't see any error messages or issues in the log, just the normal start up signs. [2019-10-23 13:30:08 +0000] [16] [INFO] Starting gunicorn 19.3.0 [2019-10-23 13:30:08 +0000] [16] [INFO] Listening at: http://0.0.0.0:1234 (16) [2019-10-23 13:30:08 +0000] [16] [INFO] Using worker: sync [2019-10-23 13:30:08 +0000] [19] [INFO] Booting worker with pid: 19 [2019-10-23 13:30:08 +0000] [20] [INFO] Booting worker with pid: 20 [2019-10-23 13:30:08 +0000] [21] [INFO] Booting worker with pid: 21 However, when I go to localhost:1234 in my browser (which I have done every other time I built this Docker) it gives me the spinning wheel of death before eventually giving me a timeout error. I don't understand A) Why it isn't working in the browser and B) Why it suddenly isn't working when I haven't changed anything? I'm looking for some advice on how I can diagnose and repair the issue. It does connect to an outside source (Elasticsearch) which was down yesterday when I first saw this issue, but … -
Unable to load static files in Django Production
I am trying to run the app with DEBUG=False Below is my setting file configuration BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static/")] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') After running python manage.py collectstatic, all the static files in the app path are copied to staticfiles directory (mentioned in STATIC_ROOT path). When loading the webpage, the static files are failed to get load. Error message: GET /static/dist/bootstrap-4.0.0-dist/js/bootstrap.min.14d449eb8876.js HTTP/1.1" 404 77 GET /static/dist/bootstrap-select/js/bootstrap-select.min.31f649694651.js HTTP/1.1" 404 77 GET /static/js/base.1332bbb46ac5.js HTTP/1.1" 404 77 GET /static/crsummary/dist/amcharts4/core.ea1ec0eb6727.js HTTP/1.1" 404 77 Looking at the error message, apps is trying to load the bootstrap.min.14d449eb8876.js from path /static/*/* but the actual file location is staticfiles/*/* I am not sure what configuration that I have missed out here. Please help -
Issue with django rest framework while handling url-encoded data
I am building a REST API server that handles POST requests. The content type in the request is "application/x-www-form-urlencoded".In the request body, we are sending "data1" (some string) and "image" ( a file) Here's the sample inputForm code I have: from django import forms class RequestForm(forms.Form): data1= forms.CharField(label='data1',max_length=10000) image = forms.ImageField() I then validate the content in the form request: if request.method == 'POST': form = RequestForm(request.POST) print("Form content: {0}".format(form)) if form.is_valid(): print("Works") else: print("Issue") Now, when I send the above mentioned data, I always get an error. It prints "Issue". In addition, the line taht prints form content shows it as an error. Something like: <ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="data1" maxlength="10000" One interesting point: if I remove "Content-type" from the request header, it works. Any inputs on how I can read the form data correctly when we use content type as application/x-www-form-urlencoded. thanks in advance... -
Working with timezone in Django - Best Practices
I would like your opinion about the practices I am using to deal with timezone, as shown below. Is correct? Should I worry about any more details? Each client/user of the system is located in a region with different time, so I put in the model the record that identifies the region: In model: TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) timezone = models.CharField ( null = False, blank = False, max_length = 32, choices = TIMEZONES, default = 'UTC', verbose_name = "timezone", help_text = "Timezone" ) When the user logs in, the settings.py TIME_ZONE variable changes according to the logged-in user's timezone: At login: settings.TIME_ZONE = timezone When I do a cursor query, I timezone as it is in settings.py: In the query: timezone = settings.TIME_ZONE query = "" " SET TIMEZONE = '{}'; ... "" ".format (timezone) In templates, I enable timezone: In the templates: ... {% load tz%} ... {% localtime on%} ... {% endlocaltime%} I hope I was clear in the presentation above. If you need more details, I can provide. Thanks for sharing your experiences. -
How can I modify the Sidebar AWX admin template in django?
home picture How can I modify the Sidebar : Tableaux de bord Jobs planning ... -
Use signal function to create Profile object upon creation of User object
I am a following a tutorial on Django and have the following models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics') def __str__(self): return f"{self.user.username} Profile" Upon creation of a User object I am trying to use signals to create a Profile object. I have created a signals.py file in my app directory: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile #Run this function every time a User is created @receiver(post_save, sender = User) def create_profile(sender, instance, created, **kwargs): if created: #if User was created Profile.objects.create(user = instance) @receiver(post_save, sender = User) def save_profile(sender, instance, **kwargs): instance.profile.save() and have imported the signals within the ready method of apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' # To make signals work you have to import your signals # inside the ready method of our apps.py module def ready(self): import users.signals However, upon the creation of a new User there is still no associated Profile object. Any idea why this is not working?