Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms, attrs cols and rows for textarea doesn't work, why?
I'm working on a project with Django and a textarea. The textarea by default renders cols="40" and rows="10", which is not great for my page. I'm trying to use Django's widgets to change those attributes to 20 and 5 respectively. This is my code: class NewContent(forms.Form): content = forms.CharField(widget=forms.Textarea(attrs={"cols":20, "rows":5})) Unfortunately, the code does not change the looks of the form at all when the page gets rendered. Meaning, it displays cols 40 and rows 10. But wait, things get really bizarre... when checking on the developer tools, on Google, I can see that the HTML code has changed to what I want! crazy!! I also tried the following code that I found in a different chat: attrs={"style": "height:60px; width:500px"} Which "changes" the size of the box but... for different reasons I'm not in love with this solution. Does anybody have an idea of what is happening here? I have a windows 10 and use VEC. Cheers! -
django form in bootstra modal not working
I am trying to show a django form inside a bootstrap modal, it kind of works, Everything except the form shows up when i try to launch the modal. folder_form.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <<div class="modal fade" id="modal-1"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <main class="p-5"> <div class="row"> <div class="col-sm-6 offset-sm-3"> <h1 class="myhead2">Create Folder</h1> <hr> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{form | crispy}} <input class="btn btn-dark my-3" value="Create Folder" type="submit" /> </form> </div> </div> </main> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> {% endblock %} home.html <a data-toggle="modal" href="#modal-1">Edit Contact</a> {% include "ahmed_drive/folder/create" %} <script type="text/javascript"> $(document).ready(function(){ $('#modal').on('submit', function(event){ event.preventDefault(); $.ajax({ url: '/ahmed_drive/folder_form.html', type: 'POST', // headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: $('#modal').serialize(), beforeSend: function () { $("#modal-1").modal("show"); }, success: function(data) { $('#modal-1 .modal-body').html(data); } }); }); }); </script> I don't know ajax so i copied it from somewhere and modified it. please tell me whats wrong. -
how to correctly link user model to a custom user model
i have this custom user model class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name and i use allauth package for authentication and once i sign up a new user i got this error in the main page of the website: RelatedObjectDoesNotExist at / User has no customer. is there a way to link the user to a customer automatically once the user got created? -
Properly get querry using javascript on Django
I'm developing a website and one of my priorities is a dynamic search table with autocomplete etc. I found this possible using ajax and javascript. I already mplemented a trigger everytime the user types in the search field. The problem is actually getting data from the database, right now i'm getting a 404 error, no data is being returned CODE: views.py if request.method == "POST": search_str=json.loads(request.body).get('searchText') bib = Bibrest51.objects.all().filter( autor__starts_with=search_str) | Bibrest51.objects.all().filter( autor__icontains=search_str) data = Bibrest51.objects.all() return jsonResponse(list(data), safe=False)``` JS: ``` const searchField = document.querySelector("#searchField"); searchField.addEventListener("keyup", (e) => { const searchValue = e.target.value; if(searchValue.trim().length > 0){ console.log("searchValue", searchValue); fetch("bibliografia-search", { body: JSON.stringify({ searchText: searchValue }), method: "POST", }) .then((res) => console.log(res)) .then((data) => { console.log("data", data); }) .catch(e => { console.log(e); }) } })``` Any help would be greatly aprecciated, i'm new on the site and i hope i di'nt do anything wrong on this post, feedback for improving my post is also aprecciated thank you! -
Django dynamic Q date filter gives mysterious results
I'm trying to query dynamically in Django with Q objects based on variables as follows: if end_date: end_time: datetime = get_end_of_time(end_date) q_objects = Q(_connector=Q.OR) query_filters = [field + '__lte' for field in fields] for _filter in query_filters: q_objects.add(Q(**{_filter: end_time}), Q.OR) things = things.filter(q_objects) q_objects looks as follows: (OR: ('created_at__lte', datetime.datetime(2020, 8, 6, 23, 59, 59, 999999, tzinfo=<DstTzInfo 'EET' EEST+3:00:00 DST>)), ('started_at__lte', datetime.datetime(2020, 8, 6, 23, 59, 59, 999999, tzinfo=<DstTzInfo 'EET' EEST+3:00:00 DST>))) However, it returns things that have created_at or started_at after the specified dates: started_at: 2020-07-22 12:45:48.160277+00:00 created_at: 2020-08-07 13:40:48.516932+00:00 It works fine if I manually query the objects as follows: things = things.filter(Q(created_at__lte=end_time) | Q(started_at__lte=end_time)) So I'm wondering, what am I doing wrong? And more importantly (so I'd learn), why is this happening? -
How do I use pagination for ViewSet with multiple models in Django Rest Framework?
I made a ViewSet to return response with combined data of two models (Items and Ads). My code is below: url.py urlpatterns = [ re_path(r'^feed/?$', FeedViewSet.as_view({'get': 'list'}), name='feed'), ] feed.py - views from rest_framework import viewsets from rest_framework.response import Response from api.models import Item, Ads from api.serializers.feed import FeedSerializer, ItemSerializer, AdSerializer from collections import namedtuple Feed = namedtuple('Feed', ('items', 'ads')) class FeedViewSet(viewsets.ViewSet): """ ViewSet for listing the Items and Ads in the Feed. """ def list(self, request): feed = Feed( items=Item.objects.all(), ads=Ads.objects.all(), ) serializer = FeedSerializer(feed) return Response(serializer.data) feed.py - serializers from rest_framework.serializers import ModelSerializer, Serializer from api.models import Item, Ads class ItemSerializer(ModelSerializer): class Meta: model = Item fields = '__all__' class AdSerializer(ModelSerializer): class Meta: model = Ads fields = '__all__' class FeedSerializer(Serializer): items = ItemSerializer(many=True) ads = AdSerializer(many=True) When I send GET request everything works fine I get response like following: { "items": [ {"title": value_1, ...}, // first item {"title": value_2, ...}, // second item //etc ], "ads": [ {"id": 1, ...}, // first ad {"id": 2, ...}, // second ad //etc ] } Now I want to add pagination to my ViewSet, how do I do it? I would appreciate if you can provide working example. -
How do I display the form in a template?
views.py from django.shortcuts import render from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form = TaskForm() context = {'tasks':tasks, How do I display the value of a Django form field in a template?'form':forms} return render(request, 'tasks/list.html', context) models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms.py from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('title','complete') I would like form fields to add new tasks for my todo beginner project. I use {{form}} on the html file but Django display <module 'django.forms' from '/home/***/.local/lib/python3.8/site-packages/django/forms/__init__.py'> instead of tasks fields How to get the form in the template ? -
Could it be possible to override the "is_active" method from my user model?
In my forms.py file: class RegistrationForm(UserCreationForm): class Meta: model = User fields = [ "first_name", "last_name", "email", "username", "password1", "password2" ] -
Raspberry Pi application with Django, Qt or something else?
I want to program a specialized solar controller using a Raspberry Pi. On the functional side I already programmed everything in Python. So inputs: temperatures, flow and flow switches and outputs: relais, datalogging are all more or less done. But the only way I have now to see what my code is doing is by print statements, that's not ideal. What is the best way to add a decent UI? Moreover I want to be able to see how the system is doing remotely. So I am in Holland and the RPi is in India. I have some experience in programming in Django, so one thought is to let the RPi run a website. Than use Django to visualize what the controller is doing. Another possibility would be to use Qt. I could program the UI with Qt and than remotely login to the RPi. Does anyone have recommendations what is the best/easiest way to get a decent UI? -
Formset Populate Mode;ChoiceField() in formset with records value
I have a formset that I've updated with a model choice field based on the values in a given table. I am hoping to have that field on populated records show that value and not an empty choice. Here is my forms.py class TPListForm(forms.Form): idtrp_rel__tpid_trp = forms.ModelChoiceField(queryset=AppTradingPartnerTrp.objects.all(), label='Trading Partner') cust_vendor_rel = forms.CharField(label='Vendor Number') sender_id_rel = forms.CharField(label='Sender ID') idtrp_rel__name_trp = forms.CharField(label='Vendor Name') category_rel = forms.CharField(label='Category') Here is my models.py class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField(max_length=50, blank=True, null=True) name_trp = models.CharField(max_length=50) description_trp = models.CharField(max_length=100, blank=True, null=True) idtrn_trp = models.ForeignKey(AppTransmissionTrn, models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True) class Meta: db_table = 'app_trading_partner_trp' def __str__(self): return self.name_trp Here is my views.py: def customer_partner(request, id): tpList = AppCustomerTpRel.objects.filter(idcst_rel=id).select_related('idcst_rel', 'idtrp_rel').values( 'idtrp_rel__id_trp', 'idtrp_rel__tpid_trp', 'idtrp_rel__name_trp', 'sender_id_rel', 'category_rel', 'cust_vendor_rel') print(tpList.idtrp_rel__id_trp) TPFormSet = formset_factory(TPListForm, can_delete=True,) formset = TPFormSet(initial=tpList, prefix='tp') for form in formset: for field in form.fields: print(field) # form.fields['idtrp_rel__tpid_trp'] = user_choices context = {'formset': formset} return render(request, 'customer_partners.html', context=context) Thanks in advance for any assistance! -
How to keep test instance IDs apart in Django?
There's a bug in the following code: def test_should_filter_foobar_by_foo_id(self) -> None: first_foo = Foo(name="a") second_foo = Foo(name="b") first_foobar = FooBar(foo=first_foo) second_foobar = FooBar(foo=second_foo) results = FooBarFilter(data={"foo": first_foobar.id} self.assertListEqual([first_foobar], results.qs.order_by("id")) The test passes for the wrong reason, because when starting from a newly initialized DB the Foo.id and FooBar.id sequences both start at 1. first_foobar.id should be first_foo.id. This is very similar to real-world tests I've written where the sequences running in lockstep has caused misleading test implementations. Is there a (cheap, simple) way to do something similar to Django's reset_sequences to jolt all the sequences out of lockstep? Whether randomly or by adding 1 million to the first sequence, 2 million to the next etc., or some other method. A few suboptimal options come to mind: Create dummy instances at the start of the test to move the sequences out of lockstep. Prohibitively expensive. Error prone because we'd have to keep track of how many instances of each model we create. Adds irrelevant complexity to the tests. Change the current values of each sequence as part of test setup. Error prone because we'd have to make sure to change all the relevant sequences as we add more models to the … -
Filtering query in django with multiple params
Is it someway to filter querysets with multiple optional parameters in Django more efficiently? For ex. I have product list and user can filter it by using multiple GET params. 6 params in this case. But if user chooses all 6 params, the function hits database 6 additional times. How to reduce it? Thanks. class ProductList(ListAPIView): permission_classes = (IsAdminUser,) serializer_class = ProblemSerializer def get_queryset(self): queryset = Product.objects.order_by('-created_at') category_id = self.request.GET.get('category_id') color = self.request.GET.get('color') size = self.request.GET.get('size') status = self.request.GET.get('status') date_from = self.request.GET.get('date_from') date_to = self.request.GET.get('date_to') if category_id: queryset = queryset.filter(category_id=category_id) if color: queryset = queryset.filter(color=color) if size: queryset = queryset.filter(size=size) if status: queryset = queryset.filter(status=sistatusze) if date_from: queryset = queryset.filter(created_at__gte=date_from) if date_to: queryset = queryset.filter(created_at__lte=date_to) return queryset -
How to redirect the customer to the success page after Payment from Stripe?
I am using Stripe to handle my payments for my own rental website. (Backend - DJANGO) Previously, I was using Stripe ChargesAPI and was manually sending out payouts to the Host of the property but I came to know that it can be automated by using Stripe PaymentIntentsAPI. I have successfully managed to onboard my customers to receive payments in their bank accounts using Stripe Express. After creating the payment intent and passing to the client I can charge their account as well as update my database for the booking. The problem I am facing here is after the payment is done, I want to redirect the customer to the success page or payment failure page which I was able to do it by passing my reservation ID and updating it as payment received which I now do by using Webhooks. How can redirect my customer to the success page showing the receipt of the booking? -
Get Count of order on every day of week
Hi I have a model like : class Order(models.Model): user=models.ForeginKey(User) startDatatime = models.DateTimeField(blank=True, null=True) I want count of order on every day of week , For example on Monday I got 5 orders , on Tuesday 0 . So it will for every week day from the date I have created this User. -
Unable to connect model to user in django
So i have a model called folder, i want to show all the folder created by current user on HomeView, but somehow it's not working, what i think is that folders are not getting connected to user who created them. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.core.validators import MinValueValidator from django.core.exceptions import PermissionDenied # The Folders Model. class Folder(models.Model): name = models.CharField(max_length = 250) parent = models.ForeignKey('self', on_delete = CASCADE, null = True, blank = True ) cr_date = models.DateTimeField(auto_now_add = True) user = models.OneToOneField(to=User, on_delete=CASCADE, null=True, blank=True) def __str__(self): return "%s" % self.name view.py class HomeView(TemplateView): template_name = "ahmed_drive/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user home_folders = Folder.objects.filter(user=user).order_by('-cr_date') home_files = Fileshare.objects.filter(uploaded_by=user).order_by('-id') context['home_folders'] = home_folders context['home_files'] = home_files return context home.html {% extends 'base.html' %} {% block content %} {% for Folder in home_folders %} <h1> {{Folder.name}} </h1> {% endfor %} {% endblock %} -
How can website developer earn money with some useful techniques? [closed]
Well I have completed my intermediate level and now I will move on some university in field of BSCS. I have skill that I can make website with Django. I have recently created a website which I will deploy within two to three day after some testing and adding some additional stuff. I haven't earn anything from that website because I made that for myself to improve my skills of Django. Since I am student I can't do full time website developing jobs. I want something which is less time consuming and give me satisfactory income so that I can afford my university expenses. I believe you guys are more experienced than me in the practical life and give me some useful information or share some techniques to manage how to make money without disturbing my studies. -
Migrating Django classic sessions to JWT
Our project will update soon from classic Django MPA to Vue.js SPA with Django REST. Is there any secure way to migrate existing sessions to JWT sessions so as not to force users Sign In again? -
Using save twice with F expression
When executing the following code. from django.db.models import F # assume that stories_filed is 0 at the start. reporter = Reporters.objects.get(name='Tintin') reporter.stories_filed = F('stories_filed') + 1 reporter.save() reporter.save() The result is that stories_filed is equal to 2. Why is that, and is there a good way of avoiding this mistake. Would wrapping it in a transaction prevent the issue? -
how to create a structured response in django?
I am newbie to django. I was following the following this tutorial All the steps are doing good (for simplicity I use one field foo). Suppose I have the following code from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() serializer = SnippetSerializer(snippet) serializer.data I get the following output {'pk': 2, 'foo: u'bar'} I want to to return a structured response like that { "response": "success:<bar>", "pk": 2 } how I can do that please? -
django-paypal How to check if payment was completed
I user django-paypal to make a working payment method, however, how can I check if the payment was actually completed after redirecting users after finish paying? Here is my process_payment function based view: def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { ... 'notify_url': 'https://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'https://{}{}/{}'.format(host, *reverse('payment_done', kwargs={'trade_id': trade.id})), 'cancel_return': 'https://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) my payment_done view (which users get redirected to after paying: # if paymenis done ????????: messages.success(request, 'Your product is in your inbox now') return redirect('trade:inbox') # else (the payment was not completed messages.error(request, 'You didnt complete the payment, if you are sure you did contact us at someemail@gmail.com and provide us with some evidence') return redirect('home') -
Why choices CharField default value also defines DateField default value
# models.py class Url(models.Model): STATUS_CHOIX = [ ('ATTENTE', 'ATTENTE'), ('VALIDE', 'VALIDE'), ('ERREUR', 'ERREUR'), ] URL = models.URLField(max_length=500) STATUS = models.CharField(max_length=10, choices=STATUS_CHOIX, default='ATTENTE',) DATE = models.DateField(auto_now_add=True) CIBLE = models.CharField(max_length=15) Here is my model, when I try to save a Url object, I got this strange behaviour, DATE field gets STATUS's default value which is 'ATTENTE' instead of having the record creation date. I have tried to swap auto_now_add=True with default=date.today() but I get the same problem. Here is a print screen of what I have in database when I run the following code: from scrapper.models import Url a = Url(URL="some_url", CIBLE="some-target") a.save() -
Django. How to get all fields in JOIN query and GROUP BY it all
I need JOIN two table, and groping by 'id' and get two aggregation func by some fields: models.py class Products(models.Model): brand = models.CharField(max_length=45, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) cluster = models.CharField(max_length=45, blank=True, null=True) target_market = models.CharField(max_length=10, blank=True, null=True) class Vardata(models.Model): month = models.DateField(blank=True, null=True) sales_units = models.IntegerField(blank=True, null=True) price = models.FloatField(blank=True, null=True) fk_products = models.ForeignKey(MntProducts, models.DO_NOTHING, db_column='fk_products', blank=True, null=True) Data: Products.objects.all() ('vendor1', 'name1', 'it', 'C') #id-12 ('vendor2', 'name2', 'it', 'B') #id-13 ('vendor3', 'name3', 'bc', 'B') #id-14 .... Vardata.objects.all() ('2020-03-01', '20', '180', '12') ('2020-04-01', '15', '182', '12') ('2020-05-01', '10', '178', '12') ('2020-03-01', '30', '120', '13') ('2020-04-01', '35', '122', '13') ('2020-05-01', '10', '118', '13') ('2020-03-01', '20', '150', '14') ('2020-04-01', '15', '155', '14') ('2020-05-01', '10', '156', '14') i need exit: exit[0] {'id': 12, 'brand': 'vendor1', 'name': 'name1', 'cluster': 'it', 'target_market': 'C', 'sum__sales_units': 540, 'avg__price': 180 } I try to get from database INNER JOIN SQL Query with all fields from both table to QureySet; and after to use 'annotate(Sum('sales_units', Avg('price')) to this QuerySet: But my query don`t take fields from parent table (Products) in query views.py qry_total_execute = Vradata.objects.select_related("fk_products").filter(fk_products__in=list_products) >>> qry_total_execute.query('SELECT `vardata`.`id`, `vardata`.`month`, `vardata`.`sales_units`, vardata`.`price_rur`, `vardata`.`fk_products`, `products`.`id`, `products`.`brand`, `products`.`name`, `products`.`cluster`, `products`.`target_market` FROM `vardata` INNER JOIN `products` ON (`vardata`.`fk_products` = `products`.`id`) WHERE … -
Modify POST data using if condition in Django Rest Framework
I'm sending data to a database using Django Rest Framework. The problem is the data send, doesn't match the data expected by the API. E.g. I send "Punten 1- 5" but the API expects "range" for this field ( ENTRY_TYPE_RANGE = 'range' in my Modal). So somewhere in my Serializer, View or Modal I need an if condition that sets "Punten 1-5" to "range" for this field before saving it to the database. Something along the lines of: if field === "Punten 1-5" then field = "range" Can someone tell me what the best approach for this should be? -
Django REST Framework: How do you get the attributes from a serialized object?
I have a POST method which is going to be used to retrieve a JSON object, which is then going to be used to retrieve the first_name, last_name, and username -- although I can't figure out how to get the fields (i.e. username) after I serialize it. What's the best way to go about that? views.py @api_view(['POST']) def createUser(request): # Making a Connection w/ MongoClient client = MongoClient('mongodb+srv://test_user:0FP33TLJVWrjl8Vy@cluster0.5sacp.mongodb.net/sample_clubs?retryWrites=true&w=majority') # Getting the Database db = client['sample_clubs'] # Getting the Collection/Table collection = db['users'] serializer = MyUserSerializer(data=request.data) # Gives bug if next 2 lines aren't here if serializer.is_valid(): serializer.save() return Response(serializer.data) serializers.py class MyUserSerializer(serializers.ModelSerializer): def get_first_name(self, obj): # obj is model instance return obj.first_name def get_last_name(self, obj): # obj is model instance return obj.last_name def get_user_name(self, obj): # obj is model instance return obj.user_name class Meta: model = MyUser fields = ['first_name', 'last_name', 'username'] # fields = '__all__' models.py class MyUser(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) username = models.CharField(max_length=200) def __str__(self): return self.username -
JQuery Smooth Scroll to EXTERNAL Anchor Links Django
I have a TWO-page Django website. I have a model that creates different elements with different names, for example: Section 1, Section 2, Section 3, etc. I put together a Navbar which adds these elements to the Navbar. When I am in index.html, I want to click on "Section 1" and scroll down with smooth scroll to Section 1, which has id #sectionone, and like that with every section. But ALSO, when I am in section.html, the template for every section, I want to click on Section 1 and go to index.html#section1 ALSO WITH SMOOTH SCROLL. How can I do this with JQuery or JS or any method? I saw multiple solutions which effectively did the smooth scroll but only on a SINGLE PAGE website, so I was wondering if it is possible with multiple pages. index.html <a href="{% url 'index' %}" id="logo"><img src="{% static 'main/img/logo.png' %}" alt=""></a> <!-- Logo --> <ul class="nav-links"> {% for PostSection in postsections %} <li><a href="{% url 'index' %}#{{ PostSection.section_heading }}">{{ PostSection.section_heading }}</a></li> {% endfor %} <li><a href="#about-me">About Me</a></li> <li><a href="#contact">Contact</a></li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> </nav> ´´´``` ``` urls.py path("<str:section_heading>/<slug:slug>/", views.postsectiondefault, name="postsectiondefault") ´´´``` Thank you!