Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /blog/redirect2
I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match this is my urls.py code : app_name = 'blog' urlpatterns = [ # path('about', views.about, name = 'about'), path('about.html', views.about, name='about'), path('home.html', views.home, name='home'), # path('home', views.home, name ="home") path('redirect', views.redirect_view), path('redirection_fct',views.redirection_fct, name='redir_fct'), #redirection par la fonction as_view path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')), path('redirect2', views.redirect_view1), ] and this is my views file : def about(request): return render(request, 'about.html', {}) def home(request): return render(request, 'home.html', {}) #redirection par HttpResponseRedirect def redirect_view(request): return HttpResponseRedirect("redirection_fct") def redirect_view1(request): return redirect('redir_fct') def redirection_fct(request): return render(request, 'redirection.html', {}) Is there something wrong with my URLs pattern or it is the render one? -
How to check if a relation exists? M2M
I have models: class User(models.Model): ... group = models.ManyToManyField( Group, related_name="users_group", ) class Group(models.Model): .... How to check in serializer is the Group empty (there is no relationship with User) My version is : class GroupSerializer(serializers.ModelSerializer): empty = serializers.SerializerMethodField() class Meta: ... def get_empty(self, obj): return not User.objects.filter(group=obj).exists() But maybe there is an even better way. -
I got an error when installing django-pyqt library
I tried to install the django-pyqt library using the following command PS C:\Windows\system32> py "C:\Users\mehdi\Desktop\myfiles\python\git hub\django-pyqt-master\django-pyqt-master\setup.py" but i got this Error PermissionError: [WinError 5] Access is denied: 'C:\Users\mehdi\.django-pyqt\drivers\etc\hosts' I followed the installation method exactly from the site and I will put the link below https://github.com/ZedObaia/django-pyqt -
Unable to read environment variables in Django using django_configurations package
I was using django-environ to manage env variables, everything was working fine, recently I moved to django-configurations. My settings inherit configurations.Configuration but I am having trouble getting values from .env file. For example, while retrieving DATABASE_NAME it gives the following error: TypeError: object of type 'Value' has no len() I know the below code return's a value.Value instance instead of a string, but I am not sure why is that behaviour. The same is the case with every other env variable: My .env. file is as follows: DEBUG=True DATABASE_NAME='portfolio_v1' SECRET_KEY='your-secrete-key' settings.py file is as follows ... from configurations import Configuration, values DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': values.Value("DATABASE_NAME", environ=True), ... I have verified that my `.env' file exists and is on the valid path. Any help would be appreciated. -
Can someone explain why my form fields are dissappering when they are not being selected?
Image of Form Fields Dissapeering When Not Selected Hi all, I am having trouble understanding why my fields are disappearing when they are not selected. I am rendering this form using Crispy Forms (followed via Youtube Tutorial). This feature was working earlier - however, I am not sure why it suddenly stopped working. I have a few other forms in this application and they are facing the same issue. Here is the relevant code that is being used to generate the form class BookAppointmentForm(forms.ModelForm): class Meta: model = BooksAppt fields = '__all__' labels = { 'hp_username': 'Doctor', 'appt_date': 'Appointment Date', 'p_username': 'Patients' } widgets = { 'appt_date': forms.TextInput(attrs={'type': 'date'}) } def __init__(self, p_username=None, *args, **kwargs): super(BookAppointmentForm, self).__init__(*args, **kwargs) if p_username: self.fields['p_username'].queryset = Patient.objects.filter( p_username=p_username).values_list('p_username', flat=True) Relevant HTML being used to render the form <div class="container" style="background-color:#E6E6FA"> <div class="col-md-10 offset-md-1 mt-5"> <div class="card-body"> <h1 class="display-5 "> Booking an Appointment for {{ user }}</h1> <p class="lead">Please Fill in the Following Form to Register an Appointment</p> <hr class="my-4"> <form class="register" action="" method="post" autocomplete="off"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {{ form.p_username|as_crispy_field}} {{ form.hp_username|as_crispy_field }} {{ form.appt_date|as_crispy_field }} <button type="submit" class="btn btn-success">Submit</button> </form> <br> </div> </div> I feel as though the … -
how to show description under choies in django
I want to show small description under choies like this image, in front to need to pass this value to show description,any can help me my model is from django.db import models from sqlalchemy import true from company.models import Company from django.contrib.auth.models import User WORK_PLACE_TYPE =( ('onsite',' On-site'), ('hybrid','Hybrid'), ('remote','Remote'), ) class Job(models.Model): company =models.ForeignKey(User, on_delete=models.CASCADE); title = models.CharField(max_length=200) description = models.TextField(max_length=1500) date = models.DateTimeField(auto_now_add=true) workplace_type = models.CharField(max_length=32 , choices=WORK_PLACE_TYPE ,default='onsite',) experience =models.CharField(max_length=400) skills =models.CharField(max_length=200) location =models.CharField(max_length=100) def __str__(self): return '{} {} {} '.format(self.title,self.company,self.location) Any hint how to do this. -
Django Problem to access to template file.html
I write like this ** in Views :** def index(request): return render(request,'Expenses/index.html') def add_expenses(request): return render(request,'Expenses/add_expenses.html') ** in Project Urls :** from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include('expenses.urls')), path('admin/', admin.site.urls) ] ** in application Urls :** urlpatterns = [ path('',views.index, name='expenses') , path('add_expenses',views.add_expenses, name='add_expenses') ] but I when I run the project I had a problem Like that -
Django how to add previous button for related blog post?
I added next button but can’t figure how to add previous button. I added parent from my first object to before last one. see the layout for better understood blog title parent object next button (python tutorial - 1 )---->(python tutorial-2)----- >successfully added next button (python tutorial-2 )------>(python tutorial-3)----- >successfully added next button (python tutorial-3)-------> Null-------> No button as no parent my html: {{i.blog_title}} {{i.blog_parent.title}} {%if i.blog_parent %} <a href="{% url 'blog:blogDetails' i.blog_parent.blog_slug %}" id="next_button">next_button</a> {%endif%} {%endfor%} Now I want to add previous button from my second blog post to last blog post. How to do that? any idea? -
How to pass inMemoryUploadedFile into an api
I want to pass user uploaded images into an api from my view I have this form which submits a file into view <form action="http://127.0.0.1:8000/handler/" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form> I want to again send this file into an api but I can't do it directly, I think i must convert the file into string and pass to the api. Anybody have any idea on how to do it @csrf_exempt def handler(request): if request.method == 'POST': file = request.FILES['file'] res = requests.post('http://192.168.1.68:8000/endpoint/',{}) -
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' …