Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tables2 add custom column for another model
I don't know if this question had been covered or not yet, I searcher all the related questions but I couldn't find a solution. What I want to do is to create a table using django-tables2 with a model let's say model A, and I want to add a custom column to this table having value from model B which is not related in any case to model A. This is what I did class TableA(tables.Table): class Meta: model = A template_name = "django_tables2/bootstrap.html" fields = ("id","username","data_from_b") Where can I put the B.objects.filter() to append it's data to a custom column. Your help would be appreciated. Thanks. -
How to redirect a form to a panel tab in views?
I created several tabs with bootstrap in my Django project. I have a form in my second tab (pills-approval-tab). What I want is when a user fills the form, it should redirect the page to the same second tab (pills-approval-tab). I have just 2 tabs. How can I do that? views.py if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() ... redirect('????') else: form = PdfRiskForm() ocr.html ... <div class="card-body"> <ul class="nav nav-pills nav-primary" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-ftables-tab" data-toggle="pill" href="#pills-ftables" role="tab" aria-controls="pills-ftables" aria-selected="true">Financial Tables</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-approval-tab" data-toggle="pill" href="#pills-approval" role="tab" aria-controls="pills-approval" aria-selected="false">Approval</a> </li> </ul> <div class="tab-content mt-2 mb-3" id="pills-tabContent"> {% include './financial_tables_tab.html' %} {% include './approval_tab.html' %} </div> approval_tab.html <div class="tab-pane fade" id="pills-approval" role="tabpanel" aria-labelledby="pills-approval-tab"> ... </div> -
POST Request creates multiple objects AJAX/Django Rest Framework
I am trying to enable a user to create a new list for a dashboard. The problem I have is that when the user creates a new list the following behaviour occurs: User creates first list: The new list appears once User creates a second list: the second list appears twice User creates a third list: the third list appears three times ETC. I'm not sure why this behaviour is occurring. Ajax Call: //create new list const createNewList = function(){ $("#newlistmodal").modal('show'); $("#save-list").click(function() { var listName = $("#newListName").val(); $.ajax({ type: 'POST', url: '/api/userlist/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'list_name' : listName }, success: function(data) { console.log(data.instance_id) var listId = data.instance_id; $("#newlistmodal").modal('hide'); $("#userLists").append( `<li class="userlist" id="${listName}" data-name="${listName}" data-pk="${listId}"> ${listName} <i id="dropdown" class="ml-4 dropdown fas fa-ellipsis-h" type="button" data-toggle="dropdown"></i> <div class="dropdown-menu dropdown-menu-left" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" id="${listName}-edit" data-name="${listName}" data-pk="${listId}">Edit List</a> <a class="dropdown-item" id="${listName}-share" data-name="${listName}" data-pk="${listId}">Share</a> <a class="dropdown-item" id="${listName}-delete" data-name="${listName}" data-pk="${listId}">Delete</a> </li> `) } }); }); } Views.py (Using DRF) class UserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer def get_queryset(self): return UserList.objects.filter(user__username=self.request.user) def create(self, request): serializer_class = UserListSerializer if self.request.method == "POST": user = self.request.user.id list_name = request.data.get('list_name') data = {'user': user, 'list_name': list_name} serializer = serializer_class(data=data) if serializer.is_valid(): instance = serializer.save() return Response({'status' : 'ok', 'user' : user, 'instance_id':instance.id}, … -
How to get over this Heroku-Redis error? SSL routines:ssl3_get_record:wrong version number
I am building a Django app using django channels and redis. Running it locally on redis works fine but when pushing it on Heroku with Heroku-Redis v6.0.12 i get the bellow error: Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number. My settings.py for the Redis part looks like this : import os ... ALLOWED_HOSTS = ['*',] ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": { "ssl_cert_reqs": None }, } } } CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": ['redis://:*****@****.amazonaws.com:27810'], }, }, } What am I doing wrong? -
Can't get model records in migration using RunPython after new field is created
Problem: I've created a new field named "new_field" in my model MyModel, created migration "01" which added this field. After that I want to change model records with respect to some old field "old_field" in new migration "02" So I've created migration "02" which changes my records using RunPython, it might look like this: . from ..models import MyModel def update_model(): for record in MyModel.objects.all(): record.new_field = record.old_field record.save() class Migration(migrations.Migration): dependencies = [('myapp', '01')] operation = [migrations.RunPython(update_model, lambda *args: None)] This migration will run fine, but after that I want to create new field "super_new_field": I'm creating migration "03" which creates new field "super_new_field" Everything will be fine. But if I'll clear database and then run migrations, migration "02" will not work since it's trying to access MyModel which does have field "super_new_field" in Django, but it's still missing in database since migration "03" was not executed yet. This means this code has to be removed (or order of migration and everything else must be changed) in order for migrations to be executed on new enviroments, which is not good Question: Is there a way to update model records inside migrations and avoid this problem? Migrations seems to be … -
Django admin User fields value in a model related list
In my django admin project i have a model like thisone: from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, ) u_name = models.CharField(max_length=200, verbose_name="Nome") u_sname = models.CharField(max_length=200, verbose_name="Cognome") ... so in my admin pge i would in list make visible also some fields related to User model like for example username, email, is_active, i do: list_filter = ('u_prov',) list_display = ('u_sname', 'u_name','user__username',) ... but i get: The value of 'list_display[3]' refers to 'user__username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'agenti.UserProfile'. How can i display fields of User model in my related model django-admin list? So many thanks in advance -
Can't pass parameter from template to Django view
Im passing three parameter from my html template to django view.py. But whenever i click on submit it show me Page not found ,. I'm still new in programming and Django. Does anyone know how can I fix this issue? The expected result is the webpage able to display all the input from the user. The result should display on the same page and not on the other pages. my template <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>Alert Policies</h2> </div> <div class="modal-body"> <p style="font-size:14px">Please select an event parameter as well as the condition type and value that apply.</p> <!-- parameter drop down --> <form action="send" method="post"> <label for="Parameter"> <b style="font-size:13px" > Event parameter to evaluate </b></label> <select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;"> <option disabled selected value>select a parameter</option> <option value="Subject">Subject</option> <option value="Text">Text</option> </select> <br><br> <label for="Condition"> <b style="font-size:13px" > Type of condition </b></label> <select name="Condition" id="Condition" style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;"> <option disabled selected value>select a condition</option> <option value="Equals">Equals</option> <option value="Contain">Contain</option> <option value="NotContain">Does not contain</option> </select> <br><br> <label for="valuetomatch"> <b style="font-size:13px" > Value to match</b></label> <input type="text" id="valuetomatch" name="valuetomatch" style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;"> <br> <br> <button class="button"><span>OK</span></button> … -
how to encrypt my website to against political review
I built a website to discuss philosophy. using the server of Aliyun Hong Kong. The frontend is vuejs. the backend is Django + MySQL. I want to encrypt the comments posted by users to prevent censorship(against political review). Q1. What legal problems will there be if users post violent comments on my website? Q2. how to embed encryption code in my website. Should I encrypt and decrypt just in the front-end, and only save the encrypted text on the database side? -
Django admin - handling permissions of many to many fields
Let's say I have 2 models as follows. As there is a many to many relation between the models, django created the required table (clientreport) and the table's permissions can be set using django admin's group permission's tab. (see screenshot) class Report(models.Model): is_visible = models.BooleanField(default=False) clients = models.ManyToManyField(Client) class Client(models.Model): name = models.CharField(max_length=32) On django admin I granted change permissions to a specific user group (e.g. group_a) on Report model. I did NOT grant any permissions on clientreport model. My desired output is, a group_a user can change is_visible field of any Report instance but could not change/delete client X reports (or clientreport). However even if there is no actual table reference between Report and Client models, a group_a user can still edit client-reports from django admin panel. (see screenshot) Is this really intended? If so, how can I get my desired goal? -
Adding extra input fields on user need and saving and fetching the values in django
I m working on a website In DJANGO where in i need to add input fields dynamically on a button click and then clicking the Submit button saves the data in Django Database How to do this and also fetch the saved data for the input fields. Example in a college a person is allowed to take as many subjects he needs. He may take 1 subject or 2 subjects or more. When he fills the form only 1 input field is shown. If he wants to add one more subject he clicks on the "Add" button and one more field is generated after this he clicks the Submit button to save the data. How to save that dynamic data created when button was clicked and then fetch it to show in template -
Django framework
I m trying to get the email of the person who just login. if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') -
Django raise IntegrityError exception befor form.save()
I have a model with a unique "code" field and a form for the same model where the "code" field is hidden. I need to set the "code" value in the view after the user has copied the form, but I get an IntegrityError exception. model class Ticket(models.Model): codice = models.CharField(unique=True, max_length = 13, default = '') form class NewTicketForm(forms.ModelForm): codice = forms.CharField(widget = forms.HiddenInput(), required=False) view if request.method == 'POST': form = NewTicketForm(request.POST) form.codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') if form.is_valid(): while True: try: codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') form.codice = codice form.save() except: break form.save() return redirect('ticket-homepage') else: form = NewTicketForm() form.codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789') context = { 'form': form } return render(request, 'ticket/new_ticket_form.html', context) I also tried to set form.code before form.is_valid () but the exception is raised anyway. technically there shouldn't be any problems because I generate the value with get_random_string and try-except allows me to do it again as long as the value is not unique. -
difference between django-allauth process='connect/login'
here in the docs there is an optional parameter process which can take either login or connect. using process='login' it works properly and creates new user if there isn't any, while process='connect' does nothing.(I was expecting it to login just if there is a user ..). but i have no idea on, how that works.. I have a loginForm and SignUpForm where both have the social login/signup option, and I don't want it to create account when it's clicked on social icon on LoginForm. how can i perform this. (sorry if messed up things..:) -
Django admin link at user model from another in list
In my django admin i have a model that link to user, i would have n my list create a link for pass to related user id editing page directly from connected models, i do: class a_cards(models.Model): CK_CHOICES = ( ('A', 'Ambassador'), ('M', 'Medico'), ('P', 'Paziente'), ('S', 'Senator'), ) c_num = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Numero card") c_data = models.DateTimeField(auto_now=True) c_type = models.CharField( max_length=1, choices=CK_CHOICES, verbose_name="Tipo utenza") c_email = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Notifica Email") c_agente = models.ForeignKey(AgenteProfile, on_delete=models.CASCADE, null=True, blank=True, related_name="ag_id", verbose_name="Agente") c_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Cliente" ) class Meta: verbose_name = 'Cards' verbose_name_plural = 'Cards' def user_link(self): if self.c_user: return '<a href="%s">%s</a>' % (reverse("admin:auth_user_change", args=(self.c_user.id,)) , escape(self.c_user)) user_link.allow_tags = True user_link.short_description = "User" def __str__(self): return self.c_num in admin: class cardAdmin(ImportExportModelAdmin): list_filter = ('c_type',) list_display = ('c_num', 'c_data', 'c_type', 'c_agente', 'user_link',) ... but when i open my admin page i see the correct link but not in libk form: where is the error? why i can't have clickable link? So many thanks in advance -
Django- Group by and Count by unique together
I have following models: class Post(models.Model): title = models.CharField(max_length=30) class PostView(models.Model): post = models.ForeignKey(Post, related_name='views', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), related_name='my_views') created = models.DateTimeField(auto_now_add=True) I want to get post views count, grouped by hour of day and unique. for example if a user sees a post at 10 AM 20 times, just one time should be calculated. I get the posts in hours by views (not unique views) as following: from django.db.models.functions import TruncHour from django.db.models import Count qs = PostView.objects.all().annotate( hour=TruncHour('created') ).values( 'hour' ).annotate( c=Count('id') ).values('hour', 'c') above code will calculate all views as total views. I want to get unique views by user_id and hour and post_id together. Is it possible to do that with ORM? -
How to store Array in MongoDB using Django MongoEngine
I'm creating a quiz app in django and mongodb using mongoengine. In multiple choice model. I need an variable array to store all the choices of each question. I'm a total beginner so need a little help. Here's the code: class multichoice(Document): m_title = fields.StringField(primary_key=True, max_length=255, verbose_name='Title') m_question = fields.StringField(verbose_name='Question') m_question_number = fields.StringField(max_length=255, verbose_name='Question Number') m_alternatives = fields.StringField(verbose_name='Alternatives') Required Result { "_id": "Which one is the German car company", "m_alternatives": ["Honda", "BMW"], "m_question": "Which one is the German car company", "m_question_number": "2" } { "_id": "world most valuable company is:", "m_alternatives": ["Google", "Microsoft", "Amazon", "Facebook", "Coca-Cola", "Disney", "Leisure", "Samsung", "Louis Vuitton", "McDonald's", "Apple"], "m_question": "world most valuable company is:", "m_question_number": "3" } -
How to override Heroku Database Settings in Django?
I need to change the settings of my database connection on Heroku to specify the schema to use. I have been using this to override the options entry: DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default']['OPTIONS']['options'] = '-c search_path=some_schema' but this doesn't change the schema the server uses - running inspectdb, it's still connected to the default public schema. I have created the schema on the postgres instance with CREATE SCHEMA some_schema AUTHORIZATION some_username; so the schema does exist. Is there a way to override the DB settings here? -
Stripe Webhook In production Error 500 - Python
I am getting an error 500 on my webhook when I try to test it in production, however it worked fine when testing using the CLI. Here is my webhook view: @csrf_exempt def stripe_webhook(request): # You can find your endpoint's secret in your webhook settings endpoint_secret = 'secret12345' payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] fulfull_order(session) return HttpResponse(status=200) The above view returns error 500. Here is the request data from stripe: { "created": 1326853478, "livemode": false, "id": "evt_00000000000000", "type": "checkout.session.completed", "object": "event", "request": null, "pending_webhooks": 1, "api_version": "2020-08-27", "data": { "object": { "id": "cs_00000000000000", "object": "checkout.session", "allow_promotion_codes": null, "amount_subtotal": null, "amount_total": null, "billing_address_collection": null, "cancel_url": "https://example.com/cancel", "client_reference_id": null, "currency": null, "customer": null, "customer_details": null, "customer_email": null, "livemode": false, "locale": null, "metadata": { }, "mode": "payment", "payment_intent": "pi_00000000000000", "payment_method_options": { }, "payment_method_types": [ "card" ], "payment_status": "unpaid", "setup_intent": null, "shipping": null, "shipping_address_collection": null, "submit_type": null, "subscription": null, "success_url": "https://example.com/success", "total_details": null } } } I am trying to set up the … -
How to override Django's default response code?
I have two classes in my views.py to handle GET all users, GET one user and POST a new user. If I try to post a user with an id that already exists, Django throws the default 400 - bad request -error. What I'd like to do is send a 409 conflict error instead. How could I achieve this? I tried and succeeded to get the request when posting new object, but I don't know how to get the response. These are my classes: class UserListView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserView(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.AllowAny) queryset = User.objects.all() serializer_class = UserSerializer -
Django template filter count
How can i count in template in view {% for subject in subjects %} {% if subject.course.id == courses.0.id %} <li> <a href="p/teacher_list/?lessonFilter={{ subject.id }}">{{ subject.subject_name }} {% for tp in t_price %} {% if tp.subject_id.id == subject.id %} {{tp.count}} {% endif %} {% endfor %} </a> </li> {% endif %} {% endfor %} I want to show how many teachers chose this subject. Is there possible way to count in template. tp Model class Teacher_lesson_price(models.Model): id = models.AutoField(primary_key=True) teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=False) subject_id = models.ForeignKey(Subject, related_name='subject_name_rel', on_delete=models.CASCADE, null=False) course_id = models.ForeignKey(Course, on_delete=models.CASCADE , null=False, default=None) price = models.CharField(max_length=250) created_at = models.DateTimeField(default=timezone.now) -
Django Rest Framework - reduce queries and increase performance for SerializerMethodField()
I have a model like this with relationship Booking -- Payment (one to may) (one Booking can have many Payments) My problem is that I calling too many expensive queries because of SerializerFieldModel(). class Booking(AbstractItem): accommodation = models.CharField(max_length=100) room = models.CharField(max_length=100) booking_method = models.CharField(max_length=100) class Payment(AbstractItem): booking = models.ForeignKey(Booking, on_delete=models.CASCADE) # paid, refund status = models.PositiveIntegerField(choices=core_choices.PAYMENT_STATUS, default=core_choices.PAID, null=True) # cash, credit_card, transfer payment_method = models.PositiveIntegerField(choices=core_choices.PAYMENT_METHOD, default=core_choices.CASH) price = models.DecimalField(max_digits=10, decimal_places=0, null=True) This is my serializer class BookingXLSXSerializer(ModelSerializer): paid_cash = SerializerMethodField() paid_card = SerializerMethodField() refund_cash = SerializerMethodField() refund_card = SerializerMethodField() class Meta: model = Booking fields = ('id', 'accommodation ', 'room', 'booking_method', 'paid_cash', 'paid_card', 'refund_cash', 'refund_card') def get_paid_cash(self, obj): payments = Payment.objects.filter(booking=obj.id, status=core_choices.CASH) cash = 0 for payment in payments: cash += payment.price return cash ... this is my view: class MyExampleViewSet(ListAPIView): queryset = Booking.objects.all() serializer_class = BookingXLSXSerializer pagination_class = SuperLargePagination I noticed that many SerializerMethodField() could share query and use different filter. Is there a smarter way to reduce calling queries for SerializerMethodField(). Or maybe a way to share the query? -
can't open manage.py file on Django (m1 Mac)
this is how error is shown on terminal I have tried using virtual envirnorment -
Python create password protected zip in-memory for Django HttpResponse
I would like to generate a password-protected Zip file for my csv data in memory and return to webpage via Django HttpResponse. So far I can generate zip file without password protection as follows: from django.http import HttpResponse import io, csv, zipfile, subprocess #... # write csv in buffer buffer_string_csv = io.StringIO() writer = csv.writer(buffer_string_csv) writer.writerow(['foo','bar']) # write zip in buffer buffer_zip = io.BytesIO() zip_file = zipfile.ZipFile(buffer_zip, 'w') zip_file.writestr('foobar.csv', buffer_string_csv.getvalue()) zip_file.close() # return zip file as response response = HttpResponse(buffer_zip.getvalue()) response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename="foobar.zip"' return response From Python code to create a password encrypted zip file? , I learned password-protecting Zip file may require 7-Zip utility. subprocess.run(['7z', 'a', '-pPASSWORD', '-y', 'password_foobar.zip'] + ['foobar.csv']) Is it possible to do that in-memory ? -
Python Django equivelant of preloading in Elixir Ecto
So I am coming from Elixir and Phoenix Background now working in a Django project. At this stage I am investigating the ORM part of Django and I have the following question Assume a model like the following class Shop(models.Model): name = models.TextField() class Product(models.Model): name = models.TextField() shop = models.ForeignKey(Shop) At this point in Ecto you can do something like the following shop = Context.get_by_id(1) shop = preload(shop, :products) and the result would be %Shop{ name: "Some name", products: [ %Product{}, %Product{} ] } Taking care of all the necceesary joing queries behind the scene is there any similar functionality when working with Django ? -
Django NoReverseMatch Error on Update and Delete Buttons
Thank you for reading my question, and for your help. I wrote a simple CRUD app, and used django-tables2 module to make my tables look pretty and more robust. I am using django 3.2, python 3.8.5, django_tables2 2.3.4. I can enter a query in the search bar on the home.html page and lists the returned results from a postgresql on the search_results.html page. On the search_results page, I have buttons next to each returned row with edit and delete options, when I hover over update buttons it points to url for localhost:8955/update/7887 or localhost:8955/delete/7887 for the delete button, of course the last four digits are unique to the returned rows, however when I click on the update or delete button I get a NoReverseMatch error. I am at my wits end what is causing the edit and delete buttons not to work, your help and assistance is very much appreciated it. Image with the returned results with the update and delete button tables.py from .models import EsgDatabase from django.urls import reverse_lazy from django.contrib.auth.models import User as user class EsgListViewTable(tables.Table): class Meta: model = EsgDatabase template_name = "django_tables2/bootstrap-responsive.html" fields = ('id','role', 'hq','system','market','state','zone','arrisseachangezone','xgsystem','xgzonecode','fto','xocnoc','snowticketassignment',) if user.is_authenticated: edit = TemplateColumn(template_name='update.html') delete = TemplateColumn(template_name='delete.html') app …