Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apscheduler Job in Django executes twice
The scheduled job executes twice with difference in nanoseconds. I have a task as follows in task.py def print_hello(): print("time-->",datetime.datetime.now()) print("hello") def print_world(): print("time-->",datetime.datetime.now()) print("hello") scheduler = BackgroundScheduler() scheduler1 = BackgroundScheduler() Add in app.py from app folder consist following code line.. from django.apps import AppConfig from datetime import date class ExploitDataConfig(AppConfig): name = 'exploit_data' def ready(self): from exploit_data import task task.scheduler.add_job(task.print_hello, 'interval', minutes=5) task.scheduler1.add_job(task.print_world, 'interval', minutes=5 task.scheduler.start() task.scheduler1.start() I want this to execute only once at the interval of 5 minutes. ANY HELP IS APPRECIABLE .. -
Get max and min formatted date values from queryset in Django
I have a one to many relation between session and camp. Now I have to get the max and min dates of all camps combined for a particular session. I am able to do it like this: sess = Session.objects.last() max_min_dates = sess.camp.aggregate(Min('start_date'), Max('end_date')) But if I try to send this from HttpResponse then I am getting this error: TypeError: Object of type 'date' is not JSON serializable So I need to send the formatted date values in that. How can I modify the above code to get the same? -
How to hit Vscode breakpoints in unit tests from within a docker-compose setup running Django
What I'm trying to do seems simple enough, but it's been crazy hard to actually get there. I have a Django application that runs in a docker-compose environment, and I want to run and debug the unit tests with breakpoints in Vscode. Since this is a big project with a team that doesn't necessarily use vscode, I can't add libraries willy-nilly (like ptvsd, for example). I'm hoping there's a magic configuration for tasks.json and launch.json that will makes things work. I have a container for a postgres database, one for django, and one for redis, all defined in docker-compose.yml. There's a command that I can run in the terminal that will run the tests, it's: docker-compose run --rm app python manage.py test where app is the django app container. I'd love to be able to run this command in such a way that it can hit breakpoints in vscode. My incomplete stab at the launch.json file looks like this: { "configurations": [{ "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "compose-for-debug", "python": { "pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }], "projectType": "django" } }] } And my tasks.json: { "version": "2.0.0", "tasks": [{ "type": "docker-build", "label": "docker-build", "platform": … -
Django models Many to one not able to access all objects in a foreign key field
I might be confused however when I check the django-admin panel I can see (will provide a screenshot) , over 50 models attached to my primary model, however whenever I make a query in the code and try to access the set associated with the field I only ever get one entry. I am trying to make one query and check all models associated with the field. My models.py code: class TokenData(models.Model): name = models.CharField(max_length=200) contract_address = models.CharField(max_length=200,primary_key=True, unique=True) def save(self, *args, **kwargs): #print('save() is called.') super(TokenData, self).save(*args, **kwargs) def __str__(self): return self.name class WalletData(models.Model): address = models.CharField(max_length=200,primary_key=True,unique=True) contract_address = models.ForeignKey(to=TokenData,on_delete=models.CASCADE,) last_bitquery_scan = models.CharField(max_length=200) def __str__(self): return self.address I am trying to access the model like so : WalletData.objects.filter(address=address) One thing I noticed is when I create a variable containing the filter, and access the contract_address in the WalletData model, I can endlessly query myself in a circle for lack of a better word, by accessing the set and executing a get against it. I am just wanting to access all 50 models like shown below -
POST method does not pass the value password from the input field
Here form is submitted via POST method but password given in the input field of type=password not assigning to 'upassword' given in the userregister function.When I print the 'upassword' it gives an output "None".Also it gives an error like this when I give JAVASCRIPT validation. Internal Server Error: /User/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 214, in userregister epassword = sha256(upassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' views.py def userregister(request): if request.method == 'POST': upassword = request.POST.get('password') print(upassword) ucpassword=request.POST.get('cpassword') epassword = sha256(upassword.encode()).hexdigest() -
The extra function written for the DeleteView class does not work
I have added a function that if the post is deleted by the user, it will be deleted if there is an uploaded photo, but the function does not work. my view: class NewsDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = News template_name = 'news/news_delete.html' success_url = reverse_lazy('news_list') def delete_header_image(self, pk): news = get_object_or_404(News, id = pk) header_image = news.header_image if header_image is not None: os.remove(str(header_image)) return HttpResponseRedirect(reverse('news_list', args=[str(news.pk)])) else: return HttpResponseRedirect(reverse('news_list', args=[str(news.pk)])) def test_func(self): obj = self.get_object() if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user: return True urls: urlpatterns = [ path('<int:pk>/delete', NewsDeleteView.as_view(), name='news_delete'), ] models: def get_header_image_filepath(self, filepath): return f'images/news/header/{self.author.id}/{self.header_image}' class News(models.Model): title = models.CharField(max_length=255) header_image = models.ImageField(null=True, blank=True, upload_to=get_header_image_filepath) body = RichTextUploadingField() datetime = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("news_detail", args=[str(self.id)]) -
Django DRF routing not a valid regular expression
I want to use a DRF viewset with an @action decorator, but when I call that endpoint I get the error: django.core.exceptions.ImproperlyConfigured: "^\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 2; was group 1 at position 32 Here is url.py: router = routers.DefaultRouter() router.register(r"", GenreViewSet, basename="genre") urlpatterns = router.urls And the viewsets.py: class GenreViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] pagination_class = None queryset = Genre.objects.all() def get_serializer_class(self): if self.action == "list": return GenreSerializer @action(detail=True, methods=["patch", "delete"], url_path="favourite") def make_genre_favourite(self, request, pk=None): genre = self.get_object() # Other code and responses here. The parent url comes from /api/genre/. The list endpoint works, it returns all genres as it should, it's the action that gives that error. Any help appreciated much. I've tried format_suffix_patterns and no luck in case you might be asking. -
Django channels is auto disconnecting after sending message
I am working on a personal chat application in django using django channels. The problem is that after sending message from user1 to user2, the channels of user1(all connected channels) is auto disconnecting after sending message to chat room, although the message is passed successfully to user2 and appeared in screen. There is no particular error message. In console it shows, HTTP GET /? 200 [0.22, 127.0.0.1:52178] WebSocket DISCONNECT /chat/3/ [127.0.0.1:58587] consumers.py: class PersonalChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_id'] self.room_id = self.room_name print(f'Room id: {self.room_id}') self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(json.dumps({ "join": str(self.room_name), })) def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): print("ChatConsumer: receive_json") text_data = json.loads(text_data) command = text_data.get("command", None) # message = text_data_json['message'] if command == 'send_message': self.send_room(text_data["room_id"], text_data["message"], text_data['type']) def send_room(self, room_id, message_content, message_type): user = self.scope['user'] room = self.get_room_or_error(room_id, user) if message_type.startswith('message'): message_obj = ChatRoomMessage.objects.create(room=room, user=user, content=message_content, message_type=message_type) message = {} message['user_id'] = str(user.id) message['username'] = str(user.username) message['profile_pic_url'] = str(user.profile_image.url) message['timestamp'] = str(message_obj.timestamp) message['msg_type'] = message_obj.message_type message['content'] = message_obj.content async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, … -
not able to save data from bootstrap form to data base in Django
I have created a form that takes 3 inputs from a user and saves user input to DataBase but I am not able to load data from the form to Sqlite dataBase there isn't any error shown on the screen but not able to store data in Db from the user input form. Please Help me I am stuck in here from last 24 hours Thank you views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import EmployeeForm from .models import Person def index(request): return render(request, 'base.html') def employee(request): if request.method == 'POST': data = request.POST first_name = data['first_name'] last_name = data['last_name'] email = data['email'] obj = Person.objects.create( first_name=first_name, last_name=last_name, email=email) if obj: return redirect('/') return HttpResponse("employee is not created") else: person = Person.objects.all() context = { 'person': person } return render(request, 'employee/employee.html', context) models.py from django.db import models class Person(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=110) email = models.EmailField() employee.html {% extends "base.html" %} {% block main %} <div class="context"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Add new </button> <div class="card"> <div class="card-header"> Employee Details </div> </div> </div> <form method=="POST" > {% csrf_token %} <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" … -
Referral application in Django
I want to create a Django application referral system for profiles created by user upon login whenever a people login they get a option to create a profile and in that create profile form their is input for referral code which eventually add some point to referred by person here is my Profile Model class Profile(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default='') name = models.CharField(max_length=200,null=True,blank=True) number = models.CharField(max_length=11,default=None,null=True) text = models.TextField(max_length=520) facebook = models.URLField(name='facebook',default=None,null=True) linkedin = models.URLField(name='linkedin',default=None,null=True) instagram = models.URLField(name='instagram',default=None,null=True) profile_picture = models.ImageField(upload_to='profile_pic/', max_length=None) published_date = models.DateTimeField(auto_now_add=True, null=True) updated_date = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=False) def __str__(self): return self.name what should be added to this profile for referral code ?? and how to create a referral class ??? -
How to remove use_for_related_fields since it's deprecated?
Since use_for_related_fields is deprecated, I see the following warning when start up tests: "RemovedInDjango20Warning: use_for_related_fields is deprecated, instead set Meta.base_manager_name on 'info.PersonLink'" but it appears on custom manager, inherited from models.Manager: class PersonLinkManager(models.Manager.from_queryset(PersonLinkQuerySet)): use_for_related_fields = True where PersonLinkQuerySet: class PersonLinkQuerySet(models.QuerySet): def filter_active(self): return self.filter(person__is_active=True) How to rewrite it to avoid this warning in the future? -
How can get current field from form in Django UpdateView like cleaned_data.get('some_field') when use a function?
I need to take one field from the form, make calculations and insert the result into the second field. If you use a function, you can use cleaned _data.get ('first_field') for this, but how to do this using UpdateView? Thank you! -
Django loop pre fetch versus new query
I cant work out in my application that looping a new queryset would loop much faster than a prefetched queryset. I am trying to cut down on queries but I am left with no option atm that to create a new one. answers = ( ReportUserAnswers.objects.filter(...) ) If i loop the above its fast. answers = question.reportuseranswers_set.all() This is really slow. Is there logic i am missing which might which makes this expected behaviour? matched_answers = [ans for ans in answers if choice = "Yes"] Loop that is being used to see the difference above. Queryset lengths are the same new query: 206 loop: 206 -
Facing 502 Bad Gateway/nginx while trying to scrape and insert data in Django
I've implemented a robot inside a Django project that receives a movie URL from IMDB within a form, scrapes some pieces of information from movies, and inserts them into the Postgres Database. It works pretty fine for almost 50% of movies and does the job without heading into errors. But it gives the error 502 Bad Gateway / nginx on some movies while trying to scrape them. I've read some articles about it and I guess the issue is kind of related to server timeout but I'm not sure if that's the case right now. Does anyone have any idea where the problem lies? Thanks in advance for your help. -
Importing csv/excel file in django admin which has inlines
I have tried django-import-export but I couldn't see any way to import inline data using it. I would like to import data from admin which has inlines(more than 1). Example: I have a Course Model, Course Details and Course Deadlines class Course(models.Model): pass class CourseDetails(models.Model): course= models.ForeignKey(course) class CourseDeadlines(models.Model): course= models.ForeignKey(course) On the admin side: class CourseAdmin(admin.ModelAdmin): inlines=[CourseDetailsInline, CourseDeadlinesInline] I would like to import Course Details and coursedeadlines as well when importing courses. Right now I am using django-import-export using which I am not able to import inlines.Any suggestions on the right way to achieve importing data with inlines will be helpful -
How to test Django model using Django test and pytest?
I am using Django to build a website but I don't know how to test my model using Django test and pytest. This is my model. class Payment(models.Model): fund = models.ForeignKey( Funds, verbose_name=_("Fund"), on_delete=models.CASCADE ) currency = models.ForeignKey( Currency, verbose_name=_("Currency"), on_delete=models.CASCADE ) amount = models.DecimalField( verbose_name=_("Amount"), max_digits=10, decimal_places=2 ) date = models.DateField( verbose_name=_("Payment Date"), auto_now_add=True ) status = models.CharField( verbose_name=_("Payment Status"), max_length=20, choices=payment_status_choices, default='pending' ) recipient = models.CharField( verbose_name=_("Recipient"), max_length=50, unique=True ) remark = models.TextField( verbose_name=_("Remark"), blank=True, null=True ) created_by = models.ForeignKey( User, default=1, verbose_name=_("Created By"), on_delete=models.PROTECT, related_name="%(class)s_createdby" ) created_date = models.DateTimeField( verbose_name=_("Created Date"), auto_now_add=True ) modified_by = models.ForeignKey( User, default=1, verbose_name=_("Update By"), on_delete=models.PROTECT, related_name="%(class)s_modifiedby", ) modified_date = models.DateTimeField( verbose_name=_("Modified Date"), auto_now_add=True ) deleted = models.BooleanField( default=False, verbose_name=_("Deleted") ) def __str__(self): return str(self.amount) Please help me doing the rest for this model. Also What is the different between Django test and pytest and which one should I use to test Django model, form and view -
How to prevent Django's prefetch_related from caching a queryset
I have the following queryset function for an Argument model: class ArgumentQuerySet(QuerySet): def prefetch_related_objects(self): from views.models import View return self.prefetch_related( Prefetch( 'argument_reactions', queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name, reaction_type=ReactionType.ENDORSE.name), to_attr='endorsement_reactions' ), Prefetch( 'argument_reactions', queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name, reaction_type=ReactionType.DISAGREE.name), to_attr='disagreement_reactions' ), ) As you can see I'm trying to prefetch the same relation using different querysets and I'm also using the to_attr parameter of the Prefetch object. The problem is the second prefetch is not working properly, the disagreement_reactions list is empty. But it works if I remove the first prefetch. I believe the first queryset, i.e., View.objects is being cached somehow. How can I prevent that? -
Render image to a choice/char field in Django admin
I have a CharField in my model like this: simbol_oznaka = models.CharField(choices=CHOICES_SIMBOLI, null=True, blank=True, verbose_name="Simbol", max_length=512) with a choice tuple like this: CHOICES_SIMBOLI=( ('', 'No Image'), ('media/simboli/2.png', 'Image 1'),). I was wondering how can I render the image in the django admin change/add form, because I don't want the user to see the "Image 1" text but rather the image itself. This is what it currently looks like: Use case: I want the users to be able to choose only one image from a few that would be displayed in the drop down (not necessarily drop down) -
How to validate all the fields at once by making a default validator in django restframework?
I don't want to use Field level or object level validation. While doing POST API call in django restframework, I want to call a default validator by is_valid() method. No arguments should be passed while calling this method and all the fields should be validated. It should be fully generic, so that I can add as many validations as possible. -
Not able to save data in database using django form
I am trying to save data in database using django form but it not saving it this is my forms.py class PlanForm(forms.ModelForm): class Meta: model = Plans fields = ['plan_name', 'plan_note', 'plan_price', 'access_to'] plan_name = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_name' } )) plan_note = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_note' } )) plan_price = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_price' } )) can_access = forms.ModelMultipleChoiceField( queryset=Add_e_office.objects.all(), widget=forms.CheckboxSelectMultiple ) and this my views.py def add_plan(request): if request.method == 'POST': form = PlanForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() messages.success(request,"Plan created successfully.") return redirect(request.path) return render(request, 'backend/add_plan.html',{'form':form}) else: form = PlanForm() return render(request, 'backend/add_plan.html',{'form':form}) when i submit my form i receive POST request but it did not save data in data base actualy it ignore form.is_valid() part. -
Comments in the admin panel are added, but they are not visible on the site
Based on this tutorial https://www.youtube.com/watch?v=An4hW4TjKhE&ab_channel=AbhishekVerma I'm trying to add the ability to add comments under posts, add a comment in the admin panel, everything is ok, but the site does not display anything under the post here is models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg') def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_post') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_user') content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post, Comment from django import forms from .forms import * class BlogListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 2 queryset = Post.objects.all() class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] … -
Can we use queryset.first() instead of catching exception?
I normally use MyModel.objects.filter(pk=1).first() instead of MyModel.objects.get(pk=1) when I am not entirely sure whether there is any object with pk=1 or not. Is it a bad practice doing so for this scenario or I need to try: MyModel.objects.get(pk=1) except MyModel.DoesNotExist: print('not found') I normally do MyModel.objects.filter(pk=1).first() for the less code. -
Why can't I add my app in the setting.py before making it? (Django)
I've been following tutorials and messing around with Django lately. I'm trying to revise what I've learned and There's a question I would like to ask: Can someone explain to me why I can't go to my setting.py and add the name of my app in the installed_apps before actually making it? I'm a bit confused about the concept. Why is the other way around allowed in the terminal flawlessly and not in this way? Thanks in advance! -
how to not apply jwt to every app in django
I am working to make a simple ecommerce app. It work with Django as a backend and React for frontend. The trouble I am facing is when I tried to enter some product information (like title, price, image, description) through admin panel , It does not show in home page. When I tried to access its json form using Rest-framework api, it shows this HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api" { "detail": "Authentication credentials were not provided." } here is the screenshot I have successfully added user model just following the tutorial but I think this is the cause. I think I have two authentication backends and jwt is not allowing me as admin user to add products. I searched it on google but could not figure what to do? This is my settings.py """ Django settings for UsamaComputers project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent … -
Is there a way to generate random integers using django forms.py?
I just started learning Django and have a problem: I initially used a class-based view to save information from the front end or user. I then decided to switch to forms.py. My problem is I cannot generate a random number to be saved using forms.py. I do not know if I should recreate this in forms or models. This was the code I wrote in views.py: def createproformastandard(request): now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1: day = "0" + str(day) if len(str(month)) == 1: month = "0" + str(month) today = str(year) + "/" + str(month) + "/" + str(day) date = str(year) + str(month) + str(day) randint = str(random.randint(1000, 9999)) rand = str("TSCL") + date + "-" + randint + str("-P") rand = str(rand) while len(ProformaReceipt.objects.filter(rand=rand)) != 0: randint = str(random.randint(1000, 9999)) rand = date + randint rand = int(rand) form = CreateProformaReceipt() if request.method == 'POST': form = CreateProformaReceipt(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'proforma/proforma_form_standard.html', context)