Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login Authentication with simplejwt in Django Rest Framework with templates and ajax
I am trying to make an application with Django Rest Framework and template without using any front-end application. I created the login form and user list by following this documentation https://www.django-rest-framework.org/topics/html-and-forms/. It works fine when submitting forms and showing list with templates. But when I am trying to authenticate login with simplejwt from the browser, the authentication fails. Failed Authentication Then I looked around and found this documentation https://ilovedjango.com/django/rest-api-framework/authentication/tips/working-example-of-jwt-authentication-with-ajax-django-rest-framework/ . I can use the ajax post call to get the token and set it to local storage on submit and set the header of another API later from the local storage, but in that case, it is not going to the action="{% url 'user:user-list-list' %}" of the form in the template after submit. So it stays on the login page and hits only the token/ URL for the token. When I add location.href = "{% url 'user:user-list-list' %}" in the ajax success, it loads the user_list but says 401 unauthorized. Here is my user_login.html template: {% load rest_framework %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <h1>User Login</h1> <form action="{% url 'user:user-list-list' %}" method="POST" id="login"> {% csrf_token %} <div class="form-group "> <label>Username</label> <input id="username" name="username" … -
how can i put a search box in my django app?
my code trying to make a search box for searching books is here, im trying to make a search box, when user enters the name of a book , like google, it be shown on page , when i add {{form}} to book.html file it has to shows a box, but it doesnt , views.py: def books(request): if request.method == 'POST': form = DashboardFom(request.POST) text = request.POST['text'] url = 'https://www.googleapis.com/books/v1/volumes?q='+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'catagories':answer['items'][i]['volumeInfo'].get('catagories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'] [i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLink') } result_list.append(result_dict) context={ 'form':form, 'result':result_list, } return render(request,'dashboard/books.html',context) else: form = DashboardFom() context = {'form':form} return render(request,'dashboard/books.html',context) forms.py: class DashboardFom(forms.Form): text = forms.CharField(max_length=100,label='Enter your search : ') and also my books.html: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search books and browse your favorite</h2> <p>just enter the search query to obtain the results</p><b></b> <form action="" method="POST"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> {% for result in results %} <a href="{{result.preview}}" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="{{result.thumbnail}}" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">{{result.title}}</h3> <b> <u> <h5 class="p-0 … -
How do I rename app on Github marketplace
I have a marketplace app https://github.com/marketplace/django-doctor/ (For context it offers fixes to Python and Django mistakes right inside the Github PR). but since creating the marketplace app I renamed the product to Code Review Doctor (it used to only offer fixes to Django code, but expanded to Python too and so the name had to change oops) I cannot see any way to rename the app and the link. Is this achievable some other way? I can't find a way to contact GitHub customer support. -
Why am I getting an error that my model form object has no attribute 'cleaned_data'?
I have a form on a page that users use to write comments. There is a view (comment) that should take in the users inputs along with some other information and save it to a model. However, when I tested it out, I got the error: 'CommentForm' object has no attribute 'cleaned_data' How do I fix this? views.py: def comment(request, id): if request.method == 'POST': form = CommentForm(request.POST) # the form if form.is_valid: current = get_object_or_404(Listing, id=id) user = User.objects.get(pk=request.user.id) obj = Comment() # the model obj.user = user obj.listing = current obj.date = datetime.datetime.now() obj.title = form.cleaned_data['title'] # this is where the error occurs obj.comment = form.cleaned_data['comment'] obj.rating = form.cleaned_data['rating'] obj.save() return listing(request, current.id, current.name) html: <form action=" {% url 'comment' listing.id %} " method="post" class="comment-form"> {% csrf_token %} <h2>Comment</h2> {{ commentForm.title }} {{ commentForm.comment }} {{ commentForm.rating }} <input type="submit" value="Comment" class="submit-btn"> </form> forms.py: class CommentForm(forms.Form): title = forms.CharField(max_length=60, widget=forms.TextInput(attrs={ 'class': 'comment-title', 'placeholder': 'Title', })) comment = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={ 'class': 'comment', 'placeholder': 'Enter Comment' })) rating = forms.FloatField(min_value=0, max_value=5, widget=forms.NumberInput(attrs={ 'class': 'rating', 'placeholder': 'Rating' })) -
Django - Prevent admin command to run twice
My problem is simple, i have an admin command name "send email": The problem is, the admin user succeed to call this function twice in a row. Probably in click on "Go" many time. So it sent email many time. There is a way to prevent it ? I tried to put a timeout in the end of the admin function "send_email" but it's not good ... It take 10 second between each users, and i have lot of users. def send_email(modeladmin, request, queryset): ... time.sleep(10) -
Does create() method save model object to Django database?
I just came across using create methods in Djangos models.Model subclass. Documentation has this example code: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): book = cls(title=title) # do something with the book return book book = Book.create("Pride and Prejudice") Does this already save new Book object to database? My intuition suggests that save() method should be called on the line # do something with the book or else it should not work. However when I try testing it, it seems that addin save() to it does not affect anything what so ever. Why is that the case and how does it actually save object to database? PS. I came across this while trying to learn testing with TestCase. If classmethod does not save anything to database problem is probably my testing code, but that would be whole another question. -
I am working on django project through github in which i get this error even after import or install all requirements
raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable -
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)