Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with categories on my blog website
I have added categories and everything but I can't see any posts in my categories. When I open for example http://localhost:8000/category/sport/ it is showing no posts... my urls.py : from django.urls import path #from . import views from .views import HomeView , ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, CategoryView urlpatterns = [ #path('', views.home, name="homepage"), path('', HomeView.as_view(), name = 'home'), path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-details'), path('add_post/', AddPostView.as_view(), name = 'add_post'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name = 'update_post'), path('article/<int:pk>/delete', DeletePostView.as_view(), name = 'delete_post'), path('category/<str:categories>/', CategoryView, name='category'), ] my models.py : from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): #return reverse('article-details', args=(str(self.id))) return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") m y views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' … -
'import jwt' not working in Django views.py though I have PyJwt installed
I'm working with Django and trying to generate jwt tokens in views.py and displaying it in html page. import jwt is throwing No module found error in views.py even though I have PyJwt installed already inside the virtual environment and it is working fine outside the views.py (say, jwttoken.py file) views.py import jwt def generateJWT(portal): key = 'secret' payload = {'iat': time.time(), 'iss' : 'localhost', 'exp': int(time.time()) + (5*365*24 * 60), 'portal': portal} #return payload return jwt.encode(payload, key, algorithm="HS256") Does it mean that I can't make use of jwt module in django? Is there any other way to make it work in Django as it is working outside? -
Celery tasks running multiple times in Django application
For weeks now we have been having issues with tasks running multiple times (always twice actually). I have tried to reproduce this locally and did a lot of testing on our staging and production server, but I can not seem to reproduce it and find the issue. Right now I simply have no clue where to look. -We have recently upgraded from celery v4 to v5, but this was together with many other upgrades. -The issues are only with long running periodic tasks (celery beat) that takeabout 15 min. to complete. -We run celery in a managed kubernetes environment with separate deployments for beat and worker. Both deployments currently have a single pod. One example of a task running twice: @idempotent_notification_task(notification_tag='CREDITS_DIRECTDEBIT_PAYMENT') def create_directdebit_payments_for_credits(): plus_admin_ids = Order.objects.filter( subscription__type=Subscription.PLUS, credits_auto_top_up_amount__gt=0).values_list('administration_id', flat=True) admins = Administration.objects.filter(id__in=plus_admin_ids) for admin in admins: remaining_credits = admin.remaining_credits if remaining_credits < 0: po_exists = PurchaseOrder.objects.filter(administration=admin, created__date=today(), service=PurchaseOrder.SERVICE.CREDITS).exists() if po_exists: print(f"PurchaseOrder for client {admin.title} already exists!") return purchase_order = PurchaseOrder.objects.create( administration=admin, service=PurchaseOrder.SERVICE.CREDITS, credits_amount=admin.order.first().credits_auto_top_up_amount) payment = create_credits_mollie_payment_directdebit(purchase_order) Notification.create_credits_directdebit_payment(purchase_order) In an attempt to create a fix I created a wrapper function to make the task idempotent, but even this did not fix the issue. The wrapper function works as expected during local … -
I am using Django rest framework I want to use random in my views.py can someone help me
I am using Django rest framework I want to use random in my views.py can someone help me I want to make Questions in views.py to be random and here is my code views.py class QuizQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quiz_id=self.kwargs['quiz_id'] quiz=models.Quiz.objects.get(pk=quiz_id) return models.QuizQuetions.objects.filter(quiz=quiz) class QuizChapterQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quizChapter_id=self.kwargs['quizChapter_id'] quizChapter=models.QuizChapter.objects.get(pk=quizChapter_id) return models.QuizQuetions.objects.filter(quizChapter=quizChapter) I want to make both of them to be random to get solutions to my problem -
(Python) how to make change on mysql, can reflect to website too
Main problem: connect exsited mysql and website , that making change on mysql can reflect to website too (ps. the Django way will stock on no way to connect exsist websit and MySQL) tried method A : even though the Django way can connect MySQL and Django, but still not lead to change mysql reflect to website too Demo idea result : (refer to author DC con, his example Concretization my aim) if I update/change the context Nordic as Nike from mySQL, by success connect both, the website part the Nike can replace Nordic as new topic I read through all the relate question, they either not 100% same to mine issue, or that issue don't get solution, or I tried the solution, but not worked , thanks -
How to correctly import and run a trained pytorch model within django application
I have a django website up and running. I would need to import a pytorch trained model (of which I am by no means an expert) I was thinking to make a wheel out of if and importing it as a module within my application. The model is obviously trained outside of the app in its own special environment. Is my approach correct, or is there a better cleaner way to do it? -
How to deal with multipe user role's with only one username in django
I have a django project with 2 types of users (Parent, Child), and using phone number as username How should I define my user model (or project architecture) to able login both parent and child with only one phone number? Currently I think about seperating profile table's and identify user role from the login endpoint, Or microservice this project into 2 smaller project's (Microservice) to do this. -
How can import a serializer module from Django app with in the standalone script in the "scripts" package?
Here is my project setup. ProjectDirectorty AppDirectory model.py serializer.py scripts Directory init.py main.py manage.py I am trying to call external API and get JSON data. Later deserialize it and store in the DB created by App. When I am running main.py using python manage.py runscript main , I get error "Cannot import module 'scripts.main': No module named 'mix.mixapp'" project setup I understand diffrence between Script vs. Module and read Relative imports for the billionth time I got stuck in this part of article "perhaps you don't actually want to run moduleX, you just want to run some other script, say myfile.py, that uses functions inside moduleX. If that is the case, put myfile.py somewhere else – not inside the package directory – and run it. If inside myfile.py you do things like from package.moduleA import spam, it will work fine." It is similar to my case. I am running main.py which is in the "scripts" dir and using function from AppDirectory. It didn't help. Please guide me to solve this problem. -
Django Transaction Rollback on related objects
In django, while in a transaction if an object is deleted its related objects will be deleted(those having one to one and foreignkey with this object) so if the transaction rolls back the deleted object will get rolled back but not its deleted related object. Is there any way with which we can do so? I tried overriding the deleted method and putting everything in a transaction atomic block but this didn't work -
How to get a count of objects in a Queryset
I have a model which which has fields like: class Vehicle(models.Model): car_name = models.CharField(max_length=255) car_color = models.CharField(max_length=255) This model has a lot of duplicate values too, I would like distinct to be shown The queryset gives an output like: <QuerySet [{'car_name': 'Audi', 'car_color': 'Red'}, {car_name': 'BMW', 'car_color': 'white'}]> I want my output Queryset to have another field, which is like a counter for the ouput. If I get two objects out of the query, then a field called ordinal_count also be sent in queryset. For example: <QuerySet [{'car_name': 'Audi', 'car_color': 'Red', 'ordinal_count': 1}, {car_name': 'BMW', 'car_color': 'white', 'ordinal_count': 2}]> This is the query which I wrote: op = (Vehicale.objects.annotate(ordinal_count=Count("car_name", distinct="car_name")).filter(car_color='white', list_display=True).values("car_name","car_color", "ordinal_count")) This is not giving me the desired input and is also messing up the filter. Should I even be using annotate? I have tried using SQl query, but I would like to get a queryset. I have written an output serializer which would easily be able to take input. Or should I get the output without ordinal_count, and later in serializer should I try to get the count output? If yes, then how do I do it? -
Will creating serializer.Serializer fields saves to the database?
When we're not creating models and directly creating the fields inn serializers using serializer.Serializer , will the fields save to database? because we havent migrated to the database? also if i have created one existing database, i'm creating some additional fields in serializers? will that also saves to database? can anyone lighten me up? Im new to django api. here i provide some example. let my Model.Py be like, class Detail(models.Model): fname = models.Charfield(maxlength=20) lname = models.Charfield(maxlength=20) mobile = models.IntergerField(maxlength=20) email = models.EmailField(maxlength=20) let my Serializer.Py be like, class DetailSerializer(serializer.Serializer): created_at = serializer.Charfield is_active = serializer.Booleanfield Will this serializer save in database that i created manually in serializer? another question is if i create serializers without a model, will that save to database? if that saves in database how's it possible without migrating? -
add +=1 to integer in the database
I want to add +=1 in Count_of_all_questions every time the function is executed. How can I do that? views.py def somefunction(request): verify = Statistik.objects.filter(user__exact=request.user) if verify: # i wanna add here on Count_of_all_questions += 1 else: form = Statistik(Count_of_all_questions=total) form.user = request.user form.save() models.py class Statistik(models.Model): Count_of_all_questions = models.IntegerField() #Count_of_all_correct_answer = models.IntegerField() #Count_of_all_wrong_answer = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) Thank you a lot! I want to add +=1 in Count_of_all_questions every time the function is executed. How can I do that? -
My link to a local markdown file does not work correctly
for example when link is: http://127.0.0.1:8000/entries/CSS it throws an error: Page not found (404) “entries/CSS” does not exist But when i put a file format at the end (in this case it is .md) it downloads the file instead of opening it in my browser: <ul> {% for entry in entries %} <li><a href ="./entries/{{entry}}.md">{{ entry }}</li></a> {% endfor %} </ul> link: 127.0.0.1:8000/entries/CSS.md I need to open this pages in browser, how do i fix it? Here is my urls.py file: from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path("", views.index, name="index"), path('newpage/', views.new_page, name = 'newpage'), ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Django Many to Many field dependent on another many to many field
I'm creating two many-to-many fields based on same model in a single model. I would like to show only those instances in second many-to-many field which are selected in first many to many field to further apply selection. Through which approach should i handle this behaviour. class Params(models.Model): name = models.CharField(max_length = 200) comments = Model.TextField() def __str__(self): return self.name class Selection(models.Model): select_params = models.ManyToManyField(Params, blank=True, related_name = "selection_1") edit_selected_params = models.ManyToManyField(Params, blank=True, related_name = "selection_from_selec_params") Thanks and regards -
How this code upload file in django can run the html file?
The code is here I am confused about the html file, it looks like it was never called but it can be run and when I change upload_form.html name to upload.html, it could be an error. So how come? and how to make the program can run upload_form.html file in another name file? This is my first question, so sorry if my question makes you confused >.< I wish I could understand the code -
Display today data and yesterday data of datetime field values using django
Here by default I need to display today data and yesterday data where the date is DateTime field Here is my views.py def completed_quanity_list(request): client = request.user.client production_process = ProductionProcess.objects.filter(client=client,is_deleted=False) today = datetime.date.today() yesterday = today + timedelta(days=-1) completed_quantity = CompletedQuantity.objects.filter(client=client,date__range=[yesterday, today]) return render(request, 'manufacturing/completed_quantity_list.html',locals()) Here is my database records example of CompletedQuantity table id date 1 2023-01-13 18:28:35.045678 2 2023-01-12 18:30:45.056345 3 2023-01-04 10:04:56.086043 4 2023-01-04 10:37:08.349253 5 2023-01-05 04:33:31.109787 6 2023-01-05 04:35:16.852320 I need to display the records of id's 3,4,5,6 in my template -
How to work with an image before saving it in my model?
django How to work with an image before saving it in my model? I have a model where a field exists image=models.ImageField(upload_to='products/') models.py class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) code_number = models.IntegerField(verbose_name='Bar Code') image = models.ImageField(upload_to='products/') purchase_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price= models.DecimalField(max_digits=10, decimal_places=2) tax = models.ManyToManyField(Tax, blank=True, related_name="tax") pro_quantity =models.DecimalField(max_digits=10, decimal_places=2, default=0) description = models.TextField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name="branchesp", blank=True, null=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name views.py class ProductCreate(View): form_class = ProductForm template_name = 'pos/product_form.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.user = self.request.user if form.is_valid(): # Procesa la imagen subida image_content = request.FILES['image'].read() image = resize_image_with_aspect(image_content, 800, 600) image_file = tempfile.NamedTemporaryFile(mode='wb', suffix='.webp') image.save(image_file, format="webp", optimize=True, quality=85) image_file = open(image_file.name, 'rb') form.instance.image = image_file.read() image_file = BytesIO(form.instance.image) image_file.seek(0) form.instance.image = File(image_file) product = form.save(commit=False) product.save() image_file.close() return redirect('inventory') else: print(form.errors) return redirect('inventory') utils.py import io from PIL import Image def resize_image_with_aspect(image_content, width, height): image = Image.open(io.BytesIO(image_content)) original_width, original_height = image.size ratio = original_width / original_height if width > height: height = int(width / ratio)manteniendo el ratio … -
Length of variable declaration in Django?
budgeted_cost_sheet_fabric_summary_obj_kg_consumption = 1.123 or def budgeted_cost_sheet_fabric_summary_obj_kg_consumption_update(id): OBJ.update(an_attribute=data) I am going to declare variable or function name like this way. Is it okay to declare in this way in Django? Or it may arise any error in future? -
Django UnitTesting: 'AnonymousUser' object has no attribute
I have the following code: class CampaignModelTests(TestCase): # https://docs.djangoproject.com/en/4.1/topics/testing/advanced/ def setUp(self): # create some test campaigns shop = Shop.objects.create(name='Test Shop') self.factory = RequestFactory() self.user = User.objects.create(shop_username='testuser', shop=shop) self.merchant = User.objects.create(username='merchant', password='merchant123', is_merchant=True, shop=shop) self.campaign = Campaign.objects.create(name='Test Campaign', shop=shop) def test_campaign_creation(self): request = self.factory.get(reverse('create-campaign'), { 'name': 'Test Campaign -1', 'shop': Shop(name='Test Shop').sid }) request.user = self.merchant print('request.user: ', request.user.is_merchant) response = CampaignCreate.as_view()(request) self.assertEqual(response.status_code, 200) And I am getting the following error: return request.user.is_merchant or request.user.is_superuser AttributeError: 'AnonymousUser' object has no attribute 'is_merchant' I have tried using self.client as well but still the same error. self.client.force_login(self.merchant) # send a request to the view response = self.client.post(reverse('create-campaign'), { 'name': 'Test Campaign -1', 'shop': Shop(name='Test Shop').sid }) self.assertEqual(response.status_code, 200) -
Django combine queries with and (&) in m2m field
I have such models: class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() tags = models.ManyToManyField(to="tag", related_name="tags", blank=True) def __str__(self): return self.title class Tag(models.Model): value = models.CharField(max_length=50) parent = models.ManyToManyField("Tag", related_name="children", blank=True) image = models.ImageField(upload_to="tags", null=True, blank=True) def __str__(self): return self.value And I have an object, for example, post C which has tag 2 and tag 3 Currently I cannot create a combined ( q1 & q2 ) query, where I will be able to filter by that condition. I am using combined queries because the case is more complex(so double filter won't do), I want to be able to filter by such queries as " 2 or ( 3 and 4 ) ", "(1 or 2) and (3 or 4)" >>> q1 <Q: (AND: ('tags__in', '2'))> >>> q2 <Q: (AND: ('tags__in', '3'))> >>> Post.objects.filter(q1) <QuerySet [<Post: post_B>, <Post: post C>, <Post: post D>]> >>> Post.objects.filter(q2) <QuerySet [<Post: post C>, <Post: post D>]> >>> Post.objects.filter(q1 & q2) <QuerySet []> >>> str(Post.objects.filter(q1).query) 'SELECT "posts_post"."id", "posts_post"."title", "posts_post"."content" FROM "posts_post" INNER JOIN "posts_post_tags" ON ("posts_post"."id" = "posts_post_tags"."post_id") WHERE "posts_post_tags"."tag_id" IN (2)' >>> str(Post.objects.filter(q2).query) 'SELECT "posts_post"."id", "posts_post"."title", "posts_post"."content" FROM "posts_post" INNER JOIN "posts_post_tags" ON ("posts_post"."id" = "posts_post_tags"."post_id") WHERE "posts_post_tags"."tag_id" IN (3)' >>> str(Post.objects.filter(q1 & q2).query) … -
How to get webhook data in python
I have a webhook url from messagebird, and post requests are being sent from the LINE Messaging API to that url when some events occur. I need to get the data of those webhooks (JSON data). I'm using Python (it's a Django app). How can I get the data from the webhook? -
Recommendations for DRF lectures in udemy
Which udemy course is best for django rest framework that follows whole django documentation? Main purpose is to learn drf in detail by following its documentation. -
How to Configuration for wgsi conf file for fjango without virtual enviroment?
i wanna host django application using apache2 with mod_wsgi without virtual enviroment so i am not able to config .conf file here is my configuration file. <VirtualHost *:80> ServerName example.in ServerAdmin info@example.in ServerAlias example.in DocumentRoot /home/MyMedbookMain/django Alias /static /home/MyMedbookMain/django/static <Directory /home/TransportDemo/static> Require all granted </Directory> <Directory /home/MyMedbookMain/django/qm> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mymedbook python-home=/usr/local/bin/pip3 python-path=/home/MyMedbookMain/django WSGIProcessGroup mymedbook WSGIScriptAlias / /home/MyMedbookMain/django/qm/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] after reload apache2 it not loading -
Django makemigrations : IndexError: list index out of range
When I attempt to run python3.8 makemigrations, I get the following : File "/usr/lib/python3.8/gettext.py", line 436, in _parse plural = v[1].split('plural=')[1] IndexError: list index out of range Upon detailed inspection by running python3.8 manage.py runserver , I observed the following: 2023-01-05 03:33:22,179 django.utils.autoreload INFO Watching for file changes with StatReloader 2023-01-05 03:33:22,180 django.utils.autoreload DEBUG Waiting for apps ready_event. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/earthling/myEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/earthling/myEnv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 92, in … -
Django ORM model to sync with db record changed by external
In Django model, is there anyway for instant sync of loaded model object with db records updated by external? Here is sample scenario. I load record in Django model by get method. book = Book.objects.get(id=1) print(book.title) # It will print '21 century' I update relevant db data manually in database using query in PGAdmin update book set title='22 century' where id=1 the model obj loaded in 1st step still retains old data instead of latest update from 2 step print(book.title) # It still print '21 century' instead of '22 century' I have no solution yet and need help for this