Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Cannot import .py file into settings.py
I have created a separate file test.py to interface with Azure Key Vault. When I run just the test.py file it works as expected. However, I cannot import it in settings.py for its values to be used there. I cannot import any file into settings.py for that matter or it causes an internal 500 error on Apache. For instance I want to add these lines to my settings.py import test Pass = test.Pass However, when adding that and restarting the Apache server is gives an error 500 page until I remove the lines and restart. test.py has no syntax errors because I can run it on its own and produce the result I am looking for but bringing any file into settings.py causes the crash. The error logs have been no help. Why would I not be able to import a file into settings.py? The file I am importing is successful a part of the PYTHONPATH variable and I have checked that by printing sys.path. Also the file is located in the same directory as settings.py mysite/ settings,py test.py urls.py wsgi.py init.py -
(Python) How to Connect/Integrate Django with website
my problem is 60% similar to this one How to retrieve data from MySQL database in Django and display it in html page? Goal: I want Connect Django with website , I see most of the result is showing create new website by Django, for now I already have website done/build separately, and wish to connect with Django environment: mySQL, python, windows and exist website to connect that for now I connect mySQL and Django and the screenshot of .py page in Django , I'm not sure what .py script should add to achive my goal https://imgur.com/a/lmj61pJ with init.py , asgi.py , settings.py , urls.py , wsgi.py -
Curly Bracket Mysteriously Appearing in Django App
I am following a Django tutorial and getting a weird bug: I have models hooked up to views hooked up to templates, but when I view the page I get a weird closing curly bracket inside the table above "Site Name". I cannot figure out where this comes from. How do I make it go away? My html Template code is: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <style>{% include "</style> <link rel="stylesheet" href="{% static "CSS/simple_style.css"%}"/> <title>Django Level Two</title> </head> <body> <h1>Hi and Welcome to Django Level Two</h1> <h2>Here are your access records:</h2> <div class="djangotwo"> {% if access_records %} <table> <thead> <th>Site Name</th> <th>Date Accessed</th> </thead> {% for acc in access_records %} <tr> <td>{{ acc.name }}</td> <td>{{ acc.date }}</td> </tr> {% endfor %}} </table> {% else %} <p>NO ACCESS RECORDS FOUND!</p> {% endif %} </div> </body> </html> My CSS code is as follows: h1{ color: #011627; } h2{ color: #191063; } .djangotwo{ border: 2px solid black; } Views code is: from django.shortcuts import render from django.http import HttpResponse from AppTwo.models import Topic, Webpage, AccessRecord # Create your views here. def home(request): webpages_list = AccessRecord.objects.order_by("date") date_dict = {"access_records": webpages_list} return render(request, "AppTwo/index.html", context=date_dict) def help_page(request): help_dict = … -
Applying django-filter settings
From django-filter documentation I can see that there is a setting to disable the empty choice under heading FILTERS_EMPTY_CHOICE_LABEL. I am attempting to apply that setting however cannot get the the correct syntax. In my settings.py file I have EMPTY_CHOICE_LABEL = [ { 'ChoiceFilter.empty_label': 'None' } ] However this returns error FILTERS_ NameError: name 'FILTERS_' is not defined What is the correct syntax to apply this setting? -
Wrong Version of Django Running in Virtual Environment
I have two versions of Python installed (OS: Windows 10). The original version is 3.8.2. I installed 3.11.1 and did not have it added to PYTHONPATH. I created a virtual env using py -m venv .env. Despite using py, the virtual environment runs both Python 3.8.2 and 3.11.1 depending on whether I type python or py. Inside the virtual environment I installed a newer version of Django (4.1.5) using py -m pip install django, which successfully installed Django within the Python311 folder on my system. However, no django-admin.py file was installed, just django-admin.exe. To ensure I created my project using the newer version of Django, I navigated to the folder where the django-admin.exe file exists and ran the following: py django-admin.exe startproject <*project_name*> <*full_path_to_project_folder*> The settings.py file shows it was created using Django 4.1.5, but whenever I start my project it runs using Django 3.0.4 (the pre-existing version). I am starting it using py manage.py runserver, to ensure Python 3.11.1 is being used. I have tried it both inside and outside my virtual environment. I have added the python311\Scripts folder at the top of my Path environment variables, and have uninstalled and reinstalled Django 4.1.5. At this point I am … -
Django Formset display currently images in BlogUpdate
i want to display currently images in BlogUpdate with custum label how can i show blog related image in BlogUpdate display currently images path with url but not display currently images in img tag i want to display currently images in blog_update.html {{ img.media_files }} display currently images path <img src="{{ img.media_files.url }}"> but not display currently images in img tag forms.py class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['title', 'text', ] class BlogImagesForm(forms.ModelForm): class Meta: model = BlogImages fields = ['media_files', ] media_files = forms.ImageField( widget=forms.ClearableFileInput(attrs={'multiple': False,})) BlogImagesFormSet = inlineformset_factory( Blog, BlogImages, form=BlogImagesForm, extra=6, max_num=6, can_delete=False, can_order=False ) views.py class BlogUpdate(LoginRequiredMixin, UpdateView): model = Blog form_class = BlogForm template_name = 'blog/blog_update.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['images'] = BlogImagesFormSet( self.request.POST or None, self.request.FILES or None, instance=self.object ) else: data['images'] = BlogImagesFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.owner = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.save() return super(BlogUpdate, self).form_valid(form) blog_update.html <form method="POST" enctype="multipart/form-data"> <div class="girdbox"> {% for img in images.forms %} <label for="{{ img.media_files.auto_id }}" class="blurfix"> <img src="{{ img.media_files.url }}"> <div style="padding-bottom: 50%;"></div> </label> {% endfor %} </div> {% csrf_token %} {{ form|crispy }} … -
How to generate a querylist in Django, which needs to be generated only once?
guys. I hope you are doing well. So, I am developing a language website now and I have a Django view, called ExerciseView. My idea is next - go to the page (views triggers) --> querylist is generated in a random order --> declare sessions --> change them to dictionary to access easier --> and conditionals starts. My question is - how to generate the querylist only once and keep it the same until the training is finished. Every time a person clicks the buttons, new GET request is made and new querylist is generated. How can I make it constant and random list, which is not changing like that? The first time it generates this [<Exercise: Я пью чай без лимона >, <Exercise: Это дом папы >, <Exercise: У Тимофея день рождения сегодня!>] The next time I make a POST request and then again GET happens and this querylist is already different: [<Exercise: Я иду домой с работы >, <Exercise: Я пью чай без лимона >, <Exercise: У меня нет друга >] class ExerciseView(View): def get(self, request, **kwargs): data = list(Exercise.objects.filter(topic_type__slug=kwargs['slug_exercise']).all().order_by('?'))[:3] id = request.session.setdefault('sentence_id', 0) score = request.session.setdefault('score', 0) sentences = request.session.setdefault('sentences', {}) for i in range(0, len(data)): sentences[i] … -
Getting django accept phpBB users
My Problem is, I want to create a extra website on a phpBB forum to provide extra stuff and registration for meeting. No problem I know django and python, so this is no problem. But I would be nice, if I could accept a session from a user or import the phpBB users so that they can login to my app. I found django-phpBB, but I don't want to access the data. If I read correctly, my case is not the use case of django-phpBB. Can anybody give me a good advice? -
Generating new HTML rows for each Document from firestore in python Django
I have a collection of documents in a Firestore database. I want to create a web form to display all the documents and their fields. I started by streaming all the documents using: docs = db.collection(u'users').stream() and then appending all the docs IDs to a list and pass it to the HTML file as follows def index(request): myIDs =[] db = firestore.Client() docs = db.collection(u'users').stream() for doc in docs: myIDs.append(f'{doc.id}') return render(request, 'index.html', { "weight":"abc", "firstRow":myIDs[0], "secondRow":myIDs[1], "thirdRow":myIDs[2], "fourthRow":myIDs[3], "fifthRow":myIDs[4], "sixthRow":myIDs[5], "seventhRow":myIDs[6], }) After that, I created a very basic HTML code just to display the document IDs as follows: <html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <td>{{ firstRow }}</td> <tr> <td>{{ secondRow }}</td> </tr> <tr> <td>{{ thirdRow }}</td> </tr> <tr> <td>{{ fourthRow }}</td> </tr> <tr> <td>{{ fifthRow }}</td> </tr> <tr> <td>{{ sixthRow }}</td> </tr> <tr> <td>{{ seventhRow }}</td> </tr> </tr> </table> </body> </html> Till this point I am just doing very basic stuff. But I am new to Django and Python for the Web, so my question is: how can I make it so that the HTML rows become adaptive based on the number of documents? For example, if I have 20 documents, I want to make …