Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate random uid and token in django without generating models and logins of user
I have to activate user without models. I am not generating any user. I want to generate random uid and token. for that I want to pass this uid and token in /activate/{uid}/{token} link. I created this code in view for generate uid and token: class ActivateUser(CreateAPIView): def get(self, request, uid, token, format = None): payload = {'uid': uid, 'token': token} print("payload : " , payload) url = "http://localhost:8000/api/auth/users/activate/" response = request.post(url, data = payload) if response.status_code == 204: return Response({}, response.status_code) else: return Response(response.json()) For activate user I generate this link in url re_path('api/auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/',ActivateUser.as_view()) create activation url in setting.py DJOSER = {'ACTIVATION_URL': 'activate/{uid}/{token}/', } -
Django How to sign up for membership on another page
I am a student who is learning Django. If you press the OK button on the sign-up page, the sign-up is complete! I'd like to put the confirmation button in another html and save what I entered on the membership page, is it possible? To summarize, I would like to move the button on my membership to Different html so that my membership can be completed. register.html <form method="post" class="post-form"> {% include "accounts/form_errors.html" %} {% csrf_token %} <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label"><b>이름</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" id="name" value="{{ form.name.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="username" class="col-sm-2 col-form-label"><b>아이디</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="username" id="username" value="{{ form.username.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="password1" class="col-sm-2 col-form-label"><b>비밀번호</b></label> <div class="col-sm-10"> <input type="password" class="form-control" name="password1" id="password1" value="{{ form.password1.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="password2" class="col-sm-2 col-form-label"><b>비밀번호 확인</b></label> <div class="col-sm-10"> <input type="password" class="form-control" name="password2" id="password2" value="{{ form.password2.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="phone" class="col-sm-2 col-form-label"><b>전화번호</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="phone" id="phone" value="{{ form.phone.value|default_if_none:'' }}"> </div> </div> <div class="form-group row"> <label for="email" class="col-sm-2 col-form-label"><b>이메일</b></label> <div class="col-sm-10"> <input type="text" class="form-control" name="email" id="email" value="{{ form.email.value|default_if_none:'' }}"> </div> </div> <button type="submit" style="background: #637B46; float: right; border: white" … -
Why serving static files are an issue in Python apps
I don't seem to understand the issue with serving static files in Python apps, for example Django. Now I am reading a documentation of WhiteNoise and first question is why it was developed in the first place? I mean what problem it solves? Why we can't save all the static files in /static folder and copy it to hosting. -
call update of a serializer in a function in django
I have this date coming from the frontend: d = {'dispatch_date': '2021-08-25T10:40:19.783Z', 'send_from_warehouse': 2, 'sales_order': 635, 'flows': [{'flow': 67, 'kit': 8, 'asked_quantity': 9, 'alloted_quantity': '9'}, {'flow': 67, 'kit': 3, 'asked_quantity': 8, 'alloted_quantity': '0'}, {'flow': 67, 'kit': 49, 'asked_quantity': 7, 'alloted_quantity': '0'}], 'model': 'Rent', 'vehicle_type': 'Part Load', 'transport_by': 4, 'expected_delivery': '2021-08-25T10:40:19.783Z', 'owner': 2, 'transaction_no': 2807} using this data I want to edit an object of Material Request with id 635. How do I call the edit from serializer of Material Request? class MaterialRequestFlowSerializer(serializers.ModelSerializer): class Meta: model = MaterialRequestFlow fields = "__all__" class MaterialRequestSerializer(serializers.ModelSerializer): flows = MaterialRequestFlowSerializer(many=True) class Meta: model = MaterialRequest fields = "__all__" def create(self, validated_data): print("validated", validated_data) items_objects = validated_data.pop('flows', None) prdcts = [] for item in items_objects: i = MaterialRequestFlow.objects.create(**item) prdcts.append(i) instance = MaterialRequest.objects.create(**validated_data) print("prdcts", prdcts) instance.flows.set(prdcts) return instance def update(self, instance, validated_data): print("s") items_objects = validated_data.pop('flows',None) prdcts = [] for item in items_objects: print("item", item) fk_instance, created = MaterialRequestFlow.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(fk_instance.pk) instance.flows.set(prdcts) instance = super(MaterialRequestSerializer, self).update(instance, validated_data) return instance -
How to run a hub pulled docker image setting the environment variables
I have a Django project and I'm trying to deploy it on an AWS EC2 instance. I've created 2 docker images (application and nginx), tested locally, pushed to hub, but when I pull in my EC2 instance and try to run it, I'm getting environment variable errors like this one: File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 90, in __getattr__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I've tried to create the .env file in the root folder and run: docker run <image_id> --env-file ./.env Also tried to set the varible manually with: expose MY_VAR='something' Still not working. Is there a specific way to run images that was created and pushed with docker-compose, setting the environment variables? -
I am trying to add Twilio broadcast SMS feature to my Django app, but can't work out how to retrieve all Database phone numbers
I have created a 'Post' model in my django app that uploads a basic article to the database. I am trying to implement a feature that notifies users that a new article has been uploaded via SMS, but this needs to be sent to all users who have registered their number in the database (saved in a separate 'Profile' model). I have added a 'save' function to the model that sends the SMS when the post is uploaded: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() detail_text = models.TextField(default='') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN user_numbers = '' client = Client(account_sid, auth_token) message = client.messages.create( body= 'Hello, a new article is available from your dashboard.', from_= settings.TWILIO_NUMBER, to = user_numbers ) print(message.sid) return super().save(*args, **kwargs) I have made the API work with a single number, hard-coded in the app, but now want to draw numbers from the database and send to all users who have registered their mobile number. I have tried using Profile.objects.get(phone_numbers) but this didn't work. Looking at the Twilio docs I am minded that I will need to save the numbers in settings.py … -
How to get the user that modified an object? django-simple-history
I am trying to save the history of an object by using django-simply-history library, so far i can see the changes of the object itself but not the user that made the changes. I have the following set up. Settings: # settings.py INSTALLED_APPS = [ # ... 'simple_history', # ... ] MIDDLEWARE = [ # ... 'simple_history.middleware.HistoryRequestMiddleware', # ... ] Models: from django.db import models from apps.companies.models import Company from simple_history.models import HistoricalRecords # Create your models here. class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) dateCreated = models.DateTimeField(auto_now_add=True,) dateUpdated = models.DateTimeField(auto_now=True,) telephone = models.CharField(max_length=20, blank=True, null=True) address = models.CharField(max_length=20, blank=True, null=True) email = models.EmailField(max_length=254, blank=True, null=True) history = HistoricalRecords() Then in the Shell i do: customer = Customer.objects.all().last() customer.name = "Test" customer.save() customer.history.all().last() Out[79]: <HistoricalCustomer: Customer object (d2211cc1-9762-4f6d-9086-634deee95b1e) as of 2021-08-24 09:28:44.978543+00:00> # How can I print the user that changed the object???? customer.history.all().last()_history_user Thanks, -
Change model in CreateView dependending on user in django
I want to change the model of a createview dependending on the user. The view class is as follow: class SubirCasoView(LoginRequiredMixin, CreateView): login_url = reverse_lazy('users_app:user-login') template_name = 'casos/crear-caso.html' success_url = reverse_lazy('casos_app:update-caso') def get_form_class(self): current_user = self.request.user if current_user.especialidad == 'Reumatología': self.form_class = CasoReumaForm else: self.form_class = CasoDermaForm return self.form_class def form_valid(self, form): """If the form is valid, save the associated model.""" if 'borrador' == self.request.POST: publicar = False self.object = form.save() self.object.user = self.request.user '''for each in self.cleaned_data['images_description']: ImageDescriptionDerma.objects.create(file=each, caso=self.object) for each in self.cleaned_data['images_evolucion']: ImageEvolucionDerma.objects.create(file=each, caso=self.object)''' else: publicar = True self.object = form.save() self.object.user = self.request.user '''for each in self.cleaned_data['images_description']: ImageDescriptionDerma.objects.create(file=each, caso=self.object) for each in self.cleaned_data['images_evolucion']: ImageEvolucionDerma.objects.create(file=each, caso=self.object)''' return super().form_valid(form) What I was trying to do is something similar to the function 'get_form_class' but with model. I have try it with 'get_object' function but seems not to work. My idea is to do something like: def function_name(self): current_user = self.request.user if current_user.especialidad == 'Reumatología': self.model = CasoReuma else: self.model = CasoDerma return self.model -
id field which is not primary key in django django model
Is it possible to create an id field in a model that is not primary_key in django? If so, how to do it? To be clearer, here is my model: class GWS(models.Model): id = models.CharField(max_length=20,primary_key=False) ... What can I do to prevent the id field from being primary key? api.GWS: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True' -
Why show "django.core.management.base.SystemCheckError" in Django App & can't run the server
I got "django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:" in my Django App. Here is My settings.py code 'rangefilter', 'csp', 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sales', And here is my admin.py code. from django.contrib import admin from .models import Sale_Data from import_export.admin import ExportActionMixin from rangefilter.filters import DateRangeFilter, DateTimeRangeFilter class Sale_Record(ExportActionMixin, admin.ModelAdmin): list_display =("CustomerName","CustomerPhone","Date", "Item", "Qty_Memory", "Qty_HDD", "Total_Qty", "Prices", "SalePerson") search_fields =("CustomerName", "CustomerPhone") list_filter = ('Date', DateRangeFilter) admin.site.register(Sale_Data, Sale_Record) Error show like this Error -
Django with Https CSRF verification failed. Request aborted
I use Django+nginx+uwsgi to build my website. Before I've already followed this https://docs.djangoproject.com/en/3.2/ref/csrf/ to set up CSRF. And when my website was Http, it worked well. But after I change my website to Https, when I wanna POST something from one page to another, it shows Forbidden (403) CSRF verification failed. Request aborted. ... Reason given for failure: Referer checking failed - no Referer. How can I solve this? -
How to prevente empty logging line in console
Im new to django and I used django logging in my settings.py and also have one subprocess which contains another basicConfig. I dont know why do I have empty lines in my logger although once I added logfile and there was no empty line there. The settings.py logging comes in the following: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(name)s - %(levelname)s - %(message)s', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple' }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', } } and this is logger example 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - DEBUG - 123 play 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - INFO - Starte subprocess fuer 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - DEBUG - Closing Stdin 2021-08-24 11:30:58+0200 [-] the basicConfig for subprocess in python is : logging.basicConfig( level=logging.DEBUG, format="%(name)s - %(levelname)s - %(message)s" ,stream=sys.stderr) logging.getLogger("Player").setLevel(logging.DEBUG) -
python- Django : Where does Django "Append a Slash"?
If I have an application called magazine, and its urlpatterns inside urls.py is like this : from django.urls import path from . import views path("articles/<int:pk>", views.get_article, name="article") .. without a trailer slash, then Django should "append a slash", right? Where is this slash appended? I mean is it added only when I handwrite the url in the browser? I mean if there was an anchor tag in a template like this : <a href="{% url 'magazine:article' 5 %}"> Article 5 </a> .. Wouldn't it go and get the path above without a trailer slash, and then an error with Not Found? -
Django - Concat two fields in a Many to Many Relation to search for a string
I'm using Django 3.2.6 and Mysql. I have two models class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Book(models.Model): ... author = models.ManyToManyField(Author, related_name="authors") A Book can have multiple authors and an author can have multiple books. Now I want to write a simple search where users should be able to search using the Author name. Since I will be using this search in different parts of the App, I created a Custom Manager added the following function. def search(self, keyword): return ( self .filter( Q(title__icontains=keyword) | Q(description__icontains=keyword) | Q(isbn__icontains=keyword) | Q(category__name__icontains=keyword) | Q(author__first_name__icontains=keyword) | Q(author__last_name__icontains=keyword) ) .annotate(book_count=Count("id")) .order_by("-id") ) Please note that annotate(book_count=Count("id")) this part is important otherwise it will return duplicate rows if a book has multiple Authors. This works if I'm searching only using first_name or last_name. For example, it will return results if I search "John" or "Smith". But if I Search full name like "John Smith" this will not return any result. So after searching, I modified the function as follows def search(self, keyword): return ( self .annotate( full_name=Concat( "author__first_name", Value(" "), "author__last_name", output_filed=CharField() )) .filter( Q(title__icontains=keyword) | Q(description__icontains=keyword) | Q(isbn__icontains=keyword) | Q(category__name__icontains=keyword) | Q(author__first_name__icontains=keyword) | Q(author__last_name__icontains=keyword) | Q(full_name__icontains=keyword) ) .annotate(book_count=Count("id")) .order_by("-id") ) But … -
Django reverse for 'password_change_done' not found
I have a small application that I'm writing, but I have came into some trouble with the password changing elements used with the Django authentication framework. But I always get the error after changing a password that: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Here is my code below: #account urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] This is my directory structure for the login system: Directory Structure Here's the password_change.html file: <h3 style="text-align: center;">Change your password</h3> <div class="login-form" style="text-align: center; "> <form method="post"> {{ form.as_p }} <p><input type="submit" value="Change"></p> {% csrf_token %} </form> </div> Any help would be greatly appreciated! -
How do I add a default value to a variable and store in the database in django?
I'm very new to the Django framework. I've started working with models and forms in django. I'm facing a problem in storing values to a database. I want to get something like this. from django.db import models class attempt(models.Model): name = models.TextField(max_length=200) department = "Software Development" Now I want to store the variable department in the database. Where for every entry of object of attempt name will be entered by the user but department remains the same. And is stored something like the below-given format in the database id: 1 name: "John Shelby" department: "Software Development" -
How would I implement a PyGame Frontend with Flask Backend for user management? [closed]
In my Pygame application I plan on having a login form. I would like this login form to be connected to a Flask Database in the cloud to allow users to be able to log in to their account from any device with the application. When a user creates an account in my game, I would like a new record to be created in the Flask Database, with their details. This database is checked every time when a user tries to log in. I am not concerned about multiplayer functionality in my game at the moment (i.e. real time interactions with others). I found this post which suggested using Django or Flask as a database management tool but I am unsure of how to implement this practically. -
getting the current user with Django drf and simple jwt
I was trying to get the current user with rest framework and simple jwt I'm new to Django and I wrote a simple view that does(ish) the job class UserDetail(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [JWTAuthentication,] permission_classes = [IsAuthenticated,] but for some reason when I post the user credentials to the endpoint in postman it says { "detail": "Authentication credentials were not provided." } but when I remove the ==> authentication_classes = [JWTAuthentication,] and permission_classes = [IsAuthenticated,] it works and gite the current user, my question is is this the right way of doing it, and are there any risks in doing it this way and if their is a better and more secure way of doing it. thanks in advance!! -
Change BooleanField whenever object is updated
I have a model with an property called changed which I'd like to change to True when the model is changed. But ofcourse I don't want to set it to True on the creation of an object. class SomeModel(models.Model): changed = models.BooleanField(default=False, blank=True, null=True) -
How to edit or delete data in one page in django
I am using Django and I am outputting data to a Table . Modification and deletion of each row implemented the function by passing the argument as the url parameter of the detail page of each row. I want to edit and edit the table itself, which outputs the entire row without going into the detail page. (The detail page is redirected by the table-link function implemented when each row is clicked.) <table id="waitinglist-list-table" class="table table-compact"> <thead> <tr> <th>name</th> <th>age</th> <th>weight</th> <th>register_date</th> <th>Edit</th> <th>Remove</th> </tr> </thead> <tbody> {% for register in register_list %} <tr class="tr-hover table-link" data-link="/register/detail/{{ register.id}}/"> <td>{{ register.name}}</td> <td>{{ register.age }}</td> <td>{{ register.weight}}</td> <td>{{ register.register_date }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit_register">Edit </button> </td> <td> <button data-toggle="modal" data-target="#remove_register" type="button" id="register-remove-button" register-id="{{ register.id }}" class="btn btn-inverse-danger">Remove </button> </td> </tr> {% endfor %} </tbody> </table> In the past, when editing and deleting, the id was requested in the url parameter. def edit_register(request, id): register = Register.objects.get(pk=id) edited_register, errors = Register.register_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) register.name = edited_register.name register.age = edited_register.age register.weight = edited_register.weight register.register_date = edited_register.register_date register.save() return JsonResponse({'code': 'success'}) def delete_register(request, id): register= Register.objects.get(pk=id) register.is_deleted = True register.save() return HttpResponseRedirect(f'/register/') Do you need a way … -
I'm making a like and dislike button function for a blog project Django.(I'm a beginner)
I'm trying to make a like button which also functions as dislike if clicked again by the same user. one user can like multiple posts but only one time, the next click dislikes it. What I've done: I made a Like model in my app. class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timeStamp = models.DateTimeField(auto_now_add=True) Next I made a post_detail view to check if user already have liked it or not. def post_detail(request, id): post = get_object_or_404(Post, pk=id) user_likes_this = post.like_set.filter(user=request.user) and True or False To increase the likes I made a this in view. def like(request, post_id): new_like, created = Like.objects.get_or_create(user=request.user, post_id=post_id) if not created: messages.error(request, "Alread liked the post.") else: messages.success(request, "Liked successfully") What I don't understand is how to call the function and use it on the like button. Please help me in such a way that a newcomer can understand and implement. -
SyntaxError: Unexpected token < in JSON at position 0 when trying to update reaction emojis
I've designed an emoji pane like facebook which is working fine. However, when I wanted to update the emoji "SyntaxError: Unexpected token < in JSON at position 0" is showing. There are also many related files, so don't know what can play an important role to understand the problem. So I'm uploading the GitHub link. This is the GitHub link for the project: project So I tried to find the reason from inspecting in my chrome browser and in the console it was like this>>> Uncaught TypeError: Cannot read property 'classList' of null at uppost_func.js:21 at dispatch (jquery-3.5.1.slim.min.js:2) at v.handle (jquery-3.5.1.slim.min.js:2) post_func.js:49 POST http://127.0.0.1:8000/react/post/2 500 (Internal Server Error) My uppost_func.js is like this. I've highlighted line number 21 in the code with #### marks>>> function getCookie(name) { var cookieVal = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieVal = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieVal; } function dropdownSettings(node) { let dropdownElem = node.querySelector(".delete-edit-panel > .dropdown"); $(window).on("resize", () => { if (window.innerWidth < 800) { dropdownElem.classList.add("dropleft"); } else { … -
Django include with variable doesn´t give expected results
So I am currently working on a rather Django Project. Since I didn´t start the project and am basically just extending the existing code I am not quite sure if my inputs are blocked through some sort of other configuration but my quite basic task doesnt give me the expected result. So my Main Screen consists of three different templates which are the HomeView and the RootView (which includes the "menu_main" & the "menu_topbar). My goal is to pass context to the menu_main but since it doesn´t have its own view I can´t seem to make it work. The RootView is quite basic and looks like this: class RootView(StrongholdPublicMixin, SimpleView): extra_context = {'home_view': setting_home_view.value} template_name = 'appearance/root.html' def get_extra_context(self): context = super().get_extra_context() context.update( { 'tree_data': Cabinet.objects.all(), }) return context While the context is added to the RootView I cannot seem to pass it to the menu_main (I need the List which is assigned to "tree_data"). I also tried changing my include of the menu_main to "% include 'appearance/menu_main.html' with sample="WORKING" %}" simply adding the "with ...etc." to it but I am not able to access the sample variable in menu_main. In the RootView HTML-File the menu_main include would look like … -
How to restrict options of a select when refreshing the page (dependent selects)?
I'm building a project using Django. I have a form in my project that has two dependent selects (dropdown list). The child select relies on a previously selected option of the parent select, so the child select displays a list of filtered options. They work well, except when I refresh the page the child select loads the entire list of options (not the options related to the parent select option). So I would like to know how can I limit the options of the child select to the selected option of its parent. Thank you in advance. -
How to create form controlling section?
I have a form. I am splitting the form to sections. I created a step form structure. User should move step by step in this structure. I want to create another section where user can check user's answers before submitting the form. But I do not know how can I get and display the answers without saving form. How can I do it? template <form id="msform" method="POST"> {% csrf_token %} .... <fieldset> <h3>D Section</h3> <div class="row"> <div class="col-2"></div> <div class="col-8"> {{ form.answer1|as_crispy_field }} {{ form.answer2|as_crispy_field }} {{ form.answer3|as_crispy_field }} </div> <div class="col-2"></div> </div> <input type="button" name="previous" class="previous btn btn-outline-dark" value="Geri" /> <input type="button" name="make_payment" class="next btn btn-outline-primary" value="Kontrol" /> </fieldset> .... <fieldset> <h1>CONTROL SECTION</h1> <input type="button" name="previous" class="previous btn btn-outline-dark" value="Previous" /> <input type="button" name="make_payment" class="next btn btn-outline-primary" value="Gönder" /> </fieldset> </form> To be clear: