Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VSCode testing uses production database instead of test database
In VSCode testing, the real production database is used. What should happen is Company.objects.create(name='kfc') creates a single Queue object for that associated Company (shown in models.py if interested) for a test database that's created for this test, then the test database gets destroyed at the end of the test. Instead, VSCode uses my production database, which does include a mcdonald's queue. Because my view uses the pk to determine the queue, and since mcdonald's queue is present, it gets the wrong queue and the test fails. However, when I try to run the tests manually, python manage.py test api.tests, the test passes since I think django's test themselves do use test databases. models.py class Company(models.Model): name = models.CharField(max_length=15) def save(self, *args, **kwargs) -> None: created = bool(self.pk) super().save(*args, **kwargs) if not created: Queue.objects.create(company=self) class Queue(models.Model): company = models.OneToOneField( Company, on_delete=models.CASCADE, related_name="queue") users = models.ManyToManyField(User, through="QueueDetails") @property def length(self): return len(self.users.all()) @property def sorted_users(self): return self.users.all().order_by("queue_details__joined_at") def __str__(self) -> str: return f"{self.company}'s queue" Please let me know if I'm missing something and how to make VSCode work with Django tests, thanks. -
webpack_loader.exceptions.WebpackBundleLookupError: Cannot resolve bundle vendor. on webpack loader
I start the server for webpack. The log is here below. yarn dev yarn run v1.22.18 warning ../package.json: No license field warning ../../package.json: No license field $ webpack-dev-server --mode=development <i> [webpack-dev-server] Project is running at: <i> [webpack-dev-server] Loopback: http://localhost:3000/ <i> [webpack-dev-server] On Your Network (IPv4): http://10.41.232.84:3000/ <i> [webpack-dev-server] On Your Network (IPv6): http://[fe80::1]:3000/ <i> [webpack-dev-server] Content not from webpack is served from '/Users/whitebear/MyCode/httproot/aicomposer_cdk/aicomposer/frontend/public' directory (node:50012) [DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details) (Use `node --trace-deprecation ...` to show where the warning was created) asset js/vendor.911d558c052970cd108d.bundle.js 210 KiB [emitted] [immutable] (name: vendor) (id hint: commons) asset js/base.911d558c052970cd108d.bundle.js 54 KiB [emitted] [immutable] (name: base) Entrypoint base 264 KiB = js/vendor.911d558c052970cd108d.bundle.js 210 KiB js/base.911d558c052970cd108d.bundle.js 54 KiB runtime modules 28.3 KiB 13 modules modules by path ./node_modules/ 166 KiB modules by path ./node_modules/webpack-dev-server/client/ 53.5 KiB 12 modules modules by path ./node_modules/style-loader/dist/runtime/*.js 5.75 KiB 6 modules modules by path ./node_modules/webpack/hot/*.js 4.3 KiB 4 modules modules by path ./node_modules/html-entities/lib/*.js 81.3 KiB 4 modules modules by path ./node_modules/css-loader/dist/runtime/*.js 2.33 KiB ./node_modules/css-loader/dist/runtime/noSourceMaps.js 64 bytes [built] [code generated] ./node_modules/css-loader/dist/runtime/api.js 2.26 KiB [built] [code generated] ./node_modules/ansi-html-community/index.js 4.16 KiB [built] [code generated] ./node_modules/events/events.js 14.5 KiB [built] [code generated] modules by path ./static/ … -
Why despite no error, the List View does not work?
I am not getting any error but my list view does not function. The detail view at the top with ID =1 is working fine. I change the ID numbers and can see the different posts. But when I go to the URL http://127.0.0.1:8000/feed/, the detail view remains stuck whereas I should be seeing 3 posts vertically. It is almost as if the page is not refreshing, Perhaps class-based views are better ways to do it, but for my own learning I want to know why this is not working. def feed_detail_view(request, id = 1): obj = Feed.objects.get(id=id) #print(obj) context = { "object" : obj, } return render(request, 'feeds/detail_view.html',context) def feed_list_view(request): queryset = Feed.objects.all() context = { "object_list" : queryset } return render(request, 'feeds/list_view.html',context) #code in my list_view html {% for object in object_list %} {{object.content}} <br/> {{object.user}} <br/> {{object.timestamp|timesince}} {{% endfor %}} -
What does django urlpattern path argument empty (' ') meaning?
what does path('') in urls.py from project mean? This is urls.py from project. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] And this is urls.py from app urlpatterns = [ path('', views.index), path('create/', views.create), path('read/id/', views.read), ] Is path('')in urls.py from project just mean empty? If it is, why when I write localhost:8080/create It will still work? I just routing path('') in urls.py from project Does it mean "except admin/" ..? -
Django DRF: how to groupby on a foreign fields?
I have a model where users can upvote other users for specific topics. Something like: #models.py Class Topic(models.Model): name = models.StringField() def __str__(self): return str(self.name) Class UserUpvotes(models.Model): """Holds total upvotes by user and topic""" user = models.ForeignKey(User) topic= models.ForeignKey(Topic) upvotes = models.PositiveIntegerField(default=0) Using DRF, I have an API that returns the following: topic_id, topic_name, and upvotes, which is the total upvotes for a given topic. One of the project requirements is for the API to use these field names specifically: topic_id, topic_name, and upvotes #serializers.py class TopicUpvotesSerializer(serializers.ModelSerializer): topic_name = serializers.StringRelatedField(source="topic") class Meta: model = UserUpvotes fields = ["topic_id", "topic_name", "upvotes"] My trouble is aggregating these fields. I'm filtering the UserUpvotes by user or team and then aggregating by topic. Desired output This is the result I want to get. When I don't perform any aggregations (and there are views where this will be the case), it works. [ { "topic_name": 3, "topic_name": "Korean Studies", "upvotes": 14 }, { "topic_name": 12, "topic_name": "Inflation", "upvotes": 3 }, ] At first, I tried creating a TopicSerializer, and then assigning it to the topic field in TopicUpvotesSerializer. But then, the resulting json would have a nested "topic" field and the aggragation would fail. Attempt … -
Which one is the correct way of using Python type hints with Django Models?
Which one of these is the correct way to use type annotations for django models? from typing import TypeVar, Generic from app.models import MyModel _T = TypeVar("_T", bound=MyModel) def func(arg: Generic[_T]): ... Or from typing import Type from app.models import MyModel def func(arg: Type(MyModel)): ... Or from app.models import MyModel def func(arg: MyModel): ... -
Javscript: Click event not working as expected?
i am trying to build an ecommerve platform using django and javascript, i have built the django server side, which when i call {{ product.id }} in my template, it should show the id for each product, now i want to get each id when i click on a button but nothing is showing up in the console. This is how the template looks index.html {% for product in products %} <p>{{ product.title }}</p> <button data-product="{{product.id}}" data-action="add" class="update-cart">Add to Cart</button> {% endfor %} now the javascript looks like this cart.js var updateBtns = document.getElementsByClassName('update-cart') console.log("Working"); for (i = 0; i > updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId is:', productId, 'Action is:', action) console.log('USER:', user) }) } this console.log('productId is:', productId, 'Action is:', action) and console.log('USER:', user) does not work. What could i be missing? -
How can I select property method of a django model in sqlalchemy
I have two models named student and payment. The relation is a student has many payment. Their codes are like Class Student(Model): id: IntegerField() name: CharField() payment = relation('Payment') @property get_total_payment(self): //calculate total payment Class Payment(Model): id: IntegerField() amount: IntegerField() student_id: ForeignKey() Now I have written a query like this. select = [ Student.id, Student.name, Markshit.number, Markshit.subject_name, ] query = sa_session.query(*select).join(Markshit).all() I want to add Student.get_total_payment in the query but gets error. How can I solve this? -
Web app security: Sending cookie along with JWT (django rest framework)
I have an Angular web app which works in conjunction with a Django Rest Framework backend. Authentication is done by means of JWT tokens. However, for some management actions, users need to go to the Django admin page. Since the Django admin page works with Cookies instead of JWTs, the user needs to log in again. A minor nuisance, but a nuisance all the same. The question is whether it makes sense to extend the Rest Framework's authentication methods to set a session cookie when the user first receives their JWT? Or would it be better to ditch JWT altogether and use cookies for the web app as well? -
How to order by based on serializer fields in django?
Here I am ordering my response list data based on the obtained value from SerializerMethodField but while doing on this approach my api responding very slowly like 14-15s but without using this sorting and using only queryset the response time is like 12-1300ms so How can I optimize this code ? I think using queryset.order_by would be faster rather than sorting from list but How can I use order_by here since I need to order by the serializermethodfield value. # serializer class MySerializer(serializers.ModelSerializer): duration = serializers.SerializerMethodField() def get_duration(self, obj): dt1 = obj.files.filter(type="1").first().approved_on dt2 = timezone.now() days = (dt2-dt1).days return days # views @api_view("GET"): def get_list_of_items(self, request): user = request.user limit = int(request.GET.get('limit', 30)) offset = int(request.GET.get('off', 0)) max = limit + offset qs = MyModel.objects.filter(user=user, status="DONE").prefetch_related("files") serializer = MySerializer(qs, many=True) sorted_ls = sorted(serializer.data, key=lambda k: k['duration'])[offset:max] return Response{'data':sorted_ls} -
missing 1 required positional argument django _id
I'm trying make cart for delivery site. I've got a lot of problems) there one of them: method remove() missing 1 argument: my view: def cart_remove(request, dish_id): cart = Cart(request) dish = get_object_or_404(Dish, id=dish_id) cart_remove(dish) return redirect('cart:cart_detail') My template: {% for item in cart%} {% with dish=item.dish %} <tr> <td> <a href="{{ dish.get_absolute_url }}"> <img src="{{ dish.picture.url }}" width="100" height="100"> </a> </td> <td>{{dish.name}}</td> <td>{{item.quantity}}</td> <td><a href="{% url 'cart:cart_remove' dish.id %}">Remove</a></td> <td class="num">$ {{item.price}} </td> <td class="num">$ {{item.total_price}} </td> </tr> {% endwith %} {% endfor %} my itter method in Cart class: def __iter__(self): dish_ids = self.cart.keys() dishes = Dish.objects.filter(id__in=dish_ids) for dish in dishes: self.cart[str(dish.id)]['dish'] = dish for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item My little error -
'MyApp' is not a registered namespace
I am trying to add a link from one page to another page. But it generating error of MyApp not registered while I have registered it in urls.py Here is my .html file: <body> <h1>Hello world </h1> <h1> <a href = " {% url 'MyApp: Variable' %} "> Variable Page</a> </h1> </body> Here is my urls.py(MyApp) file: apps_name = 'MyApp' urlpatterns = [ path('', views.simpleView, name = 'Example'), #domain.com\MyApp path('variable/', views.VariableView, name = 'Variable') Here is my urls.py(Mysite) file: urlpatterns = [ path('MyApp/', include('MyApp.urls')), path('admin/', admin.site.urls), and here is my error: NoReverseMatch at /MyApp/ 'MyApp' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/MyApp/ Django Version: 3.2.14 Exception Type: NoReverseMatch Exception Value: 'MyApp' is not a registered namespace Exception Location: C:\Users\DELL\Desktop\DJango\venv\lib\site-packages\django\urls\base.py, line 82, in reverse Python Executable: C:\Users\DELL\Desktop\DJango\venv\Scripts\python.exe Python Version: 3.7.9 Python Path: ['C:\\Users\\DELL\\Desktop\\DJango\\MySite', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\python37.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\DELL\\Desktop\\DJango\\venv', 'C:\\Users\\DELL\\Desktop\\DJango\\venv\\lib\\site-packages'] Server time: Sat, 30 Jul 2022 09:43:01 +0000 -
Why makemigrations in django doesn't work?
I wanted to insert into my database from an Excel file. So I created a model in my models.py file. models.py from django.db import models class Materiau(models.Model): designation = models.CharField(max_length=128) norme = models.CharField(max_length=128) temperature = models.CharField(max_length=128) epaisseur = models.CharField(max_length=128) symbole = models.CharField(max_length=128) rho = models.FloatField(default=0.0) E = models.FloatField(default=0.0) sigy = models.FloatField(default=0.0) Etan = models.FloatField(default=0.0) def __str__(self): return self.designation Then I created a Commands file : Path : my_app/management/commands/update_database.py from django.core.management.base import BaseCommand import pandas as pd from DataMat.models import Materiau from sqlalchemy import create_engine class Command(BaseCommand): def handle(self, *args, **options): df = pd.read_excel('dataframe.xlsx') engine = create_engine('sqlite:///db.sqlite3') df.to_sql(Materiau._meta.db_table, if_exists='replace', con=engine, index=True) Then when I run python manage.py update_database I can see the database being updated in my db.sqlite3 file. But when I run the makemigrations I get no changes detected and I can't see my database in the Django admin section. This is the error I get from Django : no such column: DataMat_materiau.id I don't understand because when I look into my database I can see an index but Django doesn't seem to recognize it. Also in my update_database.py file, I have this message Access to a protected member _meta of a class. Does anyone have an idea on how … -
Cant find the solution or mistake in jinja condition
When implementing the likes counter function, I encountered the fact that the condition for displaying different interface buttons does not work, depending on whether the user's "id" number is in the list of those who have already liked this post. HTML(fragment): {% for posts in current_page.object_list %} {% if user.is_authenticated %} <div class="line" style="display: flex; flex-direction: row; align-items: baseline"> {% if user.id in post.likes_list_id %} <div> <div style="color: green;"> it works </div> </div> {% else %} <div> <div style="color: red;"> not work </div> </div> {% endif %} </div> <div style="padding-left: 10px; color: orange;"> {{user.id}} {{post.likes_list_id}} {{post.likes_list_id.all}} </div> {% endif %} {% endfor %} views.py: def index(request): new_post = New_post_form() db_posts = Post.objects.all() # just for testing testing = Post.objects.get(id=2) foo = testing.likes_list_id() print(foo) posts_division = Paginator(db_posts, 10) requested_page = int(request.GET.get("requested_page", 1)) current_page = posts_division.page(requested_page) return render(request, "network/index.html", { "new_post": new_post, "current_page": current_page, }) model.py: class User(AbstractUser): pass class Post(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="likes", blank=True) def likes_count(self): return self.likes.count() def likes_list_id(self): return self.likes.values_list('id', flat=True) class Meta: ordering = ["-timestamp"] def __str__(self): return f"{self.pk} - {self.user_name}" And I get the following result in the browser: [1]: https://i.stack.imgur.com/d9Jik.jpg Although the user number is … -
pre_save signal not firing on model create or edit
I've use pre_save signals in my django app quite often, including in the file that I'm trying to execute this code in. For some bizzaire reason, this presave signal does't fire on save of any HAddress (create or edit). Any thoughts on why this might not be firing? def assign_government_id(sender, instance, *args, **kwargs): print('hi you') pre_save.connect(assign_government_id, sender=HAddress) No hard errors or anything like that. It just doesn't seem to fire. Thanks! -
Comparing CSV and dictionary
I have a csv file with an entry named Registration Number which is unique. I have a dictionary that has keys as Registration Numbers and values as 'REPORTED' or 'NON-REPORTED'. I want to compare the Registration Number of csv with keys of dictionary and create new column in the csv named 'STATUS' having values as 'REPORTED' or 'NON-REPORTED' from the dictionary values. In djnago, how do I do that? -
Querying objects that is created minutes ago
So , We have a model called Status. Also we have a Datetimefield in it and we add the auto_now_add=True in the model. But the question is how can i query and find the objects that is created only two minutes ago ? -
pan_no field validation in django Template
Hi Everyone i am trying to validate pan_no filed using re in django template it is work, but when field is empty then still showing invalid pan no, i am trying to solve this issue if field is empty then do not check validation. pls help me out. models.py class Pan(models.Model): pan_no = models.CharField(max_length=10, null=True, blank=True) forms.py class PanForm(forms.Form): pan_no = forms.CharField(label='Pan Card Number', max_length=10, required=False) # validate pan_no if field is not none def clean_pan_no(self): pan_no = self.cleaned_data['pan_no'] if pan_no is not None: if not re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$', pan_no): raise forms.ValidationError('Invalid PAN number.') return pan_no views.py def panview(request): if request.method == "POST": form=PanForm(request.POST) if form.is_valid(): pan_no=form.cleaned_data['pan_no'] form.save() messages.success(request, 'success') return redirect("driver_test") context{ 'form': form, } return render(request, 'pan_no.html',context=context) -
Django, custom 404 page redirects to 500 when Debug=False because Django cannot find exception parameter
When Debug = True django returns a Page not found (404) page which is totally fine But when I change Debug = False django return a Server Error (500) and the server shows these requests made: [30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145 [30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145 [30/Jul/2022 12:29:44] "GET /sdfs HTTP/1.1" 500 145 [30/Jul/2022 12:29:45] "GET /favicon.ico HTTP/1.1" 302 0 myproject main urls.py from django.conf.urls import handler404 handler404 = 'myproject.views.custom_page_not_found' please note here that hander404 is not found by django handler404 not found my views.py def custom_page_not_found(request, exception, template_name="errors/404.html"): return render(request, template_name, status=404) Please not here django cannot find the exception parameter exception parameter not found In previous community questions i could not find any question that points to the exception parameter not found issue. Please note that i am not using django templates {% %} in my 404.html file I think when django does not find the exception parameter it returns server error 500. -
What are the consequences of enforcing django foreign keys constraints at database level?
We'd like to add to an existing django app foreign keys implementation at the database level and we wonder what side effects we should expect from this. Some explanations more in details: We have a Django app, based on postgresql backend. Quite a lot of data, foreign keys, tables, etc. It used to be pure django based so we never even noticed that actually django does not implement foreign keys at database level but rather emulates it in the python stack. Now we try to integrate another project which ships SQL statements that we'd like to apply on the django database. So we receive statements like DELETE FROM foo WHERE id=bar. These statements can fail because of foreign keys which are implemented as ON DELETE RESTRICT (or maybe NO ACTION I don't remember right now) initially by django. To solve our issue, we though we could alter the foreign keys in postgres to mimic the django behavior (on delete cascade or set null mainly). This without changing anything in the django code. One comment by 'dirkgroten' found in Django does not honor ON DELETE CASCADE seems to suggest that this would not break the main application but, before we run … -
Django, form.is_valid() What does it check?
I do not use the form of models.form I received and stored each items of request.POST and request.FILES I will make my validation function. So I wonder what validation it does. (ex. input is empty, etc.) -
Django error: "ValueError: Unable to configure handler in 'database_file'
I have trouble with starting my backend in Django with the command python manage.py runserver I am using Anaconda for a virtual environment. Everything is working on Linux systems, but the two Windows developer get the following error: File "C:\Users\vu492\anaconda3\envs\sample_venv\lib\logging\config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'database_file' There are similar questions already online. (ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:) Unlike my issue others get a directory in which something is missing. -
Integration problem Between reactnative app and Django server
When i run the server it shows me a message http://127.0.0.1:8000/. i want to do integration so i need to use this url in reactnative or anyother? -
change rows values in relate to another row
I'm working on leitner flashcards system the whole leitner sys is about BOXes order e.g box1, box2 ,box3 ,so when u solve a card in box1 it gets moved backward to box2 and vise versa .. now, what if I want to change the order of a box? or even delete it? wouldn't be better to change the other boxes orders? e.g [box1, box2, box3] => [box1, box2] so now you got the idea, here's how I implement it in django models: class Box(models.Model): name = models.CharField(max_length=100) order = models.IntegerField(blank=False) end_days = models.IntegerField(blank=False) end_hours = models.IntegerField(blank=False) end_minutes = models.IntegerField(blank=False, default=0) def __str__(self): return self.name now the big Question is , when some row('obj') deleted/order-changed how can I increment/decrement other rows ???! and if u have better idea than what I'm trying to do please share it . regards -
How to integrate dash app into react app?
I have built a dash app but to provide the full solution need to integrate with react app.is there a way to plug dash app within react framework