Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form.is_valid() return flase all time
the function form.is_valid() return flase all time and i dont understand why. pliz help meץ Thanks for all the answers. views.py views.py html file html file -
How to edit ManyToManyField in model's save() method?
I have a method which has a required field for the author and a non-required field for co-authors. Sometimes the person which creates the post unintentionally, or because of the lack of knowledge, selects his/her own profile as a co-author. I would like to remove the actual author from the co-authors, and I think the best way to do it is overriding model's save() method. Here's what I have so far, but it doesn't seem to work. models.py from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ User = get_user_model() class Post(models.Model): PUBLICATION_STATUS_CHOICES = [ ("PUBLIC", _("public")), ("PRIVATE", _("private")), ("DRAFT", _("draft")), ] title = models.CharField(max_length=100, verbose_name=_("post title")) summary = models.CharField(max_length=250, verbose_name=_("post summary")) content = models.TextField(verbose_name=_("post content")) is_markdown = models.BooleanField(default=True, verbose_name=_("Markdown"), help_text=_("Is this a post written in Markdown format?")) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts", verbose_name=_("author of the post")) coauthors = models.ManyToManyField(User, blank=True, related_name="colab_posts", verbose_name=_("colaborators / co-authors")) date_created = models.DateTimeField(default=now, verbose_name=_("date of creation")) date_updated = models.DateTimeField(default=now, verbose_name=_("last update")) status = models.CharField(max_length=10, choices=PUBLICATION_STATUS_CHOICES, default=PUBLICATION_STATUS_CHOICES[0][0], verbose_name=_("post status")) slug = models.SlugField(unique=True, verbose_name=_("slug")) class Meta: ordering = ["-date_created"] verbose_name = _("post") verbose_name_plural = _("posts") def __str__(self): return f"{self.title} ← {self.author} ({self.date_created.strftime('%Y-%m-%d %H:%M:%S')})" def … -
How can I change the default register mutation in django-graphql-auth?
I want to change the fields of register mutation for example I want to ask for the password only once , and also I want do add extra fields like first_name , last_name, date_of_birth ... all of that , but still I want to beneficiate the use of the email verification and all the good parts that djang-graphql-auth brings . So here is what I have right now : A custom user (I only want the user to login using the email) : from django.db import models from django.contrib.auth.models import AbstractUser class ExtendUser(AbstractUser): email = models.EmailField(blank=False, max_length=255, unique=True, verbose_name="email") date_of_birth = models.DateField(blank=False, null=True, verbose_name="date_of_birth") # phone = # country = city = models.CharField(blank=True, max_length=150, verbose_name="city") company_name = models.CharField(blank=False, max_length=150, verbose_name="company_name") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # USERNAME_FIELD = "username" EMAIL_FIELD = "email In my schema.py I have the following : import graphene from graphene_django import DjangoObjectType from .models import ExtendUser from graphql_auth import mutations from graphql_auth.schema import UserQuery, MeQuery class UserType(DjangoObjectType): class Meta: model = ExtendUser fields = ("id", "first_name", "last_name", "email", "date_of_birth", "company_name", "city") class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: first_name = graphene.String(required=True) last_name = graphene.String(required=True) # username = graphene.String(required=True) email = graphene.String(required=True) password = graphene.String(required=True) date_of_birth … -
I am trying to Update my model without a form and show the updated records in a table every time i click on update
I am trying to Update my model and show the updated record in a table every time i click on update. ERROR Reverse for 'subt' with arguments '('',)' not found. 1 pattern(s) tried: ['subt/(?P[0-9]+)$'] Views.py def subs(request, pk): sw = get_object_or_404(Swimmers,id=pk).sessions sw_list = sw sw_lists = sw + 1 context = {'sw_lists':sw_lists} return render(request, 'accounts/modals/swimming/vw_more.html', context) Models.py class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.CharField(max_length=200, blank=False ) dateofpayment = models.CharField(max_length=200, blank=False) phone = models.CharField(max_length=30, blank=False, null=True) date_from = models.DateField(null=True) date_to = models.DateField(null=True) type_choice = ( ("basic", "Basic"), ("3x1 week", "3x1 Week"), ("1 session", "1 Session"), ("2x1", "2x1"), ) type = models.CharField(max_length=200, blank=False, null=True, choices=type_choice, default=type_choice) ammount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=True) registration = models.DateField(default=timezone.now) keenphone = models.CharField(max_length=30, blank=False, null=True) def __str__(self): return self.name Urls.py path('swimminglist/', views.SWGIndex.as_view(), name="swimminglist"), path('create/', views.SWGCreateView.as_view(), name='create_swimmer'), path('update/<int:pk>', views.SWGUpdateView.as_view(), name='update_swimmer'), path('read/<int:pk>', views.SWGReadView.as_view(), name='read_swimmer'), path('delete/<int:pk>', views.SWGDeleteView.as_view(), name='delete_swimmer'), path('subt/<int:pk>', views.subs, name='subt'), -
Post an image along with text in django restframework with flutter
I am creating a a b2b ecommerce mobile application. I am using flutter as frontend and django for backend. I am stuck while sending a post request to django server with flutter. The case is I have two types of user. THey are seller and buyer. The seller has to post product in the app. model field for product are title, description, price, image. I created post method in django rest framework and it worked while checking through postman. But i am having hard time sending image through flutter. I searched for many things but couldnot figure out what to do. I found articles and videos posting only image at a time but i want to send image along with other text field. How can i do so?? Help me find a solution. -
Ordering in django/dnf by user?
I have model post with field User (FK), can I order all the posts so that the current user's posts come first? For example in serializer class. Or maybe I should write my own filter? -
Django add chat functionality
Hi guys I am currently working on a Django website in which user can sell their old things. Therefore a want that one user can write the user who is offering the product at the moment. I know my question isn't really precise but could you give me a rough overview on how to implement the peer to peer chat functionality. So far I just found tutorials on how to built chat rooms with multiple users which can join this chat and therefore they mainly used Node.js for example. Thanks for your answers. -
django 2FA with yubikey creates wsgi error in login: Timeout when reading response headers from daemon process
Usual 2FA first requires to type your password and then the yubikey token, either when setting it up or when it is already set. I'm using this code:https://github.com/jazzband/django-two-factor-auth When i have to type the yubikey token, i.e., press the yubikey, the information is sent to the database but in the client side the process is not finished (page doesn't go to the next step and browser shows the loading icon but nothing happens until gateway timeout). Nothing works, what I see is that my mysql processlist goes idle (sleep) after the token is typed so it makes me think that the connection with the database is ok. The same code in my localhost with the lightweight django server works fine but in an apache server I have this issue. How could I track down the problem? the error log only says wsgi error, Timeout when reading response headers from daemon process. In my localhost this step gives a 302 response (it works. I believe 302 response is ok with the yubikey). In the production server is 504 (Gateway timeout). Any helps is appreciated -
Getting "Authentication Credentials Were not Provided" when testing DRF endpoint on Locust
I am trying to load test an endpoint that allows users to create posts using locust, it is worth mentioning that users need to be authenticated before they can access this endpoint. Problem: When I hit the endpoint using locust, I keep getting the error saying "Authentication provided were not provided" even though I have done so and I have also configured my endpoint to accept token (I am using the default DRF token feature). Any idea what I am doing wrong? any help will be appreciated. Below is my code: Locust file class ListPostUser(HttpUser): wait_time = between(1, 5) @task(3) def create_post(self): data = { "title": "This is another random title", "body": "This is the body of a randomly titled post" } headers = { "Authorization": "Token 508e650b0ca1613818939089190a1661a75865b1" } response = self.client.post("blog/create", json=data, headers=headers) print(response) print(response.json()) @task def comment_detail(self): self.client.get("blog/comment/1") @task(2) def post_detail(self): self.client.get("blog/post/1") def on_start(self): self.client.post("login/", json={"username": "username", "password": "mypassword"}) views file class CreatePostAPI(APIView): permission_classes = (IsAuthenticated, ) def post(self, request): serializer = CreatePostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) I should also note that the endpoint works fine on POSTMAN, I only get the error when I am load testing with locust -
Pycharm debugger "waiting for connections" but running still working
I am trying to debug django project with docker-compose interpreter. Here is my pycharm configurations But when I trying to debug it project still running but debugger is still waiting for connection and break point not working I think that structure of my project have problem cause i'm try to debug other project it still working. Here is my project structure What am i doing wrong? -
Define Django models for recipe
So, I need some help to design the models for my project. The project is quite simple, it is a cocktails maker. The idea is to have a model for all the ingredients (Vodka, coke, gin etc.), another model for the Cocktail and a last model with the recipe. How can I add some ingredients and choose their quantity into the Recipe model and then link the Recipe to the Cocktail model? Here is what I have so far, the Ingredient model is working fine, but I'm struggling to design the Cocktail & Recipe model and choose their relationship. class Ingredient(models.Model): name = models.CharField(null=False, blank=False, unique=True, max_length=100, validators=[MinLengthValidator(3)]) price = models.FloatField(null=False, blank=False) is_alcoholic = models.BooleanField(null=False, blank=False) class Cocktail(models.Model): name = models.CharField(max_length=50) price = models.FloatField() description = models.TextField() recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE) class Recipe(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.IntegerField() Any suggestions are more than welcome! -
Try and except for Query set
I want to do something similar to try and except for single object .. in my situation I got a Query set and I want to do something like : try: qs = model.objects.filter(id=1) except qs.DoesNotExist: raise Http_404() How can I do that ? -
Send an email if to a user registering in django when admin changes their account to is_active=True status
I am creating a register and login system in a project whereby on registering a users default is is_active=False. The admin then receives an email on user registering to approve or leave it inactive. on changing users status to is_active=True, the user should receive an email informing them they can now login.But i am not receiving any emails..or emails being sent, is there an error in my codes am failing to see?? Here is my signals.py from .models import AuthUser from django.db.models import signals from django.db import models from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from django.conf import settings from django.core.mail import send_mail #signal used for is_active=False to is_active=True @receiver(pre_save, sender=AuthUser, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and AuthUser.objects.filter(pk=instance.pk, is_active=False).exists(): subject = 'Active account' message = '%s your account is now active' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, [instance.email], fail_silently=False) #signal to send an email to the admin when a user creates a new account @receiver(post_save, sender=AuthUser, dispatch_uid='register') def register(sender, instance, **kwargs): if kwargs.get('created', False): subject = 'Verificatión of the %s account' %(instance.username) message = 'here goes your message to the admin' from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, [from_email], fail_silently=False) -
How do I get my Django AllAuth Templates to work?
I have put them in what I believe is the correct folder and followed all steps from the tutorial (https://www.youtube.com/watch?v=Rpi0Ne1nMdk&list=PLPSM8rIid1a3TkwEmHyDALNuHhqiUiU5A&index=2) but the templates do not appear to be being picked up. Could anyone help? My repository is https://github.com/Westsi/thynkr_python. I am using allauth. -
same user Sending multiple post api request at same time and we are trying to add new data with old data in database
But some how the there is no consistency in output. some time you will see in console there is two consecutive "inside post" and some time some time you will see one time two time consecutive "after save method" printed in console. Data also saved in database there no consistency. One solution I can think of before same user was sending many post request at same time by clicking single button now I am thinking after clicking button first request should go and after frontend got respond second request should send post request and so on. If you have better approach please suggest @csrf_exempt def product_rest(request,pk): product=Product.objects.get(pk=pk) if request.method == "POST": status = True code = 200 message = "" data = [] print("inside post") parsed_data=json.loads(request.body) print("parsing data == ", parsed_data) try: db_time = json.loads(product.time) print("old data ==",db_time) db_time.append(parsed_data) db_time_tostring=json.dumps(db_time) print("after adding data == ", db_time_tostring) product.time=db_time_tostring doctor.save() print(" after save method == ", product.time) message = "Order status created" except: status = False code = 500 message = "Internal server error" return JsonResponse({ "status": status, "code": code, "message": message, "data": data }) -
Can't access UpdateView in Django
My idea is to have Teachers and Students and I want my Teachers to have the ability to edit quizzes for the students for some reason when I try to acces the QuizUpdateView via other ListView it gives me 404 Not Found [screenshot][1] So I want to edit my quiz with this view: class QuizUpdateView(views.UpdateView): model = Quiz fields = ('name', 'subject', ) context_object_name = 'quiz' template_name = 'classroom/quiz_update.html' def get_context_data(self, **kwargs): kwargs['questions'] = self.get_object().questions.annotate(answers_count=Count('answers')) return super().get_context_data(**kwargs) def get_queryset(self): return self.request.user.quizzes.all() def get_success_url(self): return reverse_lazy('quizzes') I have int:pk in my urls.py urlpatterns = ( path('register', RegisterView.as_view(), name='register'), path('register/student', StudentRegisterView.as_view(), name='register student'), path('register/register', TeacherRegisterView.as_view(), name='register teacher'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('quizzes', QuizListView.as_view(), name='quizzes'), path('quiz/create', QuizCreateView.as_view(), name='create quiz'), path('quiz/update/<int:pk>', QuizUpdateView.as_view(), name='update quiz'), ) I have the quiz.pk in templates as well(I tried with quiz.id, same result) {% extends 'base.html' %} {% block page_content %} {% include 'classroom/student_header.html' with active='new' %} <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Quiz</th> <th>Subject</th> <th>Length</th> <th></th> </tr> </thead> <tbody> {% for quiz in quizzes %} <tr> <td class="align-middle">{{ quiz.name }}</td> <td class="align-middle">{{ quiz.subject.get_html_badge }}</td> <td class="align-middle"> questions</td> <td class="text-right"> {% if request.user.type == 'Student' %} <a href="" class="btn btn-primary">Start quiz</a> {% elif request.user.type == 'Teacher' … -
Django app returning 404 error even if urls seem to be correct according to tutorials
I am starting my first django application. I constantly keep getting 404 error after turning on server locally in my computer. I don't see any reason for such return because urls seem to be correct when compared to tutorials and guides on the internet. This is my urls file inside app (app name is reservations) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] This is urls file in project folder (project name is website) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('reservations/', include('reservations.urls')) ] and this is index function which is supposed to show basic html def index(request): response = """<html><body><p>This is home page</p></body></html>""" return HttpResponse(response) I thought that my urls are written incorrectly so i tried writing them in different way but it never worked. Thanks for any help. -
How can I convert inMemoryUploadedFile into string to pass it over an api?
I want to pass user uploaded images into an api form my view How can I convert the inMemoryUploaded file into a string and pass it over an api and convert it back to image? -
How to restrict records to a specific seller in django admin backend
class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField (max_length=50, default='', blank=True) phone = models.CharField (max_length=50, default='', blank=True) date = models.DateField (default=datetime.datetime.today) status = models.BooleanField (default=False) seller = models.CharField(max_length=100, default='', blank=True) How to restrict backend to a specific seller records like 'A Seller Example' -
Pluralize Django message
I have the following code to display a message when a custom action is executed in the Admin site: messages.info(request, '%s posts marked as Draft' % queryset.count()) What is the best way to pluralize that message for when the count is 1 and more than 1? 1 post marked as Draft 3 posts marked as Draft if statement based on queryset.count()? -
Why is the error showing 5 positional arguments while registering the model
I am trying to make a chat application on Django. I have created a model to input into a database of the format room_no, user, message. Additionally, I have included the init function to extract the data from the database in the form of a string so I can display it on the HTML page. Apart from my method, is there another way to do this? If not, could you please explain my error? Models: class chatbox(models.Model): name = models.CharField(max_length=100, blank=False,default='Anonymous') room = models.CharField(max_length=100,blank=True) message = models.CharField(max_length=500000,blank=True) def __init__(self,name,message): self.name = name self.message = message ADMIN admin.site.register(models.chatbox) Error: TypeError at /admin/DjangoChat/chatbox/ chatbox.__init__() takes 3 positional arguments but 5 were given -
dependencies reference nonexistent child node
I tried to dockerize my Wagtail Web Application and this error Occurred. I tried docker-compose build there was no errors. after that i tried docker-compose up then this error occurred I really need help on this error. Error- 49a28e66a331_wagtail_landing_web_1 | django.db.migrations.exceptions.NodeNotFoundError: Migration home.0002_create_homepage dependencies reference nonexistent child node ('wagtailcore', '0053_locale_model') 49a28e66a331_wagtail_landing_web_1 exited with code 1 This is the Dockerfile this is the dockerfile of my wagtail site.I'm very new to wagtail and docker .Please guide me if there is an Error FROM python:3.8.1-slim-buster RUN useradd wagtail EXPOSE 80 ENV PYTHONUNBUFFERED=1 \ PORT=80 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt COPY ./compose/local/web/entrypoint /entrypoint RUN sed -i 's/\r$//g' /entrypoint RUN chmod +x /entrypoint COPY ./compose/local/web/start /start RUN sed -i 's/\r$//g' /start RUN chmod +x /start WORKDIR /app ENTRYPOINT ["/entrypoint"] This is the YAML file This is the yaml file of the System version: "3.7" services: web: build: context: . dockerfile: ./compose/local/web/Dockerfile image: wagtail_bootstrap_blog_web command: /start volumes: - .:/app ports: - 8000:8000 env_file: - ./.env/.dev-sample depends_on: - … -
Update Profile Picture, when profile_photo is a FK at the user model and I want to update the photo from the user's model
In a task I have using DRF, I need to update a user's profile picture and cover picture. Here's a part of my models/users: profile_photo = models.ForeignKey(to=Photo, related_name='profile_photo',on_delete=models.CASCADE, blank=True) cover_photo = models.ForeignKey(to=Photo, related_name='cover_photo', on_delete=models.CASCADE, blank=True) Meanwhile the Photo db table looks something like this: url_path = models.FileField(max_length=300) photo_type = models.ForeignKey(to=PhotoType,on_delete=models.CASCADE) I built the serializer classes like this but cannot seem to figure out how to write the update method to update the profile_picture from the user aspect or create it if the photo instance doesn't exist. class PhotoSerializer(serializers.ModelSerializer): photo_type = serializers.PrimaryKeyRelatedField(queryset=PhotoType.objects.all(), many=False) class Meta: model = Photo fields = ['id', 'url_path', 'photo_type'] class UserPhotoSerializer(serializers.ModelSerializer): profile_photo = PhotoSerializer(many=False) class Meta: model = User fields = ['id','profile_photo'] -
DJANGO JSON filtering complicate key
I am trying to perform a DJANGO filtering logic on this JSON "data": { "process":{ "9123fd-b01-4a00-9arwefg":{ "name":"PROCESS-1", } } Here is currently what I can do: object.filter(data__process={"9123fd-b01-4a00-9arwefg":{"name":"PROCESS-1"}} But in reality, I can only input PROCESS-1 in my filtering input, so I want to do something like this object.filter(data__process__9123fd-b01-4a00-9arwefg__name="PROCESS-1") However, this is obviously not working because of the dash (-) in the key, is there anyway I can do the filtering with this complicate key? -
How use django ORM with Serverless Application Model using AWS ToolKit
I am using AWS Toolkit to create a Serverless Application using SAM. It contains API Gateway over AWS Lambda. I want the Lambda function to be able to access data in Postgres database. In pass I have done this using Django REST Framework. But I don't want the overhead of using the entire DRF as API Gateway is taking care of the need of the REST layer. Our team is pretty well versed with Django ORM and we want to leverage on that knowledge base. Trying to combine AWS Serverless plus Django leads all the google searches to Zappa, but that's not an option for us (let's leave it to that :) ). We want to use the AWS Toolkit + SAM way. Any help would be greatly appreciated.