Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't identify elements after ajax insert
There is a data in Django DB, when html page loaded it sends request to db and create html block in Django template, and at last it insert to html by id. This part works, checkboxes creates and all is good, but there is no elements is I try to find them by id after ajax insert. How to to get access them? html: <div id="fill-statuses" status-table-url="{% url 'ajax_status_data' %}"></div> Django template: {% for status in statuses %} <label class="toggle"> <input class="toggle__input" type="checkbox" id="{{ status.status_new }}_status_check_box"> <span class="toggle__label"> <span class="toggle__text">{{ status.status_new }}</span> </span> </label> {% endfor %} view.py: def fill_status_check_boxes(request): statuses = TaskStatus.objects.values('status_new').distinct return render(request, 'persons/statuses_for_filter.html', {'statuses': statuses}) And now js block, with comments: function fill_status_check_boxes() { const url = $("#fill-statuses").attr('status-table-url') $.ajax({ url: url, success: function (data) { $('#fill-statuses').html(data) }, complete: function () { console.log(document.querySelectorAll("[id*='status_check_box']")) //return array with elements, that's why I thought that all works, when tested it } }) console.log(document.querySelectorAll("[id*='status_check_box']")) //but here return empty array [] } fill_status_check_boxes() console.log(document.querySelectorAll("[id*='status_check_box']")) //and here also return empty array [] -
bulk create in django with foreign key
Models: class Author(Base): name = models.CharField(max_length=100, unique=True) class Book(Base): name = models.CharField(max_length=100, unique=True) class AuthorBookAssn(Base): author = models.ForeignKey(Author) book = models.ForeignKey(Book) I have an api to create a book, and along with the book data we would also get a list of author ids. Now for each book we need to create one/more records (depending on the author ids provided) in the AuthorBookAssn table. What is the best way to do this and can the create be done in bulk. Currently the approach is to get the author objects for each of the ids in the list and then call AuthorBookAssn.objects.create(book=book_instance,author=author_instance) -
Get user group's permission from request.user in dajngo?
I had created a group with certain permission, and added a user to that group. Now, with the request.user can we able to get the group's permission and grant permission to the respective view class.? For user permission we can do this, request.user.has_perm("app_label.code_name") For user group's permission? -
Test whether a Django migration has been applied to a DB
I have a django project, and I wish to update a MySQL database from a previous version of the codebase to be compatible with the current version. I have all of the migrations for the project, but I do not know which was the last one applied to this alternate database. I can try and determine this manually, but I was wondering if there was an easier automated way of finding which the first unapplied migration is. -
Django Keep connection with route through standalone frontend
I am working on a chatbot and want to deploy it in Django but I am using a standalone frontend. I have little to no knowledge about JavaScript and copied this Script from somewhere: onSendButton(chatbox) { var textField=chatbox.querySelector('input'); let text1=textField.value if(text1==="") { return; } let msg1={name: "User", message: text1} this.messages.push(msg1); this.updateChatText(chatbox) textField.value='' fetch('http://localhost:8000/chat', { method: 'POST', body: JSON.stringify({message: text1}), mode: 'cors', headers: { 'Content-Type': 'application/json' }, }) .then(r => r.json()) .then(r => { console.log(r) let msg2={name: "CareAll", message: r.answer}; this.messages.push(msg2); if("follow_up" in r) { let msg3={name: "CareAll", message: r.follow_up}; this.messages.push(msg3) } this.updateChatText(chatbox) textField.value='' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value='' }); } This function is for /chat route def chat_bot_response(request): if request.method == "POST": u_msg = json.loads(request.body)["message"] ints = predict_class(u_msg, cb_model) resp = {"answer": getResponse(ints, intents)} maxConf = max(ints, key=lambda x: x["probability"]) if maxConf["intent"] not in [ "greeting", "farewell", "about_self", "about_self_function", "question", "unknown", "yes_to_symptom", "no_to_symptom", ]: RESP_LIST.append(resp["answer"]) resp["answer"] = "Do You Have other symptoms?" if maxConf["intent"] == "yes_to_symptom": print(RESP_LIST) elif maxConf["intent"] == "no_to_symptom": resp["answer"] = RESP_LIST[0] return JsonResponse(resp) What I am trying to do is, I want to stay in this function when the chatbox is opened until the user leaves the page. Will I need to improve JavaScript? use … -
Django, admin panel, dependence of the values of one ForeignKey field available for selection on the value selected in another ForeignKey field
I have models: models.py class CommentCollection(models.Model): name = models.CharField(max_length=50) class Comment(models.Model): comments_collection = models.ForeignKey(CommentCollection, related_name='comments', on_delete=models.CASCADE) reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True, on_delete=models.CASCADE) text = models.TextField() user = models.ForeignKey(User, related_name='user_comments', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_public = models.BooleanField(default=False, verbose_name='Published') <admin.py> @admin.register(CommentCollection) class CommentCollectionAdmin(admin.ModelAdmin): list_display = ['id', 'name'] How to make it so that: When adding a new comment via the admin panel, after filling in the "comments_collection" field (selection from the CommentCollection model), only those comments that belong to the same collection of comments are displayed in the reply_to field for selection. @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('comments_collection', 'user', 'created', 'is_public') -
how to set password for user signup with social accounts in django
i am using django-allauth. I want that when users signup with social accounts, redirect to set the password page. I do not know what to do. Any suggestion. -
Django unit tests - django.db.utils.IntegrityError: duplicate key value violates
What's the best way class BankLoanApplicationFile(TestCase): """Test cases for loan_application.py file.""" def setUp(self) -> None: """Set up configuration.""" self.loan_product = mock.Mock(spec=LoanProduct) self.loan_type = LoanType.objects.create() self.loan_usage = LoanUsage.objects.create() self.profession = Profession.objects.create(name='Architekt/in') def tearDown(self) -> None: self.loan_type.delete() self.loan_usage.delete() This is the error : django.db.utils.IntegrityError: duplicate key value violates unique constraint. Whats the best way of ignoring this error with Django tests, I have read several post about a similar issue, but I didn't get a solution -
Change DjangoMPTT admin model name
I have the following MPTTModel and admin.py: class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] admin.site.register(infoModels.Category) When I am at the admin page the model appears as "Categorys", how can I change that to be "Categories"? -
How to send emails with Django/Celery based on DateTimes stored in the database?
I want to send reminder emails based on different dates saved in the database. I saw some links that was kinda related to that but most of them was really messy. Table send_email_at: [2022/07/12, 2022/08/19, 2022/07/23, ...] So the ideal would be to get all dates > now and if it's due just send the email -
API security questions in Django & React - Can Django validate if the userid in API == userid in Token?
In Django's views.py I have the following code: class MutatieView(viewsets.ModelViewSet): # authentication_classes = (TokenAuthentication,) authentication_classes = (JWTAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = MutatieSerializer queryset = Mutatie.objects.all() def get_queryset(self, **kwargs): user_mutatie = Mutatie.objects.filter(userid=self.kwargs['userid']) return user_mutatie In React a GET request is sent with the correct token in the header. But I commented out the original line (see below) and requested userid=1 instead of the userid as a variable of the current user which is 2. export const apiSlice = createApi({ reducerPath: "api", baseQuery: fetchBaseQuery({ baseUrl: "http://127.0.0.1:8000/api/", prepareHeaders: (headers, { getState }) => { const access = (getState() as RootState).auth.access if (access) { headers.set('Authorization', `Bearer ${access}`); } return headers }, }), tagTypes: ['MyMutatie',], endpoints: (builder) => ({ ... myMutatieList: builder.query<IMutatie[], number>({ query: (userid:number) => ({ url: `mutaties/1/`, // url: `mutaties/${userid}/`, }), providesTags: ['MyMutatie'] }), ... }), }); Now I get user1's data, which is a problem. Django should be able to see in the token that the correct userid=2 and not 1, How to achieve such a validation? Is the developer the only one to manipulate api calls like in the code above or are there other ways? In postman, but django only allows APIs from the given domain? Can that also … -
create an other table during tests manually in django webapp
I'm creating some tests in my django web app with selenium. Django create a test database with all tables. In my case however I have a model Users. I want that django create also users table when I run this command in terminal python3.9 manage.py test -v3 This command goes in error: Running post-migrate handlers for application contenttypes Adding content type 'contenttypes | contenttype' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Running post-migrate handlers for application sessions Adding content type 'sessions | session' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Running post-migrate handlers for application pygiustizia Adding content type 'pygiustizia | member' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' System check identified no issues (0 silenced). test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ... nel costruttore model Users ERROR ====================================================================== ERROR: test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) … -
Is it necessary to use class based views in django with react-frontend application or we can work with functional view also for login authentication?
I have gone through a few tutorials on user authentication in a Django + React web app. All of them simply use class based views in Django for login backend with react frontend. Any suggestion to work with functional views? -
Issue when running manage.py runserver (Django)
I was about to run my colleague's Django project. She runs it in Apple Mac and I am about to run it in my Windows. In this scenario, I was running python manage.py runserver in my virtual environment as shown here. After that, it prompts a window indicating how to open the file like this instead of running the server. If the command is run correctly, it will show runs this. I am not sure what I am doing here. Is it because of the project was created in Mac? I did create a new virtual environment on my Windows, though everything is okay. Any help would be highly appreciated. Thank you. -
I want to understand what this code does, django we application [closed]
i want to know what exactly this code does during making webApp --models.py-- From django.db import models #1 From django.constrib.auth.models import User#2 Class Notes(models.Model): user = model.Foreignkey(User, on_delete=models.CASCADE) #3 -
models.UniqueConstraint doesn't raise an error when submitting the form
I am wondering why I am not getting an error when I submit a form where I've added a UniqueConstraint on two of the fields together; the data doesn't get submitted to the database (which is expected because of the constraint I've added to the model) and all that happens is that the same form is returned. I want some sort of indication under the Key Name field to say something like "Key Name already exists". Here is my code: In models.py class Meta: verbose_name = "Key Definition" constraints = [ models.UniqueConstraint(fields=['key_name', 'developer_email'], name='unique key names for each user') ] In forms.py class KeyDefinitionForm (BSModalModelForm) : ## code I have not included goes here ## def save(self): log.debug("ENTER: forms.KeyDefinitionForm.save") if self.request: instance = super(CreateUpdateAjaxMixin, self).save() log.debug("EXIT: forms.KeyDefinitionForm.save") return instance In views.py class KeyDefinitionView (BSModalCreateView) : """Class based view for key definition loading form.""" model = KeyDefinition form_class = KeyDefinitionForm template_name = 'generate_keys/keydef_add_modal.html' body_template_name = 'generate_keys/keydef_add_body.html' def get(self, request): log.debug("ENTER: views.KeyDefinitionView.get()") form = self.form_class( initial = { 'developer_email' : request.user.email, 'issue_date' : datetime.date.today(), 'HGE_TLS' : 'N', } ) data = { 'form' : form, } result = render(request, self.template_name, data) log.debug("EXIT: views.KeyDefinitionView.get()") return result def post(self, request, *args, **kwargs) : log.debug("ENTER: … -
Reverse lookup inside a queryset in django
I have three models in my Django app. # models.py class Membership(models.Model): field1 field2 class MembershipServiceDetails(models.Model): membership = models.ForeignKey(Membership, on_delete=models.CASCADE,related_name="msd_services") service = models.ForeignKey(Service,blank=True, null=True, on_delete=models.CASCADE) field3 class MembershipSubscriber(models.Model): membership = models.ForeignKey(Membership, blank=True, null=True, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE) field4 Now I want to query the service data with customers details. But the models are related through Membership only. I'm trying something like this service_details = MembershipServiceDetails.objects.select_related('membership', 'service').annotate( service_data=F('membership').membershipsubscriber_set.first() ) Obviously it didn't work. How can this be achieved? Any help would be appreciated. -
getting error in user_profile form submition
I am getting error user_profile() got an unexpected keyword argument 'phoneNumber' Using the post method and trying to post data to the database but getting this error. model.py class user_profile(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) phoneNumber=models.CharField( max_length=12, blank=True) name=models.CharField(max_length=100, blank=True) address=models.CharField(max_length=500,blank=True) user_profile.html {% extends 'firmApp/basic.html'%} {% block body%} <div class="row"> <div class="col-md-4"> <form action="/user_profile/" method="post" >{% csrf_token %} <div class="mb-3"> <label for="name" class="form-label">Full-Name</label> <input type="text" class="form-control" name="Name" > <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" name="address"> </div> <div class="mb-3"> <label for="phoneNumber" class="form-label">Contact Number</label> <input type="text" class="form-control" name="phoneNumber"> </div> <div class="mb-3"> <label for="formFile" class="form-label">select image</label> <input class="form-control" type="file" name="formFile"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {%endblock%} views.py def user_profile(request): if request.method=="POST": phoneNumber=request.POST.get('phoneNumber') name=request.POST.get('Name') address=request.POST.get('address') user=request.user print(user) profile=user_profile(phoneNumber=phoneNumber, name=name, address=address,user=user) profile.save() return render(request, "firmApp/blog/user_profile.html") I have checked the complete code but am unable to solve the issue. I am getting below error user_profile() got an unexpected keyword argument 'phoneNomber' -
I want to get data from JavaScript with Django
There is price filtering written in JavaScript in the template. I want to take the price range given in this filter with dajngo and write a filtering function. I couldn't because I don't know JavaScript. How will I do? So, i want to write a django function that takes the given start and end values and sorts the products accordingly. main.js // PRICE SLIDER var slider = document.getElementById('price-slider'); if (slider) { noUiSlider.create(slider, { start: [1, 100], connect: true, tooltips: [true, true], format: { to: function(value) { return value.toFixed(2) + '₼'; }, from: function(value) { return value } }, range: { 'min': 1, 'max': 100 } }); } -
How to access all the object in the params object in Django html template?
I have a function send a confirmation email template to user, the params on argument contains two object booking which is a Django object from DB and emails_text object which pulling from a json file and definitely I can access it when I print it import json with open('emails_text.json') as json_file: emails_text = json.load(json_file) my emails_text.json file { "booking_confirmation_email_template": { "title": "booking confirmation", xxxxx } } but the confirmation function can read the booking object but not the emails_text def preview_confirmation_email(self, request, object_id, **kwargs): params = { 'booking': Booking.objects.get(id=object_id), 'emails_text': emails_text['booking_confirmation_email_template'], } return HttpResponse(content=render_email_template('email/booking/confirmation.html', params)) my confirmation.html is as follow {% extends "email/sook_booking/temp_confirmation_base.html" %} {% load static %} {% load booking %} {% block title %}Booking Confirmation{% endblock %} xxxxxxxxx <h1 class="email-title">{{emails_text.title}}</h1> xxxxxxx -
Error with dj_rest_auth.jwt_auth.JWTCookieAuthentication
Everytime I run my server, I get this error on my terminal. I have tried researching about the cause but no luck with a response. This is the error below: CreateProfileView: could not resolve authenticator <class 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'>. There was no OpenApiAuthenticationExtension registered for that class. Try creating one by subclassing it. Ignoring for now. This is my rest_framework settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } Thanks. -
how to calculate students total marks in django using total function and sort
model class from django.db import models class Student(models.Model): Name = models.CharField(max_length=50,) Roll_no = models.IntegerField(default = 0 , unique = True ) Emailid = models.EmailField(max_length=54 ) Submrk1 = models.PositiveIntegerField() Submrk2 = models.PositiveIntegerField() Submrk3 = models.PositiveIntegerField() Total = models.IntegerField(default = total) def __str__(self): return self.Name + self.Total def total(self): self.Total = self.Submrk1 + self.Submrk2 + self.Submrk3 return self.Total views from django.shortcuts import render , redirect from .models import Student from django.shortcuts import HttpResponseRedirect def liststu(request): student = Student.objects.all() return render(request, 'liststu.html',{'student': student}) def Createstu(request): if request.method == 'POST': name = request.POST.get('name') rollno = request.POST.get('rollno') email = request.POST.get('email') sub1 = request.POST.get('sub1') sub2 = request.POST.get('sub2') sub3 = request.POST.get('sub3') stu = Student.objects.create(Name = name,Roll_no = rollno, Emailid = email, Submrk1 = sub1, Submrk2 = sub2 , Submrk3 = sub3) return HttpResponseRedirect('list') else: return render(request, 'create.html') def sort(request): ctx = Student.objects.order_by('Total') return render(request, 'liststu.html' , {'student':ctx}) -
Django HTML image not found but path is correct
So i am creating a list with images but the image is not showing. This is my model: enter image description here This is my view: enter image description here And this is my directory: enter image description here I think it should work since the path is correct, but it is not working. -
AttributeError in django(Got AttributeError when attempting to get a value for field)
views: class ProductListView(APIView): def get (self,request): products = Product.objects.all() serializer = ProductSerializer(products,many=True, context={'request' : request}) return Response(serializer.data) serializer: class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) file_set = ProductsFileSerializer(many=True) class Meta: model = Product fields = ('title','description','avatar','categories','file_set') model: class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) avatar = models.ImageField(blank=True, upload_to="products/") is_enable = models.BooleanField(default=True) categories = models.ManyToManyField('Category' , verbose_name='categories' , blank=True ) class Meta: db_table = 'products' verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.title my error: Got AttributeError when attempting to get a value for field file_set on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'file_set'. -
Rendering highest integer value from three models instances in django
I have three models which are related all to one model. class MyModelParent(models.Model): name = models.CharField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MyFirstModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="first_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MySecondModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="second_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MyThirdModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="third_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.ranking or "" I am rendering MyParentModel in DetailView (CBV) and passing related models as a context to render individual models 'ranking' field on the same template. Now I need to render same 'ranking' on MyParentModel ListView, but I only want to display 'ranking' which has highest value. Question is, how I can compare my related models 'ranking integer value' and display highest on MyParentModel ListView page? I am on learning curve so appreciate your help...