Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Run a function (view) with a "request" argument from another function (view)?
How run this function (view) in views.py from other function(view)? I want follow to DRY conception. def add_many_rows(request): if request.method == 'POST': data = json.loads(request.body) for row in data: something = Something(name=row['name']) something.save() return HttpResponse("OK") My problem is argument (request). What should I pass in the argument to call this function FROM ANOTHER FUNCTION (instead of calling from the HTML page). I would like something like that: def other_view_function(request): ... add_many_rows(magic_argument_for_my_dumb_tasks) ... return redirect('row_list') -
How do I filter a Django Queryset by removing results in which another model has a ForeignKey relationship?
With the following models.py ... from django.db import models class Notebook(models.Model): name = models.CharField(max_length=255) class Entry(models.Model): notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE) name = models.CharField(max_length=255) How would I write a filter to only return Notebook that have no Entry? -
Django 'AnonymousUser' object has no attribute '_meta' login function doesn't work properly
{% extends 'toDo/base.html' %} {% block content %} <h1>Log In</h1> <h4>{{error}}</h4> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Log In</button> </form> {% endblock %} Thats template def log_in_user(request): if request.method == 'GET': return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm(), "error": "Incorrect username or password. Try again."}) else: login(request, user) return redirect('currentTodos') That's my function that should login user and redirect him to succes page. However it only works for superuser. If i try to login as user with no staff premissions i get and error message i created return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm(), "error": "Incorrect username or password. Try again."}) I've already tried writing it like this but it doesn't change anything: from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials I also tried adding backed=... to login function. Nothing works Please help. -
Avoiding the "Two event loops are trying to receive() on one channel layer at once!" error with Django Channels
In short: I am trying to make Django-channels consumers communicate with a separate logic thread. Regardless of what I ask below, there might be a better-suited option I need to consider besides Django-Channels. My goals are: I want to start logic thread programmatically, this is why Django-Channels worker threads do not really work for me. I want the logic thread to be able to send data to consumers I want consumers to be able to send data to the logic thread I do not want to handle game logic in a (for example) "host" consumer, as the game will crash if the host has to reconnect their websocket Longer version: Let's say I am trying to make a simple game on a website, which uses websockets to communicate between the front- and backend. using Django Channels, this could be very easily set up. However, when I need to handle game logic, I want to compute it in some central thread that does not cease whenever a client disconnects. I have found that you can communicate with consumers from some arbitrary thread from outside the consumer scope here. However, this has an issue: The game logic can send information to clients … -
Dockerfile for golang and python
There is a django project already running. Now Inside the code, I need to execute the following command in the subprocess module: cmd = f's5cmd cp {obj1} {obj2}' Now locally this code is running fine. But after deploying the code it is unable to find s5cmd. According to s5cmd documentation it is written in golang and on my system it is installed that's why it is working fine. So i updated the dockerfile but still its not working. FROM python:3.6 COPY ./requirements.txt /tmp/requirements.txt RUN pip install --no-cache-dir -r /tmp/requirements.txt COPY . /apps/project/ WORKDIR /apps/project/project/ EXPOSE 8000 CMD gunicorn project.wsgi:application --timeout 3000 --access-logfile '-' -w 3 -k gevent --bind=0.0.0.0:8000 This dockerfile is working. Now the updated dockerfile looks like this but its not working i.e the s5cmd command is not working with docker. FROM python:3.6.7-alpine3.6 # author of file LABEL maintainer="Baktawar" # Install native libraries, required for numpy RUN apk --no-cache add musl-dev linux-headers g++ RUN apk add --no-cache --virtual .build-deps bash gcc musl-dev openssl go RUN apk update && apk add ca-certificates wget && update-ca-certificates RUN wget -O go.tgz https://golang.org/dl/go1.15.2.src.tar.gz RUN tar -C /usr/local -xzf go.tgz RUN cd /usr/local/go/src/ RUN ./make.bash RUN export PATH="/usr/local/go/bin:$PATH" RUN export GOPATH=/opt/go/ RUN export PATH=$PATH:$GOPATH/bin … -
form.ValidationError is not showing in template
I'm new to Django so excuse some errors. I'm trying to create validation system for email and print those errors, if any, to the template. Just to make clear, I'm able to create new user and redirect to login page, I just can't display error messages. I do apologize if this is trivial question, but I'm kinda stuck on this for 2 days. I have tried this video on youtube: and i have tried to follow this post and it didn't work. forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms # This class will overwrite origginal UserCreationForm0 class CreateUserForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User # this will add email to our register_form fields = [ 'username', 'email', 'password1', 'password2' ] def clean(self): cleaned_data = super(CreateUserForm, self).clean() email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('User with same email already exists') return cleaned_data views.py from django.shortcuts import render, redirect from .forms import CreateUserForm from django.contrib.auth import login, authenticate, logout from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages # Create your views here. def registration_page(request): if request.user.is_authenticated: return redirect('') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) … -
Django {% url %} inside React component
I am trying to use the Django {% URL %} tag inside a React component. For some reason, URLs without arguments work just fine. However, as soon as I try to pass an argument to the tag the following error appears: Reverse for 'expression' with arguments '('',)' not found. 1 pattern(s) tried: ['en/define/(?P[-a-zA-Z0-9_]+)$'] Here is my React code: class Definition extends React.Component { render() { const definition = this.props.definition; const expression = definition.expression; return ( <a href="{% url 'dictionary:expression' expression.slug %}"> {expression.expression}: {definition.definition} </a> ); } } Here is the URL_patterns for my app called "dictionary": path("define/<slug:slug>", dictionary_views.ExpressionView.as_view(), name="expression") Why doesn't React accept {% url 'dictionary:expression' expression.slug %}? -
I have a foreign key relationship between two ModelChoiceField
I have a foreign key relationship between two ModelChoiceField. How do I make sure that when the user selects an option, the associated options are listed in the other ModelChoiceField. -
django : how can I create the admin?
I am trying to follow django's tutorial on how to create a poll but I cannot create a super user such as python manage.py createsuperuser. Trying to execute the command only gives the following error django.db.utils.OperationalError: no such table: auth_user and connecting to the admin page ( the default http://127.0.0.1:8000/admin ) also gives the same error when inputting a random user name and password. Isn't the instruction supposed to create the table ? I saw nothing in the tutorial about creating that table manually. -
Django Mysql database
So today is my first time connecting my django project to a mysql database. I followed some instructions I saw on the web to do so. When I ran "py manage.py migrate" my cmd said wheel not installed. So I installed it which was a pain finding the right one to install. So after that I ran the command again but my cmd says mysqldb module not found. Right now when I run that command in my venv again this is what shows: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n"). -
Django form not using function parameters correctly
Im redirect to a page with a form on where the user can upload an image and comment but I keep getting errors. I'm trying to make it so that the forbrief field automatically gets via the pk when this function was called. models.py class Designs(models.Model): forbrief = models.ForeignKey(Brief, on_delete=CASCADE) description = models.CharField(max_length=200) postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True) design = models.ImageField(null=True) date = models.DateTimeField(auto_now=True, blank=True) forms.py class ImageForm(forms.ModelForm): class Meta: model = Designs fields = ['description', "design",] Views.py def designUpload(request, pk): render(request, "users/upload_design_page.html") if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.instance.forbrief = pk form.save() return render(request, 'users/upload_design_page.html') else: form = ImageForm() return render(request, 'users/upload_design_page.html', { 'form': form }) HTML {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} -
Set instances of a Form without the User input
I am trying to set an instance of a Modelform that render through ListView. Program Model: class Program(models.Model): patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0) program_name = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted) def get_absolute_url(self): return reverse('program-detail', kwargs={'pk': self.pk}) Exercise Model: class Exercise(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=1000, default="") description = models.TextField(default="") load_share = models.TextField(default="") breath_method = models.TextField(default="") recovery_method = models.TextField(default="") measure_method = models.TextField(default="") notes = models.TextField(default="") extra_info = models.TextField(default="") reps = models.PositiveSmallIntegerField(default=0) sets = models.PositiveSmallIntegerField(default=0) def __str__(self): return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted) Data Model: exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0") set_number = models.PositiveSmallIntegerField(default=0) spo2 = models.PositiveSmallIntegerField(default=0) hr = models.PositiveSmallIntegerField(default=0) physical_level = models.PositiveSmallIntegerField(default=0) breath_level = models.PositiveSmallIntegerField(default=0) sys = models.PositiveSmallIntegerField(default=0) dia = models.PositiveSmallIntegerField(default=0) misc_input = models.PositiveSmallIntegerField(default=0) def __str__(self): return self.exercise.name My Exercise listView include the Data form that the User need to fill up, It is paginated to 1 exercise per page. Exercise ListView: # Exercise list inside each program + Data form class ExerciseListView(LoginRequiredMixin, FormMixin, ListView): model … -
Save a History of person in DB with Django
I'm developing something and I'm having difficulty with a part of the Model, I registered a customer and within this customer, I would like to register customer history information (registered manually), where there will be only 1 text field (unique, because each user has its own history). A story cannot be shown on another customer. When accessing the customers page, inside it will have several customers, when entering the specific customer page, I want to be able to insert a customer information, and in that information, I would like to click "add" and it will go to the bottom of the site, thus recording a 'customer history', this can be done several times, as more than one comment can be made to the customer. How to do this with 'models'? Because I would like to save everything in a database, so I don't have a chance to lose any information. -
Inserting a 'hidden timestamp field' in a modelform?
I have a simple form that allows a user to create a post. The fields are post_title, post_content, post_date. The post_title and post_content will be provided by the user, however the post_date will be autogenerated by the system and will give the current timestamp. Due to this, I will only show both title and content in the form. When I try and submit a request however, this gives me an IntegrityError saying NOT NULL constraint failed: main_app_post.post_date. I am fairly new at Django so I really have no idea what to do. I want it that whenever the user sends a Post request (and if it passes the validations), it will generate the current timestamp to post_date before saving it to the database. Any advices in regards of this? Thanks a lot! models.py: class Post(models.Model): post_title = models.CharField(max_length=100) post_content = models.TextField(max_length=400) post_date = models.DateTimeField() def __str__(self): return self.post_title forms.py: class PostForm(forms.ModelForm): class Meta: model = models.Post fields = ('post_title', 'post_content') views.py: if request.method == 'POST': form = forms.PostForm(request.POST) if form.is_valid(): post_title = form.cleaned_data['post_title'] post_content = form.cleaned_data['post_content'] post_date = datetime.datetime.now().timestamp() form.post_date = post_date form.save(commit=True) -
How can I return an array of objects instead of an array of arrays in Django Rest Framework?
I am trying to display all doctors that work at a certain clinic as an array of objects instead of an array of arrays. http://localhost:8000/api/clinic/ results [ { "id": 1, "doctors": [["Henry", "Ford", 20], ["Elon", "Musk", 30]] // get array of objects instead "name": "Clinic number 1", }, ... ] This how I implemented my models, serializers and viewsets: class Clinic(models.Model): name = models.CharField(max_length=200) class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctors") class ClinicSerializer(serializers.ModelSerializer): doctors = serializers.SerializerMethodField() class Meta: model = Clinic fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' class ClinicViewset(viewsets.ModelViewSet): queryset = Clinic.objects.all() serializer_class = ClinicSerializer class DoctorViewset(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
Django authetication problem, wrong error message
My sign up form works fine but when I type the Your username and password didn't match. Please try again. I want it to say something like 'try a stronger password' my sign up view def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() email = form.cleaned_data.get('email') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'registration/signup.html', { 'form': form }) -
ERR_HTTP2_PROTOCOL_ERROR loading admin pages in Django
I've started to get errors loading some pages in Django admin (with Grappelli): net::ERR_HTTP2_PROTOCOL_ERROR 200 It appears in chromium browsers console. These pages never load. For some time firefox has served this pages well, but today I've got the admin page which has been loaded partially, disrupted in the middle of inline forms, with this in the console: Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content. I'm not even sure if the problem is with Django, because everything is ok on the dev server and the problem occurs with the production server (Nginx). I've already tried solutions from here with no result. But since the problem somehow connected with Django admin pages, how can I investigate it? -
format django current time and 7 days back time
Here i have piece of django python code. I am trying to get current time 7 days back time. But unfortunately both time formats are not matching so the api is not accepting seven_days_back_date date. I don't wants to replace anything looking for some efficient way. from datetime import datetime from django.utils import timezone now = f"{datetime.utcnow().isoformat()}Z" profile = Profile.objects.get(id=profile_id) last_updated_date = profile.data_last_updated seven_days_back_date = last_updated_date - timezone.timedelta(days=7) seven_days_back_date = f"{seven_days_back_date.isoformat()}Z" print(now) print(seven_days_back_date) Result i am getting: 2020-09-21T16:16:30.753375Z 2020-09-14T16:16:04.042587+00:00Z expecting: 2020-09-21T16:16:30.753375Z 2020-09-14T16:16:04.042587Z Please have a look -
Custom systemd service to run Gunicorn not working
I am trying to deploy my Django website to a Ubuntu server. I am following this tutorial: linuxhint.com/create_django_app_ubuntu/. However, the Gunicorn service doesn't work. I have my site at /home/django/blog. My Python 3.6 virtualenv is activated at /home/django/.venv/bin/activate (-rwxr-xr-x 1 django root 2207 Sep 21 14:07 activate). The script for starting the server is at /home/django/bin/start-server.sh (-rwxr-xr-x 1 django root 69 Sep 21 15:50 start-server.sh), with the following content: cd /home/django source .venv/bin/activate cd blog gunicorn blog.wsgi Running this script manually works just fine. The Gunicorn service is at /etc/systemd/system/gunicorn.service, with this content: [Unit] Description=Gunicorn After=network.target [Service] Type=simple User=django ExecStart=/home/django/bin/start-server.sh Restart=on-failure [Install] WantedBy=multi-user.target Running 'systemctl status gunicorn.service' gives this: ● gunicorn.service - Gunicorn Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-09-21 16:15:17 UTC; 6s ago Process: 1114 ExecStart=/home/django/bin/start-server.sh (code=exited, status=203/EXEC) Main PID: 1114 (code=exited, status=203/EXEC) Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Service hold-off time over, scheduling restart. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Scheduled restart job, restart counter is at 5. Sep 21 16:15:17 example.com systemd[1]: Stopped Gunicorn. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Start request repeated too quickly. Sep 21 16:15:17 example.com systemd[1]: … -
Django rest returning 'token not valid' when using token generated from google and fb api
Calling Facebook endpoint send me this: { "token": "token", "email": "", "username": "" } But whenever I try to use the token to access a view it throws: The error is same when using google api too. { "code": "token_not_valid", "detail": "Given token not valid for any token type", "messages": [ { "message": "Token has no id", "token_type": "access", "token_class": "AccessToken" } ] Am i missing something? -
In DRF how can one properly display the related name field from one model inside another?
I am trying to display all doctors that work at a certain clinic but keep getting clinic.Doctor.None. I'm trying to get a list of the doctors ids or names in there http://localhost:8000/api/clinic/ results [ { "id": 1, "doctors": "clinic.Doctor.None", //how to show list of ids or names here? "name": "Clinic number 1", }, ... ] This how I implemented my models, serializers and viewsets: class Clinic(models.Model): name = models.CharField(max_length=200) class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctors") class ClinicSerializer(serializers.ModelSerializer): doctors = serializers.CharField(read_only=True) class Meta: model = Clinic fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' class ClinicViewset(viewsets.ModelViewSet): queryset = Clinic.objects.all() serializer_class = ClinicSerializer class DoctorViewset(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
How do i compute every Item unitprice multipy by its quantity
I know how to use aggregate and annonate, (a little bit), but what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? I just want to get the total amount of every item, but how do i do that? what should I use? aggregate or annotate? I use aggregate for getting the total amount of all product total = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) and this is my logic on how to get the the total amount of per product total_amount_of_product = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id')).annotate(total_per_item=Sum(F('unitprice') * F('quantity'), output_field=FloatField(),)) item_totals = [item.total_per_item for item in total_amount_of_product] this is the result in my html this is how i print to the html <td class="cart__cell--total"><span class="cart__item-total">₱ {{item_totals}}</span></td> -
UserInfo matching query does not exist.?
I create a django web app. It's a crud project. When i want to login as a admin it show me this message but it's work well when i login as a user. can not figure out where is the problem. Help me to solve this. -
How to clear cache data without delete my session data in Django 2.2.2
I am trying to delete the cache from django in browser without delete the session data of my website. -
Django + React: React "frontend" Django app vs. React scripts embedded in Django templates?
I am trying to understand how to best structure my Django-React project to increase readability and maintainability for the future. As far as I understand there are multiple ways to integrate Django and React. The two options I am considering for my project are: Creating a big "frontend" Django app where all the HTML will be managed through a React app. Embedding smaller React scripts in Django templates and use Django as the main vehicle to manage HTML. Which alternative would be better for what particular context and why?