Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How do I create Django forms from scratch and validate the data being sent through so that I can style my forms exactly how I want them to be styled?
I really hate how the forms look in Django, its my biggest turn-off at the moment. I really want to enjoy using it because I'm new to web development and programming in general. What is the most effective systematic way to write my own HTML form, write the code to validate the data being sent through and match it with a model in my database. After the data is validated, it will be received by the server without having blank data being sent in. ALSO! I wrote my own version of this that couldn't validate the data being sent through and I was going to just roll with it (bad ik just testing stuff though) and when I tried to have multiple forms within the same view, I ran into a lot of errors. I'm not sure if that's possible with Django so any advice on that too would help a lot. -
IntegrityError Django ORM
I am processing a file that contains consultation and medical data. I am also processing another file that contains only exam data. As a good practice, I normalized the models leaving as follows: class Medico(models.Model): codigo_medico = models.IntegerField(primary_key=True, unique=True) nome = models.CharField(max_length=50) class Consulta(models.Model): numero_guia = models.IntegerField(primary_key=True) data_consulta = models.DateField() valor_consulta = models.FloatField() codigo_medico = models.ForeignKey(Medico, on_delete=models.CASCADE) class META: ordering = ['data_consulta'] class Exame(models.Model): exame = models.CharField(max_length=30, null=False) valor_exame = models.FloatField() numero_guia_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) class META: ordering = ['-valor_exame'] Note that the medical model has the ID field marked unique = true, because, regardless of the consultation, there can only be one doctor with a certain code. I did the file processing and it worked perfectly. When trying to run the same file, knowing that the doctor's data is unique, I get IntegrationError (return Database.Cursor.execute (self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: relatorio_medico.codigo_medico) This was expected. I did this processing precisely to get the repeated data. The question is, if a particular consultation file arrives, I will always have a doctor who is already registered at my base, so I need to deal with IntegratedError cases. I tried to use try and except but to no avail. How I … -
Best way to squash migrations django
I had 10 migrations and I wanted to keep them in one file . So I squash them using ./manage.py squashmigrations accounts . Now I had 11 files including init and squash file. so I deleted 9 other files and kept init and squash and run migration and migrate . Now want to ask Is this proper way ? and I have another app with same scenario should I do same to that ? -
500 error on deployed django app with debug set to False
I know this has been asked before but ive done everything recommended in other posts but i am still encountering the issue. I've added necessary allowed hosts set up postgres so that I don't use sqlite in production whitenoise set up and there's no issue with my static files previously when I ran heroku logs --tail it showed variable errors since i was using sqlite but i resolved that by setting up postgres and running migrate so all seems fine now so I'm stuck output from log 2020-09-27T17:17:09.000000+00:00 app[api]: Build succeeded 2020-09-27T17:17:18.450683+00:00 app[web.1]: 10.16.178.50 - - [27/Sep/2020:17:17:18 +0000] "GET / HTTP/1.1" 500 145 "http://zersh.shop/users/seller_reg/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0" 2020-09-27T17:17:18.451441+00:00 heroku[router]: at=info method=GET path="/" host=zersh.shop request_id=c7568fc0-74d7-466b-b309-e9dacb26842f fwd="154.231.163.135" dyno=web.1 connect=0ms service=833ms status=500 bytes=577 protocol=http urls project level from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import handler404 urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('user.urls')), path('users/', include('django.contrib.auth.urls')), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), path('store/', include('store.urls')), #path("djangorave/", include("djangorave.urls", namespace="djangorave")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #error handlers handler404 = 'store.views.error_404' #handler500 = 'store.views.my_custom_error_view' settings import dj_database_url import dotenv import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) … -
how to fetch the data of each excel row into html templates?
I need to uplaod an excel file in Django. Then i want to fetch certain values from each row of excel and paste it in html template. This process needs to be repeated till whole of the excel rows finish. -
Post Method not working in class based view in Django
I am making a simple sign in and sign up module in Django. I am using a class Based View inside which I have a function to get the data from the HTML form and save it in the database. But its not getting pass the request.method=='Post' condition as I am printing "In Post" its not displaying in the terminal. View.py class MainView(TemplateView): template_name='main.html' def post(self,request): if request.method=='post': print("In Post") email=request.POST.get('user_email') username=request.POST.get('user_name') password=request.POST.get('user_pass') hashed_password=make_password(password) print(hashed_password,email,username) UserModel.objects.create(email=email,username=username,password=hashed_password) else: return render(request,'main.html') main.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <link rel="stylesheet" href="{% static 'login.css' %}"> <script src="{% static 'login.js' %}"></script> <title>Main</title> </head> <body> <div class="form-wrap"> <div class="tabs"> <h3 class="signup-tab"><a class="active" href="#signup-tab-content">Sign Up</a></h3> <h3 class="login-tab"><a href="#login-tab-content">Login</a></h3> </div><!--.tabs--> <div class="tabs-content"> <div id="signup-tab-content" class="active"> <form class="signup-form" action="" method="post"> {% csrf_token %} <input type="email" class="input" id="user_email" autocomplete="off" placeholder="Email"> <input type="text" class="input" id="user_name" autocomplete="off" placeholder="Username"> <input type="password" class="input" id=" " autocomplete="off" placeholder="Password"> <input type="submit" class="button" value="Sign Up"> </form><!--.login-form--> <div class="help-text"> <p>By signing up, you agree to our</p> <p><a href="#">Terms of service</a></p> </div><!--.help-text--> </div><!--.signup-tab-content--> <div id="login-tab-content"> <form class="login-form" action="" method="post"> {% csrf_token %} <input type="text" class="input" id="user_login" autocomplete="off" placeholder="Email or Username"> <input type="password" class="input" id="user_pass" autocomplete="off" placeholder="Password"> … -
Django - ManyToMany where I could select the same foreign model multiple times
Apologies if this has been answered, I'm uncertain how to word it so couldn't find an existing solution. Let's say I have a basic ManyToMany relationship as shown here: class Topping(models.Model): name = models.Charfield() class Pizza(models.Model): toppings = models.ManyToMany(Topping) That's simple and great, however in the project I'm working on, I want to be able to select the same Topping more than once. For example, ["pepperoni", "mushroom", "onion"] would be a perfectly good result, but I need to allow something like ["pepperoni", "pepperoni", "pepperoni"] I've tried using a intermediate class, where Pizza has a ManyToMany to Topping, which is just a foreignkey to ToppingType, which is the Charfield - class ToppingType(models.Model): name = models.Charfield() class Topping(models.Model): type = models.ForeignKey(ToppingType) class Pizza(models.Model): toppings = models.ManyToMany(Topping) and that works, however it means if one day I create something with five "pepperoni" selections, I then permanently have five copies of pepperoni as a Topping in my database. As I mentioned at the top, I'm sure there's a fairly clean solution, but I've had trouble figuring out how to phrase my searches. -
'QuerySet' object has no attribute model_to_dict
I'm trying to convert a Django Model into a dictionary, however, I'm currently having the following issues: models.py from django.forms import model_to_dict class Stuff(models.Model): name= models.CharField(max_length=250, null=True, blank=False, unique=True) def __str__(self): return self.name def toJSON(self): item = model_to_dict(self) return item class Meta: verbose_name = 'Stuff' verbose_name_plural = 'Stuff' This is how I run my query from apps.stuff.models import * s = Stuff.objects.all() Which results in the following Queryset s <QuerySet [<Stuff: abcd>]> However, when I run my .toJSON() method this is what I get s.toJSON() Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'toJSON' Any ideas of how to correct this issue? -
{FieldError}Unsupported lookup 'time' for TimeField or join on the field not permitted
I am trying to do a query using Django but it does not work. Here is my query : Mytable.objects.filter(hour__time__range=(begin.time(), end.time())) And I got this error : {FieldError}Unsupported lookup 'time' for TimeField or join on the field not permitted. where begin = 2020-11-20 08:00:00 and end = 2020-11-20 10:00:00 I precise hour = models.TimeField(default=None, blank=True) Could you help me please ? Thank you !