Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
modelForm instance not coming through
I'm passing an instance of a model into a modelForm, but, within the view, when I print the form, the values within the model don't show up. Also, when the form is rendered on my template, the values from the instance don't show up. Views.py def support_ticket_view(request, id=None): id = int(id) instance = SupportTicket.objects.get(id=id, user=user) form = SupportTicketEditForm(request.POST or None, request.FILES or None, instance=instance) context = { 'form': form, } return render(request, 'accounts/support_ticket_view.html', context) forms.py class SupportTicketEditForm (forms.ModelForm): def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance',None) super(SupportTicketEditForm, self).__init__(*args, **kwargs) class Meta: model = SupportTicket fields = ( 'image', 'body_question', 'urgency', 'question_type', 'status', ) widgets = { 'image': ImageThumbnailFileInput } models.py class SupportTicket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.TextField(max_length=10000, null=True, blank=False) def __str__(self): return self.user.username -
Shuffle "PASSWORD-HASHERS" every hour Django
Im trying to make a website with Django, and what i saw that if you change the default django hasher, it will automatically change it for the user who logs in too. For example, you have an user password encoded with Bcrypt, and you change in Django settings file the hasher with Argon. Next time the user logs in, Django will automatically change the password encriptaion with Argon. Basically what i want to do is change the hasher automatically every hour. I tried with threads but the only problem is that i need to restart the server to apply the new hasher. PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', ] def randomizeHasher(): global PASSWORD_HASHERS while(True): hasher = PASSWORD_HASHERS random.shuffle(hasher) PASSWORD_HASHERS = hasher time.sleep(20) t = threading.Timer(0,randomizeHasher) t.start() -
Django "Forbidden (CSRF cookie not set.)" on localhost:8000
I have a Django app running locally on 127.0.0.1:8000. When I access it via 127.0.0.1:8000 on my browser, everything is fine. However, when I access it via localhost:8000, CSRF errors occur : I think it is due to an AJAX POST request not properly sending the csrftoken cookie. On the same HTML page, I have two actions that submit POST requests : one with an html form using the Django template tag {% csrf_token %} (that one works perfectly well) another one that uses the Fetch API (AJAX) to submit a POST request to a view in my Django app that sends back a JSON (note that I am not using django-rest-framework), and this one doesn't work. The fetch request looks like this : const csrftoken = getCookie('csrftoken'); fetch(route, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, credentials: 'include', body: JSON.stringify(reqBody) }).then(...) But my view returns a Forbidden (CSRF cookie not set.) error when I make that request. If I add a @csrf_exempt decorator (which removes the error, but I don't want to deactivate CSRF permanently) to it and print request.META.get("CSRF_COOKIE"), request.META.get("HTTP_X_CSRFTOKEN") and request.META.get("HTTP_COOKIE"), this is what I obtain : CSRF_COOKIE: None HTTP_X_CSRFTOKEN: cdd9hIG22C39heME5aUvBU8VfB9hpnnvf8TWLYMQBJsS8jqoPh0ErA7iq1fdHSt2 HTTP_COOKIE: isNotIncognito=true; … -
Django - How to edit specific row in database based on multiple fields?
So, I'm fairly new to this and haven't had time to sit down and do proper learning. What I'm trying to eventually achieve is modifying a timestamp that is initially NULL to the current time, based on employee # and work area. The idea behind this, is a "check-in/check-out" system. First the user enters # and work area and when they "Enter", an entry is created in the database with the #, work area, time in, and a "time out" that is set to NULL. Once they're done, they'd just enter their # again, work area, and "Leave" and this should look for the last entry with NULL in time out, and same # and work area and update the time out to the new timestamp. In the case this doesn't exist then it would create a new entry but alert the user. forms.py class WarehouseForm(forms.Form): class Meta: model = EmployeeWorkAreaLog fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, … -
DataTables: Howto send Checkbox selection items by email
I have a Table. I can select items from the table by using DataTables, and Checkbox selection. My aim is to make a selection and send an email with the id of the selected items. Each item in the Table has an unique reference, accessible through a button in the table with reference: href="{% url 'person-detail' object.person_detail_uid %}" In my initial try, I created a "Send Button" for each item, linking to: href="{% url 'person-send' object.person_detail_uid %}", but it looks horrible when scaling it up, instead I would like to select those items to send and have one send button instead. How do I do that? Many thanks for input. URLs and Product Send looks like this: path('person/<uuid:slug>/send/', send_person, name='person-send'), def send_person(request, slug): slug_field = 'person_detail_uid' subject = "Hello" message = f'website/person/{slug}/' send_mail_from = 'nnnnnn@nnnnnn.nnn' recipients = ['nnnnnn@nnnnnn.nnn'] send_mail(subject, message, send_mail_from, recipients) return HttpResponseRedirect('/person/list') -
Displaying the next form below the previous one only once validated
I am experienced in Python, but I'm quite new to Django. So I apologize in advance if the answer to my question is quite obvious. That being said, I couldn't figure out how to make the below work after several days. I have a set of 20 questions which can be either of type: 1. forms.CheckboxSelectMultiple 2. forms.RadioSelect 3. forms.TextInput What I am aiming for is that as soon as the user submits the answer to the first question, the second question displays just below (the first question turning into read only)... an so on until the user reaches the last question where he gets redirected to a page with the answers. So far, what I have been able to achieve is to have all questions displayed all thogether with a "Validate" button at the bottom (redirecting to the answer page). I would gratefully accept any lead or piece of advice. Thanks. Eric -
How to install django-wkhtmltopdf in Pythonanywhere.?
How to install django-wkhtmltopdf in pythonanywhere.? When I try to install with pip3. It’s already satisfying When I run the project its server error (500) Bash Console Requirement already satisfied: django-wkhtmltopdf in ./.local/lib/python3.7/site-packages (3.2.0) Server Error Log FileNotFoundError: [Errno 2] No such file or directory: 'wkhtmltopdf': 'wkhtmltopdf' Can wkhtmltopdf be installed on Pythonanywhere? When I choose an AWS server, do I face a similar problem? Do AWS support wkhtmltopdf.? How to solve this.? My entire project depends on the PDF reports -
sorting a query set after a for loop on it
I want to apply a method on all of the objects in a query set and then sort them. for product in products: product.update_exist_flag() products = products.order_by('-exist_flag') it raises this error: AssertionError: Cannot reorder a query once a slice has been taken. how can I fix it? -
Linking my Django docker container to a postgres container
I create a django docker application image. in my django app, in settings.py DATABASE entry is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cath_local', 'USER': 'postgres', 'PASSWORD': 'mypass', 'HOST': 'postgres', 'PORT': '5432', 'OPTIONS': { 'client_encoding': 'UTF8', }, } } well, at this point i create my docker image using docker build command; all done. Before running my django app docker image i run: docker run -it postgres image is downloaded and container start correctly but when i run my django app docker run -it cath2019/cathedral_studio:latest but wher python manage.py runserver command into my Dockerfile start i get this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name does not resolve here my app Dockerfile: FROM python:3.6-alpine RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev #RUN apk update && apk add build-essential libssl-dev libffi-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 How can i connect into my django settings DATABASE to running postgres container? So many thanks in advance -
Table as field in model
I have such models: class Department(models.Model): name = models.CharField(max_length=30) schedule = models.ForeignKey('Schedule', on_delete=models.CASCADE) class Schedule(models.Model): post_name = models.CharField(max_length=30) shift_start = models.TimeField(auto_now=False, auto_now_add=False) shift_end = models.TimeField(auto_now=False, auto_now_add=False) Each department have a schedule - some [post_name, shift_start, shift_end] lines for each post. If use ForeignKey there will be only one line instead of a list. Is it possible to create some Schedule tables and link each with certain Department? -
I need to develop a page for displaying data by bank branches
I am new on django. I need an advice. How can I: • develop a structure and create a database of data by bank departments, • develop a web page for displaying data by department with the ability to filter, show / hide certain data, charts, color codes I finished the documentation of django. Dont link me there, please. I know the models and can create database and play with it on a server side. But how can I actually display it on web-page?