Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stay on Same Product after Add to Cart?
I make my E-Commerce Website using Django. When I use Add to Cart functionality on the website refresh the page & I go to the top of the page. But I want the user to stay on the same Product after Add to Cart. Add To Cart function is made using Session in Django, not JS. So I want when users use Add To Cart Function user stay on the same product. I think this thing is possible using JS. This is Add to Cart button <form action="{% url 'cart:AddCart' %}" method="POST">{% csrf_token %} <input hidden type="text" name="product" value="{{i.id}}"> <button id="clickMe" class="main-btn cart cart-btn" style="padding: 5px 32px">Add <i class="fa-solid fa-cart-shopping"></i></button> </form> -
Django perform custom SQL directly
This is my first time to execute custom SQL directly, How to add dynamic string value inside the sql query? I try some of the example and docs from django sql but still not working. def insert_sql(): dn = datetime.today() - timedelta(days=1) dn = str(dn) date_input = datetime.strptime(dn[:-7],'%Y-%m-%d %H:%M:%S') date_input= date_input.strftime('%Y-%m-%d') sql = '''INSERT INTO table name( ........................ more sql here WHERE item IS NOT NULL AND disc <> '-' AND date= '{date}' ''' with connections['db_2'].cursor() as cursor: cursor.execute(sql) row = cursor.fetchone() return row The error is: django.db.utils.ProgrammingError: syntax error at or near "{" LINE 485: AND date= {date} please help me. Thnank You! -
Is there a way to render a Django formset in Jinja2 using the batch filter to create a grid?
I'm looking to render a Django formset similar to a spreadsheet with rows and columns. I was hoping to use the Jinja2 filter "batch" to create the columns but I'm not sure if that is possible. I know I can render the formset using for loops in Jinja but it's getting very messy as I've also got to add non-form information at points in the rendering and the position of that information is dynamic. Ideally, I would like to set the column loop up with "batch", then apply another set of loops to render the actual column forms and non-form data, then repeat this for each column. I appreciate any input or insights you may have. -
Python Threading blocks the django server when using thread.join
I'm looking to run a function without blocking the whole server. import threading def heavy_function(my_args): # heavy stuff here . . A solution for me would be to create a thread to allow the server to respond to user requests t = threading.Thread(target=heavy_function,args=(my_args,),daemon=True) t.start() t.join() #once thread is over do some other stuff . . . t.join() should wait for a thread to finish. Except that it blocks the whole server. Is there something equivalent that allows me not to block the server while waiting for the thread to end? Celery is not at all suitable for what I do, thank you for not proposing this solution -
how to integrate django-parler and django-polymorphic in the right way
I tried to follow the django-parler documentation to integrate django-parler with django-polymorphic, and was doing something like this class TestQueryset(TranslatableQuerySet, PolymorphicQuerySet): pass class TestManger(TranslatableManager, PolymorphicManager): queryset_class = TestQueryset class Test(PolymorphicModel): price = models.CharField(max_length=30) class TestChild(Test,TranslatableModel): default_manager = TestManger but the problem is that I want to have the translated fields in the base class Test, how can I exactly do that, because in the documentation i only found a way to add it to the subclasses -
Formatting ouput table in template from django.model
I am creating a currency exchange rate aggregator app. I have got next models. class Bank(models.Model): bank_name = models.CharField( max_length=30, blank=False, unique=True, ) class ExchangeRate(models.Model): USD_in = 'USD_in' USD_out = 'USD_out' EUR_in = 'EUR_in' EUR_out = 'EUR_out' RUB_in = 'RUB_in' RUB_out = 'RUB_out' USD_EUR_in = 'USD_EUR_in' USD_EUR_out = 'USD_EUR_out' exchange_choise = [ (USD_in, 'USD_in'), (USD_out, 'USD_out'), (EUR_in, 'EUR_in'), (EUR_out, 'EUR_out'), (RUB_in, 'RUB_in'), (RUB_out, 'RUB_out'), (USD_EUR_in, 'USD_EUR_in'), (USD_EUR_out, 'USD_EUR_out'), ] datetime = models.DateTimeField( auto_now_add=True, blank=False, ) exchange_type = models.CharField( max_length=12, choices=exchange_choise, ) rate = models.FloatField() bank_id = models.ForeignKey( Bank, on_delete=models.CASCADE, ) quantity = models.IntegerField( default=1, ) Basically two tables. One stores bank names, another exchanging currencies and their rates. So if I will output data from model as it is I will get next picture: Notice, that each currency exchange rate takes one row (datetime, currency, rate, bank). And I want to display rates in the format in table on webpage. I wonder, how can I do this? Do I need to perform some join operation or to write code in template to format it like this. -
How to implement custom redirects?
I have an eCommerce web app. A user may browse items while being logged in. If a user is logged in and registered, but hasn't entered their shipping address information (not required for initial account creation) and tries to purchase an item by clicking on the 'purchase' button which is mapped to a checkout view in my views.py, I want to first redirect that user to a shipping address form that I have set up in a different view and template, and then after they have successfully entered their shipping address info I have a boolean field for the user called address_verified which I will then set to True, redirect them back to the purchasing page so they can proceed with the purchase. Basically, I want to implement the same functionality of Django's @ login_required(login_url='/account/login') decorator that creates this redirect url query: '?next=/redirect/to/url' -
python program question, use django as example
I think this question is about python program, it is not how to use django. I am confused about QuerySet, what is it? # print(Hotel.objects.all().values()) # output <QuerySet [{'x': 1}, {'y': 2}]> # type print(type(Hotel.objects.all().values()) #output <class 'django.db.models.query.QuerySet'> # like list print(type(Hotel.objects.all().values()[0]) #output {'x': 1} Why print(Hotel.objects.all().values()) , it is not just return [{'x': 1}, {'y': 2}]? And why it could be operate like list, but type() show it is not list? JsonResponse(Hotel.objects.all().values(), safe=False)) show TypeError: Object of type QuerySet is not JSON serializable I think it like list [], so it could be serializable. But, actually, it could not be serailizable. However, it could work like list. ex: list methods all work, also iteration. -
What kind of expectation I have to put in this error? (SSLCertVerificationError)
Sometimes I get this error and want to know which expectation I should set to try sending the query again: HTTPSConnectionPool(host='x.x.x', port=443): Max retries exceeded with url: /api/x/x/x/x (Caused by SSLError(SSLCertVerificationError("hostname 'api.exmple.com' doesn't match either of '*.azureedge.net', '*.media.microsoftstream.com', '*.origin.mediaservices.windows.net', '*.streaming.mediaservices.windows.net'"))) my code : if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,auth=(username, password),verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,verify=True) exemples: except ssl.SSLCertVerificationError except ssl.SSLError List ssl.CertificateError Thank you in advance -
_clone() got an unexpected keyword argument 'klass' Django
I've tried to overwrite get_queryset method in order to customise count method but when I'm trying to call it I'm receiving a typo: "TypeError: _clone() got an unexpected keyword argument 'klass", I ve google it a little bit but I didn't find anything relatable. admin.py: def get_queryset(self, request): qs = super(MyAdminModel, self).get_queryset(request) return qs._clone(klass=FastCountQuerySet) Any thoughts on this topic? Thx in advance! -
Django: Get latest record before certain date for all given users
So I have table the looks something like this user_id value date_created 1 10 2022-8-14 2 11 2022-8-14 3 12 2022-8-14 1 13 2022-8-15 2 14 2022-8-15 3 15 2022-8-15 1 10 2022-8-16 2 11 2022-8-16 3 12 2022-8-16 I want to find latest record before a certain date for given users. Following query filters all records for given users before a certain date. UserData.objects.filter(user_id__in=user_list, date_created__lte=start_date) How do I modify this query to get only the latest rows before the start date for each user. For example if the start date is 15 August it should give rows 4 to 6 from the table. PS: Date created is a simplification, it should be datetime and there can be multiple values on each day by same users. -
How to I change the order of my columns so it doesn't break an import with pg_restore
I'm trying to export data from a live Postgres DB into a local Postgres DB and have used pg_dump (via DataGrip) to dump the database into a tar file. I am using the INSERT option from the DataGrip dialogue which is giving the following. --dbname="XXX" --format=t --file="XXX/DataGrip Backup/{timestamp}" --inserts When I try and import the tar file using pg_restore (once again through DataGrip), one of my tables (the most important one!) won't import. The error I'm getting is: pg_restore: error: could not execute query: ERROR: invalid input syntax for type numeric: "AUD" The table has a numeric field and a varchar field. One for the discount and one for the currency being used. This is from a model (Django) using the MoneyField: coupon_discount = MoneyField( decimal_places=2, max_digits=10, null=True, default_currency="AUD", default=0.00 ) An example of the data I am importing is: Command was: INSERT INTO public.customers_customer VALUES (2557, '', NULL, 3, NULL, NULL, NULL, NULL, '2022-08-14 08:45:50.466306+00', '2022-08-14 08:45:50.466454+00', '2022-08-14 08:45:50.466459+00', 2559, '90h0nbJgDU', 0, 0.00, 'AUD', false, false, NULL, 1); pg_restore: error: could not execute query: ERROR: invalid input syntax for type numeric: "AUD" LINE 1: ...10:31:35.347403+00', 2560, 'o4VxTmqlOa', 0, 0.00, 'AUD', fal... When I look at the external Postgres DB … -
Can't customize the choice of autocomplete_field with TabularInline Django
I'm trying to limit the choice in autocomplete_field within TabularInline Django but I can't. I can do this within a ModelAdmin via get_search_results. But within TabularInline, it seems that the funtion get_search_results isn't called. Someone has any idea to do this with TabularInline? class BarInline(admin.TabularInline): model = models.Bar extra = 0 search_files = ('bar',) autocomplete_fields = ('bar',) def get_search_results(self, request, queryset, search_term): # I want to do something here to limit the choice of autocomplete_fields 'bar'. # But this function is never called within TabularInline # For exemple, I want to ... queryset = models.Bar.objects.filter(bar__name__contains="Only") ... @admin.register(models.Foo) class FooAdmin(ModelAdmin): inlines = (BarInline,) -
Update values in jsonfield for particular keys
Good morning everyone. I have JSONField in my model with following structure: { "1": { ... "is_disabled": false }, "2": { ... "is_disabled": false }, "3": { ... "is_disabled": false } } And i have set of pks like: pk_set = {1, 2} How can i update "is_disabled" key to true only for pks in pk_set? -
Use the django contains query with multiple objects
I want to use the Django contains query with multiple search objects. Currently, the way it's mentioned on the documentation is as follows: Entry.objects.get(headline__contains='Lennon') This basically returns all those headlines which contain the word 'Lennon'. Instead I want to filter it by a list of strings. Let's say my strings are names = ['McCartney', 'Lennon', 'Starr', 'Harrison'] Now, I want all those headlines which contain any of the words from the list above. Additionally, the list is dynamic so I can't exactly make hard-coded queries. So, I need a dynamic method of searching through my database using the contains keyword for multiple objects. How do I write a query for this? -
vHost config in cyberpanel
I want to host my django website on cyberpanel vps.I have done all the things and uploaded project to file manager of website on cyberpanel. here is my vHost config docRoot /home/fastrefer.online/public_html vhDomain fastrefer.online vhAliases www.fastrefer.online adminEmails jackgaming967@gmail.com enableGzip 1 enableIpGeo 1 index { useServer 0 indexFiles index.php, index.html } errorlog $VH_ROOT/logs/$VH_NAME.error_log { useServer 0 logLevel WARN rollingSize 10M } accesslog $VH_ROOT/logs/$VH_NAME.access_log { useServer 0 logFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" logHeaders 5 rollingSize 10M keepDays 10 compressArchive 1 } scripthandler { add lsapi:fastr9279 php } extprocessor fastr9279 { type lsapi address UDS://tmp/lshttpd/fastr9279.sock maxConns 10 env LSAPI_CHILDREN=10 initTimeout 600 retryTimeout 0 persistConn 1 pcKeepAliveTimeout 1 respBuffer 0 autoStart 1 path /usr/local/lsws/lsphp81/bin/lsphp extUser fastr9279 extGroup fastr9279 memSoftLimit 2047M memHardLimit 2047M procSoftLimit 400 procHardLimit 500 } phpIniOverride { } module cache { storagePath /usr/local/lsws/cachedata/$VH_NAME } rewrite { enable 1 autoLoadHtaccess 1 } context / { type appserver location /home/fastrefer.online/public_html/refer_and_earn binPath /usr/local/lsws/fcgi-bin/lswsgi appType wsgi startupFile refer_and_earn/wsgi.py envType 1 env LS_PYTHONBIN=/home/fastrefer.online/public_html/bin/pyhton env PYTHONHOME=/home/fastrefer.online/public_html/ } context /.well-known/acme-challenge { location /usr/local/lsws/Example/html/.well-known/acme-challenge allowBrowse 1 rewrite { } addDefaultCharset off phpIniOverride { } } vhssl { keyFile /etc/letsencrypt/live/fastrefer.online/privkey.pem certFile /etc/letsencrypt/live/fastrefer.online/fullchain.pem certChain 1 sslProtocol 24 enableECDHE 1 renegProtection 1 sslSessionCache 1 enableSpdy 15 enableStapling 1 … -
Not Found: /topics [16/Aug/2022 13:32:34] "GET /topics HTTP/1.1" 404 2202
Page not found (404) Request Method: GET Request URL: http://localhost:8000/topics Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ The current path, topics, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
How to check and get the data in database using django template and api, if its not there then post new data.(rest_framework)
I have the code for django api to display the exist data in postman. But I need is at First I need to verify the email_id is exist if it exist I want to display the data, if it not there I need to create the data using that email_id. I am using form.py, from socket import fromshare from newappapi.models import example from django import forms from rest_framework import status from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from newappapi.serializers import exampleSerializer class VenueForm(forms.ModelForm): class Meta: model = example fields = ['email_id'] def save(request,self, commit=True): email_id = forms.EmailField(max_length = 200) venue = super(VenueForm, self).save(commit=False) email_id = self.cleaned_data['email_id'] if request.method == 'GET': email_id = request.GET.get('email_id', None) values = example.objects.filter(email_id=email_id) if values.exists(): tutorials_serializer = exampleSerializer(values, many=True) return JsonResponse(tutorials_serializer.data, safe=False) return JsonResponse({'message': 'The email_id does not exist'}, status=status.HTTP_404_NOT_FOUND) if commit: venue.save() return venue I am using the template, {% block content %} <center> <h1>Email Verification</h1> <br/><br/> <form action="" method="POST , GET"> {% csrf_token %} {{form}} <label>Email-id</label> <input type="text" id="id" class="form-control"/><br/><br/> <input type="submit" value="Verify" class="btn btn primary"> <input type="submit" value="Post" class="btn btn primary"> </form> </center> {% endblock %} And i have Two buttons(verify, Post), if we click verify it want to show the data … -
How to add input values to database using click button in django
I have a code for display the values as a datatables from mongodb, Now how to add new data to database and also it show to us using submit. Actually I want query for submit button it can store new datas to database <form action="submit" method="POST"> {% csrf_token %} <div class="mb-3"> <label>Id</label> <input type="text" id="id" class="form-control"/> </div> <div class="mb-3"> <label>Code</label> <input type="text" id="code" class="form-control"/> </div> <div class="mb-3"> <label>Created</label> <input type="number" id="created" class="form-control"/> </div> <div class="mb-3"> <label>Email_id</label> <input type="email" id="email_id" class="form-control"/> </div> <div class="mb-3"> <label>modified</label> <input type="number" id="modified" class="form-control"/> </div> <div class="mb-3"> <label>Name</label> <input type="text" id="name" class="form-control"/> </div> <div class="mb-3"> <label>Picture_Url</label> <input type="url" id="picture_url" class="form-control"/> </div> <div class="mb-3"> <label>Rank</label> <input type="number" id="ranking" class="form-control"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-sm pull-right" id="submit">Submit</button> </div> </form> I am using nosql database(MongoDB) in Django framework -
why my submit input isn´t working in django?
I have a form so an user can ask for a loan and it will tell them if it´s approved or not. The problem is not the logic, it´s the submit input that doesn't work. It will not save the form in the database or show me the errors because of the submit input. Maybe is something wrong with the succes_url? I don't know, but here's my code: views.py: #don't worry about the logic part of the form, it's just to show how it´s supposed to work class LoanRequest(LoginRequiredMixin, generic.CreateView): form_class = LoanForm success_url = reverse_lazy('Prestamos') template_name = 'Prestamos/template/Prestamos/prestamos.html' def form_valid(self, form): user = self.request.user cliente = Cliente.objects.get(user_id = user.id) if not cliente.approve_loan(form.cleaned_data.get('loan_total')): form.add_error(field=None, error='loan not approved') return self.form_invalid(form) else: form.instance.customer_id = cliente super(LoanRequest, self).form_valid(form) return render(self.request, 'Prestamos/template/Prestamos/prestamos.html', context={'form': form, 'success_msg': 'loan approved!'}) urls.py: urlpatterns = [ path('prestamos/', views.LoanRequest.as_view(), name = 'prestamos'), ] forms.py: class LoanForm(forms.ModelForm): class Meta: model = Prestamo #loan in English fields = ['loan_type', 'loan_total', 'loan_date'] and the template: <div class="container"> {%if success_msg%} <p class="alert alert-success">{{success_msg}}</p> {%endif%} <form action="" method="POST"> {%csrf_token%} {%for field in form%} <div class="form-group"> <label for="{{field.label}}">{{field.label}}</label> {{field}} </div> {%for error in field.errors%} <p>{{error}}</p> {%endfor%} {%endfor%} <input type="submit" value="request"></input> </form> </div> -
Django Rest Framework: Create Related Object or Find by ID
Problem We are developing an API using DRF to create a Membership record that includes a related Entity record w/ all the personal information and a related Address record w/ all the address information. On this API we want to include behavior in way that allows the API to receive an Entity ID to reuse an existing entity or all the other attributes of the entity to create a new one. The same goes for the address. When we post all the required information, with the goal of creating the related Entity and Address, everything works fine, but when we just post the IDs we are facing a problem. The issue we are facing is that if we send the ID w/o all the other related fields we are getting validator errors and we cannot proceed with the get of the related objects and create main record. What we have tried What we have done so far is: Created the Serializers for Membership, Entity and Address. Configured the Serializer for Membership to have the related Entity and Address serializers. Overwritten the .create method on the Membership serializer to create the nested objects. The closest problem / answer we could find … -
'str' object is not callable in django models
I am using using pre-save signal in jdangp. When I change the title for resource model then I got the error below. 'str' object is not callable model.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) pre-save signal function is def tag_set(sender, instance, **kwargs): instance.title('change title') pre_save.connect(tag_set, sender=resource) When I change title in pre-save I got error. -
In django admin panel, how can I autocomplete input?
In django admin panel, I want to add event listner so that while writing in field 1 same content must be filled in field 2 and if user want to change the field 2 he can change the input of field 2. -
How do I configure aws:elasticbeanstalk:container:python:staticfiles in Elastic Beanstalk?
I'm trying to run eb create to deploy my Django project to AWS. The error I'm getting is ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python:staticfiles', OptionName: '/static/'): Unknown configuration setting. I'm unsure what this error means and there's not much I can find on it. I've tried to define this variable in .ebextensions/django.config. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:elasticbeanstalk:container:python:staticfiles: /static/: 'frontend/views/build/static/' My settings.py is configured with the following vars: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/views/build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') I'm trying to run this ebs instance on Amazon Linux 2 -
How to upload an image to django backend using react and fetch
I am trying to make a PUT request to my django backend to update an image. But whenever I make the request, it returns the image that is already in the database. It does not update with the new image i uploaded. views.py @api_view(['PUT']) def UserPageCreateView(request, pk): if request.method == "PUT": page = UserPage.objects.get(id=pk) serializer = UserPageSerializer(instance=page, data=request.data, many=False, partial="True") if serializer.is_valid(): serializer.save() return Response(serializer.data) models.py class UserPage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField() title = models.CharField(max_length=100, default="") description = models.TextField(max_length=100, default="") profile_photo = models.ImageField(upload_to="images", default="media/images/apple_atgqt1") def save(self, *args, **kwargs): self.slug = self.user.username super().save(*args, **kwargs) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("page_detail", kwargs={"slug": self.slug}) React FETCH REQUEST const PageUpdate = async (e) => { const response = await fetch(`http://127.0.0.1:8000/page-create/${id}`,{ method: "PUT", credentials: "include", headers: { "Content-Type": "multipart/form-data" }, body:JSON.stringify({ "profile_photo": profile_photo, }) }) let data = await response.json() console.log(data) } Modal for choosing a new image to upload <Modal.Body> <Form> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Email address</Form.Label> <Form.Control type="file" value={profile_photo} onChange={(e) => setProfilePhoto(e.target.value)} /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1" > </Form.Group> <Button variant="secondary" onClick={handleClose}> Cancel </Button> </Form> </Modal.Body> Browser [form and console image][1] From the above image, you can see the the image i uploaded is not the image that is …