Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to integrate RazorPay Payment System
The below code of razorpay docs gives in the value of the client-user and the amount of money to be paid. How can I take the amount and username saved in a model in the database.? Like, I have an table of orders and a function is defined inside the Model Class to get the total amount of the whole order(eg. I have two items to buy and the 'get_total' function returns me the total order amount) if request.method == "POST": name = request.POST.get('name') amount = 50000 -
Error while giving following command python manage.py makemigrations
I am giving following command python manage.py makemigrations, but I am getting the error, from employee.forms import EmployeeForm ModuleNotFoundError: No module named 'employee.forms' I am not able to rectify the error please guide -
DRF: Set ChoiceField default programmatically from DB query
I asked a similar question here about setting the default value of a TextChoices field on a model. Now I'm taking it to the next level. I've moved the choices settings from the model to the serializer ChoiceField. The site is Django/DRF/django_tenants backend with Vue frontend. I want the front/backends to be using the same set of choices and, just as important, the same default values. So I created an OptionGroup table. Here are two sample rows from that table (some options omitted): { "results": { "id": 1, "name": "payment_method", "defined_in": "option_table", "default_option": "5", "options": [ { "id": 2, "name": "Bank Transfer", "value": "2" }, { "id": 5, "name": "Credit Card", "value": "5" }, { "id": 8, "name": "PayPal", "value": "8" } ] } } { "results": { "id": 3, "name": "invoice_type", "defined_in": "class", "app_label": "invoices", "choices_class": "InvoiceType", "default_option": "standard", "options": [ { "name": "Standard", "value": "standard" }, { "name": "Retainer", "value": "retainer" }, { "order": 1, "name": "Estimate", "value": "estimate" } ] } } The first one (defined_in = "option_table") has its options defined in a related Option model. The second one has its options defined in a subclass of TextChoices in the backend code. In addition to keeping … -
Parse GraphQL query to find fields to be able to prefetch_related?
When using DjangoListObjectType from graphene_django_extras, I can define a custom qs property on a SearchFilter. The qs function has the object as its only argument, and through that I can get the request, and in turn the query string which includes the queried fields. Before hacking together my own parser to get these fields, am I going about this the wrong way? Or is there something else out there? The idea is to have quite a rigid approach, as we have 7 types of paginated list types with fields that result in a few unnecessary database hits, so we want to prefetch a few fields. Graphene has a dataloader approach which kind of looks right, but more complicated than just prefetching them at the qs stage. -
Django, just showing once when I use multiple forms with rich editor
I am creating comment area and reply to comment area for users. And I using django-ckeditor for this but there is a problem. When I add "reply form" just showing once in the page. Not showing other forms. The reply system its works just its not showing ckeditor(Rich editor). I am add some photos for better understanding: second form in same page: inspect of first form: my Models: class UserMessages(models.Model): postMessages = RichTextUploadingField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) username = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="Username", null=True) replies = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) my Forms: class MessageForm(forms.ModelForm): class Meta: model = UserMessages fields = ("postMessages",) widgets = { "postMessages": forms.TextInput(attrs={"class":"form-control"}), #And I tried this but not works.. class ReplyFormMessage(forms.ModelForm): class Meta: model = UserMessages fields = ("replies",) my HTML: <form method="POST" > {% csrf_token %} {{form.media}} {{ form }} <input type="hidden" name="replies_id" value="{{ message.id }}"> <input type="submit" value="Reply" class="btn btn-default"> </form> as for me, ckeditor just using one id for all form in page. So, do you have an idea? -
Django gabarit tag - how to return a variable as string instead of text
I am working on a django project. I came accross a trouble. I have an instance somewhere in my view called roadnetwork. In my html(or js) template, I would like to get this instance name via {{roadnetwork.name}} as a string and not a text. Any help is appreciated! -
Django POST request pending issues (AJAX) and doesn't come out on the terminal
move post request status stays pending The forward button supposed to send post request(move) and receive by the web server but as in the image nothing come out on the terminal when I pressed the button. here's the involved code: <button class="btn btn-primary btn-lg btn-block"onmousedown="runScript(this)" onmouseup="end()" name="UP" value="up" id="buttonUp" style="margin-bottom: 5px">FORWARD</button> function runScript(button) { counter = setInterval(function(){ $.ajax({ url: 'move', //The URL you defined in urls.py type: "POST", data: { UP: button.value, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(data) { //If you wish you can do additional data manipulation here. // wrapper.innerHTML = count + "bit" + data;\ wrapper.innerHTML = "Ultrasonic: " + data; if (data < 5) { userInput.innerHTML ="Object Close"; } else { userInput.innerHTML =""; } count ++; } }); }, 500); } -
Django: Continue the execution of Cron job even if my server restarts
I have a cron job in Django and I want that to be executed at its scheduled time. But the problem is in between that if my server restarts then the scheduled job is not persisted and is not executed. I want that job to be persisted and executed even if my server is restarted. Thanks in advance! -
Django CKEditor 5 frontend. Submit stops working when I add {{ form.media }} to template
I'm following this guide to set up SKEditor5 for my django project. It works fine in Admin. However, for it to work in my frontend form, I need to add {{ form.media }} and my Submit button simply stops doing anything. Note, without the {{ form.media }}, I do not see SKEditor on the frontend but Submit works just fine. There's very little information about Django CKEditor5 out there. Maybe CKEditor5 only work in Admin and not made for front end? Or maybe I should replace {{ form.media }} with something else? Please, help. models.py from django.db import models from django import forms from django_ckeditor_5.fields import CKEditor5Field from PIL import Image from django.contrib.auth.models import AbstractUser class Article(models.Model): title = models.CharField(max_length=100) content = CKEditor5Field('Content', config_name='extends') def __str__(self): return self.title views.py from django.views.generic import ListView, CreateView from .models import Article class IndexView(ListView): model = Article template_name = 'test_app/index.html' context_object_name = 'articles' class ArticleCreateView(CreateView): model = Article fields = '__all__' template_name = 'test_app/create.html' success_url = '/' create.html <form method="POST" action=""> {% csrf_token %} <p>{{ form.media }}</p> <p>{{ form.as_p }}</p> <input type="submit" value="Add Article"> </form> urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns … -
How to set CSRF token in Django Ajax call in case of a url submit outside a Django form?
I'm trying to make an AJAX call to update the rendered data when clicking on an icon like below. However, it always returns: Forbidden (CSRF token missing or incorrect.): /shuffle_pollers What I understand from the Django doc is that I could set the token within the form, but in my case I don't use a form to call the url. So how can I implement the CSRF token into the Ajax call? // Refresh pollers on shuffle click $('#shuffle-icon').click(function () { // Get the CSRF token function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); // Ajax handler $.ajax ({ url: '/shuffle_pollers', type: 'post', mode: 'same-origin', success: function () { $('.pollerfeed').removeChild(); } }) }) <div class="shuffle-icon-ctn"> <img id="shuffle-icon" src="{% static 'images/shuffle-logo.svg' %}"> </div> def shuffle_pollers(request): if request.method == 'POST': print('Triggered') return request -
How to use data from filter() in template in django python
i want know how can i use data in template here is the model: class NewOrders(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items=models.TextField(null=True) and here is how i am getting data in view using filter method: def Myorders(request): #show my orders morder = NewOrders.objects.filter(user=request.user) print(morder) context={ 'my_orders':morder, } return render(request,'myorder.html',context) which gives my output like this: <QuerySet [<NewOrders: 21>]> now i want this items in model in template: {% for entity in my_orders %} <p> item name: {% entity.items %}</p> {% endfor %} but after dong this i get error: entity.items', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
How to dynamically filter using a ListView
I want to dynamically filter my results in the front-end using only my ListView class with a search input. It should first display the entire list of users, but when something gets typed in the search input it should filter the results based upon that input. What is the best/shortest way to do this using only my classBased View? My current code: Template: <div class="card mt-3"> <div class="card-body"> <form action="" form="get"> <input data-url="{% url 'klantbeheer' %}" class="zoekklanten" name="q" type="text" placeholder="Zoek op contactnaam..."> </form> {% if object_list %} <div class="single-table"> <div class="table-responsive"> <table class="table text-center"> <thead class="text-uppercase bg-dark"> <tr class="text-white"> <th scope="col">Bedrijfsnaam</th> <th scope="col">Contactnaam</th> <th scope="col">Locatie</th> <th scope="col">Actie</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{ user.bedrijfsNaam }}</td> <td>{{ user.contactNaam }}</td> <td>{{ user.adres }}</td> <td> <a href="{% url 'klantupdaten' user.id %}"><i class="fas fa-edit"></i></a> <a href="#" data-url="{% url 'klantverwijderen' user.id %}" class="deletegebruiker" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="fas fa-trash-alt"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> {% else %} <p>Geen gebruikers gevonden</p> <p> <a href="{% url 'klantaanmaken' user.id %}" class="btn btn-primary">Maak klant aan</a> </p> {% endif %} </div> </div> View: class ManageUserView(SuperUserRequired, ListView): model = User template_name = 'webapp/klant/beheerklant.html' #Query based upon contactName def get_queryset(self, query): #Contactnaam bevat QUERY EN … -
Access djagno model before creation one
Consider the following application structure. You have two models: Recipe and Ingredient, which are related to each other (obviously, each recipe has some ingredients and many ingredients can be in some recipes). Note, that you have decided to use M2M (many to many) relation between these two models with an explicit intermediate model -- RecipeIngredient -- which also contains one additional field named amount. With all of the above, I have only two question for you. How would you save Recipe instance with multiple ingredients through django shell if Recipe instance still is not created. You can consider, that you already have ingredients in your DB. And the second one, how one can access amount field while creating a recipe? If you are confused, I can reformulate the question. How you would save a recipe with specified ingredients and their amount? (If there is a simple model relation I can use, please, describe it). from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator, MaxValueValidator User = get_user_model() class Recipe(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recipies', verbose_name='Author of a recipe' ) name = models.CharField(max_length=200, verbose_name='Name of a recipe') image = models.ImageField() text = models.TextField(verbose_name='Description of a recipe') ingredients … -
Django: redirect the user from the login page if he has already logged in
I want to redirect the user from the login page if he is already logged in; this means that the user who logged in will no longer have access to the login page. the login page looks something like this: example.com/login this is my code in view.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: logIn(request, user) return redirect('/') else: messages.info(request, 'username or password is wrong') context = {} return render(request, 'account/login.html', context) -
Django authentication with firebase?
How can I override default Django authentication with firebase authentication with Phone, Google, Facebook, Email? I planned to build a mobile application where I used firebase for authentication ( why firebase because with this I can easily access cloud databases, more control over ads, analytics, testing, and distribution ) But the rest of the things I planned to used Postgres / MongoDB and Django ( why Django it's easy to build pre-build admin panel and manage ) But the problem is that how can I control my Django authentication because 90 to 95 % of databases are stored in Django so I also need that authentication so we can get more control over data with security Like we have a comment, like, a poll system in my application, and the data are stored in Django. So if we have a users model in Django so we can easily map the data in Django otherwise it's taken a lot of effort and it also compromises the security. Note: there might be one solution is there but I don't want to use that because it makes an application is more complex and it also has security issues. The solution is to create … -
run haversine formula on MariaDB server using annotate() in django orm
Hii I trying to run the Haversine formula on the MariaDB base on my model the model is class MeteorologicalSite(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) class Site(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) and this is the Haversine function def Haversine_formula(self, site): from django.db.models.functions import Cos, Sin, ASin, Sqrt, Radians lat1 = Radians(site.lat) lon1 = Radians(site.lon) lat2 = Radians(F("lat")) lon2 = Radians(F("lon")) r = 6372.8 sql_haversine_formula = 2 * r * ASin( Sqrt( Sqrt( Sin((lat1-lat2)/2)**2+ Cos(lat1)* Cos(lat2)* Sin((lon1 - lon2)/2)**2 ) ) MeteorologicalSite.objects.filter(radiation=True)\ .annotate(mycolumn=sql_haversine_formula) and it doesn't run it return <django.db.models.query.QuerySet object at 0xffff57b99ca0> I tried to use lat and lon for 1 and 2 as Decimal directly and it still doesn't work so I understand that my problem is in the way I use annotate or in me sql_haversine_formula Does anyone have an idea why this does not work? sorry for my English -
How to update value when i used only request.POST method for save data into database.? i did not use any form class
enter image description here model for database. enter image description here data save method. -
Make models in admin site appear only in debug mode otherwise display one model
I want to make my models appear in admin site only when debug variable is set to True, when debug is set to False I only want to display one model I am looking for an elegant way to implement this I thought I could do something like this: if not DEBUG: admin.site._registry = {} admin.site.register(Model 1) But where does this code should live? I want it to execute after execution of all admin.py modules from all applications where models registration takes place. To sum it up DEBUG = TRUE Admin site shows: Model 1 Model 2 Model 3 DEBUG = FALSE Admin site shows: Model 1 -
XLWT || IndexError at /XLS tuple index out of range Request Method : GET
I am currently running into the above-mentioned error when running the below code that is supposed to print to pdf when the button is clicked. The following is how the code is called on html <a href="{% url 'printToXLS' %}" class="btn btn-primary">Print To Excel</a> Please see the error message and views.py below Views.py: def printToXLS(request): response = HttpResponse(content_type= 'application/ms-excel') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.xls' wb=xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('TrialBalance') row_num = 0 font_style = xlwt.XFStyle() columns = ('Account' , 'Description' , 'Debit' , 'Credit') all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) for col_num in range(len(xAll_l)): ws.write(row_num , col_num , columns[col_num] , font_style ) font_style = xlwt.XFStyle() for row in xAll_l: row_num += 1 for col_num in range(len(row)): ws.write(row_num , col_num , str(row[col_num]) , font_style) wb.save(response) return response Error : IndexError at /XLS tuple index … -
Login user from different application into Django application
I have a use-case where I have to login a user from different application in my django application. The user will click a button in the primary application where the user data like username, firstname, lastname and userid is sent to me as jwt token. In my application I am decrypting the jwttoken and fetching the user data json and then using django.contrib.auth import login method to login the user and then sending the response user = User.objects.get(user_name=user_name) login(request, user) response = HttpResponse(json.dumps({'message': "you are successfully logined in"}), content_type='application/json') response.status_code = 200 return response where in the primary application then the user is redirected to dashboard of my application whose view is @login_required(login_url='/testserver/user/login/') def dashboard(request): user = User.objects.get(user_name=request.user) return render(request, 'home.html', {'user':user}) the problem is that the user is redirected to /testserver/user/login/ url and if i remove it @login_required(login_url='/testserver/user/login/') then i see that request.user is AnonymousUser how can i fix this to make it end to end working -
DJANGO, returning from AJAX call does not update html
I am updating a db entry through a click on a select dropdown. After confirming the selection I send an AJAX POST to another view that applies required changes on the db and reverse to the previous page. The problem is that the destination page does not reflect the new values unless I refresh. select html (project.html) <select id="update_status_outreach" name="{{outreach.id}}_____{{project.id}}"> {% for outreach_status in outreach_statuses %} {% if outreach_status.0 == outreach.outreach_status %} <option value="{{ outreach.outreach_status }}" selected>{{ outreach.outreach_status }}</option> {%else%} <option value="{{ outreach_status.0}}">{{outreach_status.0}}</option> {% endif %} {%endfor%} </select> Javascript (project.html) document.getElementById("update_status_outreach").onchange = changeListener; function changeListener() { var name = this.name.split("_____"); var project_id = name[1]; var outreach_id = name[0]; var new_status = this.value; if(confirm("Placejpòdore")) { $.ajax({ type: "POST", url: "{% url 'action:update_status_outreach' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", 'project_id': project_id, 'outreach_id': outreach_id, 'new_status': new_status }, }); } } update_status_outreach view in outreach.py @login_required(login_url='action:login') def update_status_outreach(request): project_id = request.POST['project_id'] outreach_id = request.POST['outreach_id'] new_status = request.POST['new_status'] jobproject = get_object_or_404(JobProject, id=project_id) if jobproject.owner != request.user: raise HttpResponse(status=500) else: outreach_to_be_updated = Outreach.objects.get(id=outreach_id) outreach_to_be_updated.outreach_status=new_status outreach_to_be_updated.save() return HttpResponseRedirect(reverse('action:project', args=(project_id,))) project view in project.py @login_required(login_url='action:login') def project(request, project_id): if request.method == 'POST': outreach_id = request.POST.get('outreach_id') new_rank = request.POST.get('new_ranking') update_rank(outreach_id=outreach_id, new_rank=new_rank) project_referred = get_object_or_404(JobProject, id=project_id) jobpositions_referred = JobPosition.objects.filter(jobproject=project_referred) … -
how to format large numbers using spaces instead fo comma?
I am using django.contrib.humanize intcomma tag to format large numbers like this $18,162,711,641 but what I want spaces instead of comma, like this $18 162 711 641 How can I achieve this? Thank you. -
python / django log in issue
Currently I have usertypes in this python/django project and I was able to log in as admin but I am not being able to login as student or staff I am using postgres as data base can anyone please help me ? my models.py file models.py class CustomUser(AbstractUser): user_type_data = ((1,"HOD"), (2,"Staff"), (3,"student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Admin(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Staff(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_picture = models.FileField() address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING) session_start_year = models.DateField(blank=True, null=True) session_end_year = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type==1: Admin.objects.create(admin=instance) if instance.user_type==2: Staff.objects.create(admin=instance) if instance.user_type==3: Students.objects.create(admin=instance, course_id = Courses.objects.get(id=1), session_start_year="2020-04-02", session_end_year="2022-01-01", profile_picture="", gender="") @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): if instance.user_type==1: instance.admin.save() if instance.user_type==2: instance.staff.save() if instance.user_type==3: instance.students.save() here are my views.py file views.py def DoLogin(request): if request.method != "POST": return HttpResponse("<h2> Do log in first </h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get("email"),password=request.POST.get("password")) … -
How to pass context dictionary in django rest framework? Help me and make my life simple and easy
First of all, I want to pass multiple queryset in the same view or you can say same url path or route. In django we pass this context dictionary like this qs = Qs.objects.all() ps = Ps.objects.all() context = { 'qs' : qs, 'ps' : ps } return render(request, 'some.html', context) and in the frontend we just call them via qs or ps and we get the object. I want to do the same in django rest framework and react frontend. @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) related = Product.objects.filter(category=product.category).exclude(_id=pk).order_by('?')[:4] print(related) serializer = ProductSerializer(product, many=False) return Response(serializer.data) I have two queryset here product and related. I want to pass both of them in the same serializer or response. I don't know actually how to pass multiple queryset. In the react frontend const productDetails = useSelector(state => state.productDetails) const {loading, error, product} = productDetails useEffect(() => { dispatch(listProductDetails(match.params.id)) }, [dispatch, match]) const addToCartHandler = () => { history.push(`/cart/${match.params.id}?qty=${qty}`) } when I call this <h3>{product.name}</h3> I get the name from product queryset. I want the same process for my related queryset. Suppose if I call {related.name} then it should show me the name of the related product. In the backend if … -
Why does print show SRID 3847 in Geodjango?
I'm developing an app using Geodjango and PostGIS. In the admin area of my site, all polygons are displayed correctly with the (default) SRID of 4326 e.g. SRID=4326;POLYGON ((0.6564331054687499 52.13854550670472, 0.6289672851562499 52.08456959594681, 0.7553100585937497 52.08456959594681, 0.6564331054687499 52.13854550670472)) Why, when I print to the web server/console does the SRID show in 3857? The above admin area polygon is printed as: SRID=3857;POLYGON ((73073.79904062848 6825215.129639958, 70016.31790922143 6815431.190019455, 84080.73111369385 6815431.190019455, 73073.79904062848 6825215.129639958)) I don't know whether I can continue manipulating polygons as I can't, at present, be sure of their projection.