Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install incompatible packages with pip version v20.3?
Since PIP has released v20.3, I am not able to install my requirements without upgrading my Django version to match versions of other packages. This was just a warning up until this version but now the installation itself is blocked. Since upgrading Django and other packages for the entire project may take a weak, am looking for a temporary solution that will allow to me to continue installation with the current Django version. I have tried installing with an older version of PIP but that is also failing now. I tried downgrading the packages which was throwing an incompatible higher version but the installation is stuck while pip is searching for suitable versions to be installed. -
Add a button to update a field in django
I want to add a button to my html which can update automaticaly the status of client from 'active' to 'hide'. it will be an additional option for the user to choose to hide or to delete the object. Model : class Client(models.Model): name = models.CharField(max_length=256) status = models.CharField(max_length=25, default='active') View : def Client_List(request): clients = Client.objects.filter(status='active') context = {'clients':clients} return render(request, 'sales/client_list.html', context) class ClientDelete(DeleteView): success_url = reverse_lazy('list_clients') model = Client def get(self, *a, **kw): return self.delete(*a, **kw) html : <a class="btn" href="{% url 'delete_client' client.id %}"> <a class="btn" href="{% url 'hide_client' client.id %}"> -
Coupon does not render in html when I redeem coupon - Django
When I submit a voucher, I get redirected back to the cart expecting table data with expected discounted results showing in cart.html In coupons/models.py I have from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code which I've loaded into the admin site and created 3 records coupons/views.py file is @require_POST def coupon_apply(request): now = timezone.now() form = CouponApplyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] print(code) try: coupon = Coupon.objects.get(code__iexact=code, valid_from__lte=now, valid_to__gte=now, active=True) print(coupon.code, coupon.active) request.session['coupon_id'] = coupon.id except Coupon.DoesNotExist: request.session['coupon_id'] = None return redirect('cart/') project/urls.py is url(r'^coupons/', include(('coupons.urls', 'coupons'), namespace='coupons')), app/urls.py is path('coupons/apply/cart/', views.cart, name='cart'), and coupons/urls.py is url(r'^apply/$', views.coupon_apply, name='apply'), coupons/forms.py file is class CouponApplyForm(forms.Form): code = forms.CharField() which I render in app/views.py file def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] coupon_apply_form = CouponApplyForm() context = {'items': items, 'order': order, 'cartItems': cartItems, 'coupon_apply_form': coupon_apply_form} print(coupon_apply_form) return render(request, 'IT6041App/cart.html', context) when I click on Apply, my page redirects back to the path('coupons/apply/cart/', views.cart, name='cart'), but my new lines do not appear. cart.html file is <table class="table"> … -
annotate() + distinct(fields) is not implemented
My code In Django queryset=SurveyResponseDetails.objects.values_list('Survey_Question_Answer','Survey_Question_Desc').filter( Survey_Id='1H2711202014572740').annotate(Survey_Question_Answer_count=Count('Survey_Question_Answer')).order_by('Survey_Question_No').distinct('Survey_Question_No') -
Django | PostgreSQL | ManyToManyField vs ForeignKey performance
I am going to a Vehicle table, which has two damage types - primary and secondary (optional). Not more, only these two. And I am wondering because I expect, that the Vehicle table will have really a lot of records in near future, about 1M+ and I am not sure if I should use ManyToMany field or two ForeignKeys with disabled related_name class Damage(models.Model): name = models.CharField(max_length=32, unique=True) Should I use this solution: class Vehicle(models.Model): damage_primary = models.ForeignKey(Damage, on_delete=models.CASCADE, related_name='+') damage_secondary = models.ForeignKey(Damage, on_delete=models.CASCADE, blank=True, related_name='+') OR this one: class Vehicle(models.Model): damage = models.ManyToManyField(Damage, on_delete=models.CASCADE) What is the best practice, please? Because internal table, which Django will create when I will use ManyToManyField will have really a lot of records, if, in Vehicles table, there will be 1 000 000 and more records, in future. Thank you very much for any advice! -
Text searching in Django with trigram
I want to speed up search results in my application, however, I keep getting the same results no matter what method I use. Since it's Django application I'll provide both ORM commands and generated SQL code (PostgreSQL is used). First, I have enabled GIN indexing and trigram operations on the database: Second, I have create table that contains 2 varchar columns: first_name and last_name (plus an id field as primary key). from django.db import models class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) I have also filled the database with 952 example records so that I don't have a situation, where Postgres avoids using index because of too small data set. Next, I run following queries on non-indexed data. Simple LIKE query: In [50]: print(Author.objects.filter(last_name__icontains='ari').query) SELECT "reviews_author"."id", "reviews_author"."first_name", "reviews_author"."last_name" FROM "reviews_author" WHERE UPPER("reviews_author"."last_name"::text) LIKE UPPER(%ari%) In [51]: print(Author.objects.filter(last_name__icontains='ari').explain(analyze=T ...: rue)) Seq Scan on reviews_author (cost=0.00..24.28 rows=38 width=16) (actual time=0.011..0.242 rows=56 loops=1) Filter: (upper((last_name)::text) ~~ '%ARI%'::text) Rows Removed by Filter: 896 Planning Time: 0.042 ms Execution Time: 0.249 ms Trigram similar: In [55]: print(Author.objects.filter(last_name__trigram_similar='ari').query) SELECT "reviews_author"."id", "reviews_author"."first_name", "reviews_author"."last_name" FROM "reviews_author" WHERE "reviews_author"."last_name" % ari In [56]: print(Author.objects.filter(last_name__trigram_similar='ari').explain(ana ...: lyze=True)) Seq Scan on reviews_author (cost=0.00..21.90 rows=1 width=16) (actual time=0.582..0.582 rows=0 loops=1) Filter: … -
django datatables manytomany field serverside processing
In my Django project, I am using the datatables.net jquery plugin to display some of the data from my Django models in a table. I am using this to do the serverside processing. Everything works well, but I have to display some data from another table that is linked to the first table using Django's manytomany field. Currently it shows 'appname.Location.None' in every row of the datatable. models class Location(models.Model): location = models.CharField(max_length=200000, blank=True, null=True) lat = models.FloatField(blank=True, null=True) long = models.FloatField(blank=True, null=True) def __str__(self): return self.location class Event(models.Model): name = models.CharField(max_length=200, blank=True, null=True) is_active = models.BooleanField(default=True) status = models.CharField(max_length=100, blank=True, null=True) types = models.CharField(max_length=500000, blank=True, null=True) impact = models.CharField(max_length=500000, blank=True, null=True) loc = models.ManyToManyField(to=Location, related_name='loc', blank=True) def __str__(self): return self.name views class events(BaseDatatableView): columns = ['name', 'status', 'impact', 'types', 'id', 'loc'] order_columns = ['name', 'status', 'impact', 'types', 'id', 'loc'] def get_initial_queryset(self): return Event.objects.filter(is_active=True) script $(document).ready(function () { $('#tableid').DataTable({ "processing": true, "serverSide": true, "ajax": "{% url 'evnts' %}", //goes to class evnts columns: [ { data: 'name', }, { data: 'status', }, { data: 'impact', }, { data: 'types', }, { data: 'id', }, { data: 'loc' } ] }); }); What am doing wrong? -
How to pass variables from __init__ to Meta class in Django
I am trying to create a dynamic form from columns in a database. The columns are different for every table but I must be able to add a table and then Django needs to be able to create a form to insert new values without having to modify the code. views.py def add_entry(request, partname): partname = partname.replace('_', ' ').title().replace(' ', '') form = AddPartForm(request.POST, model=partname) context = {'form': form} return render(request, 'index.html', context) Passing the model from views.py to forms.py works like class AddPartForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') super(AddPartForm, self).__init__(*args, **kwargs) The problem is that I get the following error: ValueError: ModelForm has no model class specified. I can't seem to get that model variable to the Meta class. Is there a way to do this or should I approach it in a different way? -
Use exisiting URL as login
Hi I am a Django newbie and need some help with the following. Everytime someone needs to login to my app, I want them to be directed to an existing authentication URL: https://example.com I have setup the following urls.py: from django.contrib import admin from django.urls import path from .views import * from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), path(r'', auth_views.LoginView.as_view(template_name="login.html"), name="login"), ] I have a login.html template" {% load static %} <html> <body> <head> <link rel="stylesheet" href="{% static 'css/login.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <nav> <div class="nav-wrapper"> <a>Quality Dashboard IDM</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> </ul> </div> </nav> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </body> </html> Instead of using this template I want to do something like urlpatterns = [ url(r'^admin/', admin.site.urls), path(r'', url=https://example.com), ] How do I basically paste that URL into my app, so every time I type in the IP-address, it takes me to https://example.com ? -
django nested serializer and ViewSet
I have a problem with nested serializer and ViewSet My models are like this and their relationships are quite clear This classse have Nested relationships with each other class Sim(models.Model): name = models.CharField(max_length=255) subject = models.ManyToManyField(Subject) grade = models.ManyToManyField(Grade) class Exercise(models.Model): name = models.CharField(max_length=255) sim = models.OneToOneField(Sim,related_name='sims', on_delete=models.CASCADE) class Result(models.Model): is_example = models.BooleanField(null=False) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, blank=True, null=True, default=None) class Parameter(models.Model): name = models.CharField(max_length=255) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, blank=True, null=True, default=None) class ExerciseData(models.Model): value = models.CharField(max_length=255) parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, blank=True, null=True, default=None) result = models.ForeignKey(Result, on_delete=models.CASCADE, blank=True, null=True, default=None) I want to build a ExerciseSerializer like this class ExerciseSerializer(serializers.ModelSerializer): parameters = ParameterSerializer(many=True, read_only=True) exercisedatas = ExerciseDataSerializer(many=True, read_only=True) sims = SimSerializer(many=True, read_only=True) class Meta: model = models.Exercise fields = ['name', 'id', 'parameters', 'exercisedatas','sims'] extra_kwargs = { 'id': {'read_only': True}, } class SimSerializer(serializers.ModelSerializer): grade = GradeSerializer(many=True, read_only=True) subject = SubjectSerializer(many=True, read_only=True) class Meta: model = models.Sim fields = ['name', 'subject', 'grade', 'id'] extra_kwargs = { 'id': {'read_only': True}, } class ParameterSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = ['name', 'id'] extra_kwargs = { 'id': {'read_only': True}, } class ResultSerializer(serializers.ModelSerializer): class Meta: model = Result fields = ['is_example', 'id'] extra_kwargs = { 'id': {'read_only': True}, } class ExerciseDataSerializer(serializers.ModelSerializer): parameter_set = ParameterSerializer(many=True, … -
admin panel django not showing chart
I implemented the chart in the admin panel and I want to show the number of sales of each product in this chart. I display the number of sales on the y axis and the product name on the x axis. The problem I have is that the number of sales for the same product is not displayed (for example, the guitar maker has sold three but shows two, or jazz has sold 5 but has shown 3 so far). The number of sales does not match the name of that product. The photo is the attached diagram. [![admin panel photo][1]][1] [1]: https://i.stack.imgur.com/BpJUJ.jpg my template : {% extends "admin/change_list.html" %} {% load static %} {% block extrahead %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script> <script> var options = { responsive: true, maintainAspectRatio: true, legend: { position: 'left' }, title: { display: true }, animation: { animateScale: true, animateRotate: true } }; window.onload = function () { var ctx = document.getElementById("gender-chart"); {% regroup cl.queryset|dictsort:"sell" by sell as sell_list %} {% regroup cl.queryset|dictsort:"name" by name as name_list %} var lineChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for category in name_list %}'{{ category.grouper }}',{% endfor %}], datasets: [{ label: '# … -
Django set two fields with unique values in a model
Here is my problem, I want to create an school administration site so I need to register the student data. The students have two fields that need to be unique, for example:## Student A: 'enrollment_id: 123', 'other_field: ABC' Student B: 'enrollment_id: 234', 'other_field: CDE' ## Those two fields can't have the same values. If I already have an student with ABC in the 'other_field' and I want to register an student with the same value, the app shouldn't allow that. I'm using Django 3.1.1 and so far I have already tried UniqueTogether and UniqueConstraint(fields = ['enrollment_id', 'other_field'], name='some_name') in my Student Model and as PK I have the enrollment_id. But that doesn't work. I can still register the same value in "other_field" if "enrollment_id" is different. I need to mention that I'm using SQLITE to test the app before migrating the DB to another Engine. Also I'm using CBV to create the forms. Thank you very much, any help is appreciated! EDIT: Yes, I've already made the migrations -
Example of clean architecture with Python
I'm trying to create a web application based in Python. Now I'm at the point of defining the architecture, and I've found a lot of literature about Clean Architectures, Onion Architecture, Hexagonal Architecture... But it would be really helpful a good example of a real web project that follows these kind of designs. Do any of you know about a good public example in order to see a real implementation? Thanks in advance. -
What is the point of specifying Integer Choices in django models?
The official django docs give the following example for specifying integer choices for a column: class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) However, I find that if I open 'python manage.py shell' and simply do something like: c = Card() c.suit = 5 c.save() it saves the card with no problems, even though 5 isn't included in my choices. so what is the point of specifying my integer choices? -
PyCharm Pro dont let me start Django project, yesterday everything was fine
I am trying to start a Django project, but pycharm wont let me do it. Yesterday everything was fine. I have already reinstalled pip3 and python3. What should i do? Here are the screenshots: image 1 image 2 image 3 image 4 The following command was executed: pip install Django The exit code: 2 The error output of the command: Usage: /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] <requirement specifier> [package-index-options] ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] -r <requirements file> [package-index-options] ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] [-e] <vcs project url> ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] [-e] <local project path> ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] <archive url/path> ... no such option: --build-dir Non-zero exit code (2) -
Obtaining to fetch data from the form using GET Method
I want to fetch a list of data using ajax function which is called in views.py for the ajax function using GET Method in views.py. But my submit button is not functioning nor it is fetching any data and displaying the result. Any help will be appreciated. My codes are: views.py def home(request): majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk") if request.is_ajax() and request.method == 'POST': form = request.GET.get('major1') form = request.GET.get('major2') form = request.GET.get('major3') form = request.GET.get('major4') form = request.GET.get('major5') line_chart = pygal.Line(width=1500) line_chart.title = 'Budget Estimation' context = { "chart": line_chart.render_data_uri(), 'majors': majors } return render(request, "website/index.html" , context ) -
Return two field values from one SerializerMethodField
I have following serializer: class SampleSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() label = serializers.SerializerMethodField() field3 = serializers.SerializerMethodField() field4 = serializers.SerializerMethodField() field5 = serializers.SerializerMethodField() class Meta: model = Sample fields = ( 'status', 'label', 'field3', 'field4, 'field5' ) The problem is, the conditions used to obtain the first two fields are same. So I don't want to run the same codes again in two serializer method fields. I want to get both of the values from the same serializer method. How can I efficeintly get values of both of the fields from only one serializer method field? -
save multiple check box values insert update and delete in django
save multiple check box values insert update and delete in Django I am trying to update the multiple check box values in django -
RawPostException: You cannot access body after reading from request's data stream
I am trying to get the data from ajax to django post view, I create the cart with items now I need to get the cart to backend My js code is: $.ajax({ url: url, type: "POST", data: JSON.stringify({'order_data':order}), contentType: 'application/json; charset=UTF-8', success: function (data) { if (data['success']) { alert(data['success']); } }, error: function (request, error, status) { if (request) { } } }); My View code that I am using in Django view: if request.method == "POST": data = json.loads(request.body) cart = data['order_data'] Then I am getting that error RawPostException: You cannot access body after reading from request's data stream your suggestions will be preferred -
django template variable in <a>
How can i add a django template variable to href attribute of tag?something like this <a href="{{meeting.meeting.url}}">{{meeting.meeting_url}}</a> meeting.url stores a link to another website such as google etc and it is saved in database Thanks in advance -
PayPal integration in Django web applications
I'm working on a project in which I'm using Python(3.9) & Django(3.1.2) and I need to implement the Paypal payment method in this project. Can somebody help me with the source code to integrate PayPal? -
Django ORM can't get value from specific field
My old project uses django 2.1.7, drf 3.9.2, psycopg2==2.7.7, and postgresql in AWS RDS. I found a strange thing that orm couldn't get some values from database. Actually, there were real values in my database. ORM works well in other values in other columns, but some in specific value, it weren't work. the field looks like this: - models.CharField(max_length=5000, null=True) the value in DB looks like: character varying(5000) in postgres 0_ 46 46 .... 52 53 50 43 41 54 52 / the result in my server or shell is just None. other values work well... -
Understanfding the `initial` argument of the form in Django (Form.initial)
Here are my functions in views.py. But I am interested in last, edit_entry function's behavior: class AddForm(forms.Form): title = forms.CharField(label="Enter the title", max_length=100) content = forms.CharField(widget=forms.Textarea, label="Enter your text") def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def add_entry(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] if util.get_entry(title) is None: util.save_entry(title, content) return redirect('entry', title) else: return render(request, "encyclopedia/add_entry.html", { "form": AddForm(), "title": title }) return render(request, "encyclopedia/add_entry.html", { "form": AddForm() }) def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return redirect('entry', title) return render(request, "encyclopedia/edit_entry.html", { "form": AddForm(initial={'title': title, 'content': content}), "title": title, "content": content }) Even if I delete the initial argument of my AddForm, it gives the same result, like this: "form": AddForm({'title': title, 'content': content}). It shows me the initial content, I can add some words and save it, and it works. Then why we need this initial if we can do it without it? Just in case, here is my edit_entry.html … -
Dynamically check value and display alarm popover
I want to validate user input so he only provides number from a certaint range with 0,5 step. But I want my website to do it every time user swaps to another input form, not after he sends the data to my view. Can you give a hint of how should it be done? I don't know Javascript but I know there is onfocusout DOM event. Is it correct approach to use it, check whether or not value is valid and display alarm based on that? -
How can we upload multiple files and store address of file as json using Django and Javascript
I want to know how can we upload file dynamically( meaning there will be one filefield on frontend and one add button) if user will click on add button new file field will be generated there using javascript. I want to upload file(without refreshing page) and get the address of that image(to store that in jason format). So by this way I will be able to upload multiple files. I am using Django, jquery and Javascript, Django-rest-framework.