Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does the Django ORM support SQL "AS" operator?
I want to be able to write a query like... SELECT month(date) AS m, name FROM users; What is the django ORM equivalent? -
Nginx returns 403 when serving a file from S3 via x-accel-redirect
I have the following nginx config: upstream upstream_server { server localhost:8000; } server { client_max_body_size 50M; error_log /dev/stderr; listen 80; location ~ ^/document_store/(.*?)/(.*?)/(.*) { internal; resolver 8.8.8.8 ipv6=off; set $download_protocol $1; set $download_host $2; set $download_path $3; set $download_url $download_protocol://$download_host/$download_path; proxy_set_header Host $download_host; proxy_set_header Authorization ''; proxy_set_header Cookie ''; proxy_hide_header Content-Disposition; proxy_hide_header Access-Control-Allow-Origin; add_header Content-Disposition $upstream_http_content_disposition; add_header Access-Control-Allow-Origin *; proxy_max_temp_file_size 0; proxy_pass $download_url$is_args$args; } location / { proxy_pass http://upstream_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Context: All requests hit the / block and are proxied to the django app running on gunicorn behind this server. For some requests, the django app will return a 200, with an x-accel-redirect header of the form: /document_store/<PROTOCOL>/<PRE-SIGNED S3 URL>. Expected behaviour: Nginx intercepts the response with the x-accel-redirect header, and instead serves the file from the pre-signed s3 url. Actual behaviour: Django successfully returns a 200, with the header set as expected. Nginx intercepts this request, and returns a 403. I have logged out the contents of the x-accel-redirect header, and passed <PROTOCOL>://<PRE-SIGNED S3 URL> to curl, which results in the file being downloaded successfully, so I am confident that: The header is being constructed properly The pre-signed header gives … -
'NoneType' object has no attribute 'display_name' in django
I have an django project where there are some apps , and models.py for each app with some ForiegnKey Fields. like below. for example this is Master_data app and inside models : class MaintenanceType(models.Model): name = models.CharField(max_length=10) display_name = models.CharField(max_length=100, null = True, blank = True) def __str__(self): return self.display_name or self.name calculator app model: class FamilyGroup(models.Model): name = models.CharField(max_length=10, choices=name_choices) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_type = models.ForeignKey(FamilySituation, on_delete=models.PROTECT, null=True, blank=True) maintenance_type = models.ForeignKey( MaintenanceType, on_delete=models.PROTECT, limit_choices_to={'name__in': ['Single', 'Couple']}, null=True, blank=True) so i have a property function in the FamilyGroup model : @property def maintenance_type_rate(self): b = self.maintenance_type.display_name r = MaintenanceTypeRate.objects.filter( Q(rate__gte=0) & Q(maintenance_type__display_name=b)) for d in r: return float(d.rate or 0) im getting an error 'NoneType' object has no attribute 'display_name' the error occurs at the property function traceback: File "/home/abdallaoss/cra-calculator/calculator/models.py", line 301, in maintenance_type_rate b = self.maintenance_type.display_name or Exception Type: AttributeError at /calculator/transaction/ Exception Value: 'NoneType' object has no attribute 'display_name' -
How to use django exceptionreporter's get_traceback_text() function?
I want to collect info about the exception that happened on the server by saving the exception's text (e.g traceback) in the database. How to do this without using any third-party apps like Sentry? How to create a view, that handles http500 errors on site and saves their traceback in database? -
Django Group By Permutations of ManyToManyField
I'd like to perform a group_by on a ManyToManyField habit_type = models.ManyToManyField(HabitType, blank=True), but not on every single existing element but on the existing permutations. E.g. currently there are 7 existing elements which are referenced to and with the query below it is grouped by each element. I'd like to group by the existing permutations like (1,2), (1,3,5), (1,4,6,7) But I do not want all possible combinations which would be a little bit too much... result = obj.registration_set.values(habit_type=F('participantpersonal__habit_type'))\ .annotate(number_personal=Coalesce(Count('participantpersonal__habit_type'), 0)) return result As example I have 6 entries with the habit (1,2) the current output is: { "habitTypeGroup": 1, "numberGroup": 6 }, { "habitTypeGroup": 2, "numberGroup": 6 } And my wished output is: { "habitTypeGroup": [1,2], "numberGroup": 6 }, Thanks for your help in advance -
Receiving a hidden input trough a submit button that has also other functionalities
I am building a django app in which the user has to write a sentence in a text box. After that the user has to click on continue and the sentence gets sent to the server and received by it. then it returns the next html page and with the sentence as context data for the render function. Now on this second html page the user has to record an audio of a word he sais. The word is then turned into a string and after that sent to the server trough a submit button. Since I passed the sentence to the second html page I can put a hidden input that has the sentence as value on the second html page. But now I would like that this sentence(the hidden input value) gets sent to the server with the word as a string. And this is what I tried but it does not work and I do not understand why. This is the impotant part of the second html page: <div id='result' class='voc'> Your text will appear here </div> <br> <div id= 'record'> <button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button> <form action="/audio_data" method="POST"> <button class='btn btn-info btn-sm ml-3' value="Send" id="send" … -
cant add mysql database in django
i have problem with mysql database. i creat new django project. and i add in settings.py mysql database connection information after that i migrate to mysql database and everything is fine. data tables was created and information of admin was added to user_auth. when i created superuser with python manage.py createsuperuser user was added to user_auth table in phpmyadmin "mysql" database. but when i want to enter on admin panel i'm getting this error. screenshot of admin login "picture" user is created in database "picture" my settings.py code import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'century_21_db', 'USER': 'century21', 'PASSWORD': '!nxSb543js!6bX60', 'HOST': 'localhost', 'PORT': '3306', } } -
Filter Djangos Admin list_display and inline
I have a table with films which is connected through intermediate table to to the table Person, which has name and role (writer, actor, director) a person. I am now searching a way to display writers, actors and director separately in list_display. What I have made: list_display = ('title', 'ratings', 'created_on', 'actors', 'writers', 'director') def actors(self, obj): actors = FilmWork.objects.filter(person__role__iexact='actor').values_list('person__name', flat=True) return ", ".join([a for a in actors]) (Same for writers and director). But it shows all actors to each film, but not only belonging to this film. The same in inline edit form, I want to edit them separately, but see the whole list of the names: class ActorInlineAdmin2(admin.TabularInline): model = FilmWork.people.through def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(person__role__iexact='actor') How can I fix it? Is there actually also a way to add new name to the inline, if there is no such name in the drop down? My models: class FilmWorkPerson(models.Model): movie = models.OneToOneField('FilmWork', models.DO_NOTHING, primary_key=True) person = models.ForeignKey('Person', models.DO_NOTHING) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'film_work_person' unique_together = (('movie', 'person'),) class FilmWork(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) people = models.ManyToManyField('Person', through=FilmWorkPerson) class Person(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=100) role = models.CharField(max_length=100) created_on … -
Is there any way to perform QueryStrings through selenium. If my selenium project is to automate recharges
I want to create a link to my selenium mobile recharge file. Thus whenever I hit no. and amount in the link (maybe using query string) it should automate my ** pay.find_element_by_id('mobileNumberTextInputId').send_keys('1234567890')** to something like "automatically" adding no. to 'send.keys' does class= "pagination" can solve my issue? if yes then how? do I have to first create a template to run selenium? or POSTMAN is one of the options? -
Django: TypeError: 'Dossier' object is not iterable while implementing Ajax and Json
I am trying to implement CRUD using Ajax and Json following this tutorial. My URL: from django.urls import path from . import views urlpatterns = [ path('dossier_create/', views.dossier_create, name="dossier_create"), ] My Views: def dossier_create(request): if request.method == 'POST': dossier_form = DossierForm(request.POST) activity_form = ActivityForm(request.POST) else: dossier_form = DossierForm() activity_form = ActivityForm() return save_dossier_form(request, dossier_form, activity_form, 'sbprofile/dossier/partial_dossier_create.html') def save_dossier_form(request, dossier_form, activity_form, template_name): data = dict() if request.method == 'POST': if dossier_form.is_valid() and activity_form.is_valid(): dossier_form = dossier_form.save(commit=False) dossier_form.added_by = request.user dossier_form.added_date = timezone.now() dossier_form.save() dossier = get_object_or_404(Dossier, id=dossier_form.id) activity_form = activity_form.save(commit=False) activity_form.dossier = dossier activity_form.added_by = request.user activity_form.added_date = timezone.now() activity_form.save() data['form_is_valid'] = True dossiers = Dossier.objects.all() data['html_dossier_list'] = render_to_string('sbprofile/dossier/partial_dossier_list.html', { 'dossiers': dossiers }) else: data['form_is_valid'] = False context = {'dossier_form': dossier_form, 'activity_form': activity_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) My JS: // Create dossier $(".js-dossier-create").click(loadForm); $("#modal-dossier").on("submit", ".js-dossier-create-form", saveForm); var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-dossier").modal("show"); }, success: function (data) { $("#modal-dossier .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#dossier-table").html(data.html_dossier_list); $("#modal-dossier").modal("hide"); } else … -
Django Foreign key automatic assignment on form submission
Hey Fellow Django coders I have a Booking(Parent) and tblProcessBooking(Child) tables so I created a model form of the tblProcessBooking that has a foreign key called Approval_Status, so I want the Approval_Status to match the correct booking please check my HTML file and image to see what I mean. I tried setting using a dyanamic url valvue by saving it into a cache then accessing it in the Admin_home function as to set the approriate foreighn key value for the corresponding booking. MODELS.PY FILE class Booking(models.Model): purposes = (('Per', 'Personal use'), ('SV', 'Site Visit'),) pick_up_locations = (('JHB', 'Johannesburg Office'), ('DBN', 'Durban Office'), ('PE', 'Port Elizabeth Office'), ('MP', 'Mpumalanga Office'), ('PLK', 'Polokwane Office'), ('BLOE', 'Bloemfontein Office'), ('CPT', 'Cape Town Office'), ('MFK', 'Mafikeng Office'),) purpose = models.CharField(max_length=255, choices=purposes) description = models.CharField(max_length=1080, default='') client_name = models.CharField(max_length=255) pickUp_date = models.DateTimeField() dropOff_date = models.DateTimeField() booking_date = models.DateTimeField(default=datetime.now()) pickUp_location = models.CharField(max_length=255, choices=pick_up_locations) dropOff_location = models.CharField(max_length=255, choices=pick_up_locations) destination = models.CharField(max_length=255, ) vehicle_type = models.ForeignKey(VehicleType, default=10, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.SET_NULL, null=True, blank=True) unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) def __str__(self): id_ = str(self.pk) return id_ class tblProcessBooking(models.Model): statuss = (('A', 'Approved'), ('D', 'Declined')) status = models.CharField(default="Pending", max_length=1080, choices=statuss) description = models.CharField(max_length=1080, default='Booking requirements met') date_processed = models.DateTimeField(default=datetime.now, … -
How to access the csrf_token inside django view
I'm trying to access the csrf_token inside the django view function. I have tried importing the csrf: from django.template.context_processors import csrf and using it like this landingPageHtml = landingPageHtml.replace('csrf_token', csrf(request)['csrf_token']) But I'm getting an error. second argument must be a str not lazy object. How can I access the csrf token in a view? @login_required def viewLandingPage(request, slug): lp = getLandingPage(request, slug) landingPageHtml = getLandingPageFile(request, lp['file']) landingPageHtml = landingPageHtml.replace( '{{ lp.seo_title }}', lp['seo_title']) landingPageHtml = landingPageHtml.replace( '{{ lp.seo_description }}', lp['seo_description']) landingPageHtml = landingPageHtml.replace('csrf_token', 'csrf_token') return HttpResponse(landingPageHtml) -
Django: invalid certificate after installing SSLSERVER
I am trying to run my server with https, so I installed django-sslserver, and running as below. py manage.py runsslserver --certificate F:/certs/server.crt --key F:/certs/server.key 127.0.0.1:8000 The output after execution is: Watching for file changes with StatReloader Validating models... System check identified no issues (0 silenced). January 22, 2021 - 23:20:11 Django version 3.1.2, using settings 'ecommerce.settings' Starting development server at https://127.0.0.1:8000/ Using SSL certificate: F:/certs/server.crt Using SSL key: F:/certs/server.key Quit the server with CTRL-BREAK. The website is running well but I still get What is wrong? -
saving generated otp into database
i am creating a booking system in which i send the user a code via sms when they submit their booking form, the code is for them to bring to the company when they are attending their appointment but i am failing to save the code to the database, the code is generated and passed on in the message, here is the views.py file code = generateOTP() def booking(request): if request.method == 'POST': print(request.POST) book = BookingForm(request.POST, ) if book.is_valid(): phone = book.cleaned_data['phone'] book = book.save(commit=False) book.user = request.user book.otp_code = request.GET.get[code] book.save() messages.success(request, 'Form submission successful') sendSms(message, phone) msg_body = f''' Hello {request.user.username}! Your Verification Code is : {code} Make sure you give this code when attending booking Thank you for booking with us :) ''' Models.py class Booking(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) otp_code = models.CharField(max_length=6, null=True) -
Django - How to take first word of a string in html template?
I have this list where I want to only get the first word (I would like to remove the "engineering" in all of them) and I am displaying this in my html template like this: {% for course in courses %} <li>{{ course }}</li> {% endfor %} I tried to do this: {% for course in courses %} <li>{{ course|first }}</li> {% endfor %} but it only gives me the first letter of each string. I know that i can do the truncate but not all of them have the same number of letters. I also tried to do this but to no avail. What solutions can I try? Thanks in advance! -
Does DRF Model serializer preserve the order in the list when creating multiple objects?
I want to use ModelSerializer to create multiple objects. If I have a list of the data for the objects as, data = [{object_1_data},{object_2_data},...] and when I use model serializer to create the objects as, serializer = serializer(data=data, many=true) if serializer.is_valid(): objects = serializer.save() Does the return objects list contain the objects in the same order as earlier? objects = [object_1, object_2, ...] -
OperationalError at /admin/products/product/ about slugfield
my models.py from django.db import models class Product(models.Model): category_name = models.CharField(max_length=60, default='') category_url = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return "%s" % (self.category_name) class Mobile_Brand(models.Model): brand = models.CharField(max_length=60, default='') brand_url = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return "%s" % (self.brand) class Mobile(models.Model): mobile_model = models.CharField(max_length=255, default='') mobile_brand = models.ForeignKey(Mobile_Brand, verbose_name="Mobile_Brand", on_delete=models.CASCADE ) category = models.ForeignKey(Product, verbose_name="Product", on_delete=models.CASCADE, default='' ) mobile_img = models.ImageField(upload_to="mobile",default='') mobile_url = models.SlugField(max_length=200, unique=True, default='') and after makemigrations and migrate when i go to admin page and Mobiles page or other ones, i see such errors for Products section : no such column: products_product.category_url for Mobiles section : no such column: products_mobile.mobile_url for Moblie_Brands section : no such column: products_mobile_brand.brand_url thanks for help -
Field 'id' expected a number but got 'admin'. in django
i created this to make searchbox to search models, when i replace body instead of author it works perfectly and fetches data accurately but when i use foreign key object string input is not working but when i type pk of user it fetches the username accurately but does not accept string for eg: when i type name of the post it gets but on author when i type name of the author it says following error and does not accept string but can accept pk and fetch author pls edit this code such that when i type name of the author it gets the name and their post HELP IS MUCH APPRECIATED views.py def search(request): query = request.GET['query'] allposts = bio.objects.filter(author=query) params = {'allposts':allposts} return render(request,'profile_app/search.html',params) models.py class bio(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) body = models.CharField(max_length=50) search.html <h1>this is home</h1> <form action="/search" method="get"> <input type="search" name="query"> <button type="submit">press here</button> </form> -
django reverse url erro
I have following code in urls.py urlpatterns=[ path('estimate_insert/',views.estimate_ui,name='estimate_i'), path('<int:id>/',views.estimate_ui,name='estimate_u'), path('estimate_delete/<int:id>/',views.estimate_d,name='estimate_d'), path('estimate_preview/<int:id>/',views.estimate_preview,name='estimate_v'), ] I am matching these urls to the following code in views.py def estimate_ui(request,id=0): if request.method=="GET": if id==0: form=EstimateForm() else: obj_estimate=Estimate.objects.get(pk=id) form=EstimateForm(instance=obj_estimate) return render(request,"Invoices/estimate_ui.html",{'form':form}) else: if id==0: form=EstimateForm(request.POST) else: obj_estimate=Estimate.objects.get(pk=id) form=EstimateForm(request.POST,instance=obj_estimate) if form.is_valid(): form.save() return redirect('/invoices/') the below mentioned url is causing problem when I access it. path('<int:id>/',views.estimate_ui,name='estimate_u'), When I access I get the following error NoReverseMatch at /invoices/status/3/ Reverse for 'estimate_u' with arguments '('',)' not found. 1 pattern(s) tried: ['estimate/(?P<id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/invoices/status/3/ Django Version: 3.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'estimate_u' with arguments '('',)' not found. 1 pattern(s) tried: ['estimate/(?P<id>[0-9]+)/$'] can anyone explain why is this happening. I am accessing index.html--> linked to move to status.html(it has link to move estimate.html)--> at estimate.html I have many steps its basically a workflow based application. I watched almost all url related videos at youtube, searched google but found nothing that could help. thanks -
redirect Django to custom page after social login and then redirecting to previous page using ?next
In django, When user logs in using Login from google, I am redirecting it to /user/profile/picture/ where I am doing some code to store profile picture in another table. Then I want to redirect the user to previous page where he/she clicked Siginin in with google What I have tried: In settings.py LOGIN_REDIRECT_URL = '/user/profile/picture/' In home.html <a href="{% provider_login_url 'google' %}?next={{request.path}}"> The main problem is here. Django redirects to /user/profile/picture/ and it loses the next parameter. And if I remove the line LOGIN_REDIRECT_URL = '/user/profile/picture/, the problem is that it will not create a new row in table for setting profile picture and it will directly redirect to previous page using next paramter. What I want? I want django to redirect me first to user/profile/picture and then redirect me to the previous page where user clicked on Sigin with Google PS: I am using django 3.0.5 if it makes any difference. -
Djongo Boolean Filed get query is giving key error
i am using MongoDB(3.6) in Django(3.1.5) through djongo(1.3.3). ########### models.py ############ from djongo import models class ModelClass(models.Model): name = models.CharField(max_length=250) is_active = models.BooleanField(default=True) ########### view.py ############# def model_class_view(request): obj = ModelClass.objects.get(name='name', is_active=True) it giving an error DatabaseError No exception message supplied -
How can I access my uploaded images in amazon s3 bucket with no public access in django martor markdown?
I store all my media files in AWS s3 bucket and it works fine but the only problem is Martor. If i upload images from martor editor the image will be uploaded to my s3 bucket but can't be displayed in my template due to the 403 forbidden error request. The reason it's error is because my s3 bucket is not in public access mode and I don't want it to be in public access mode. So i need accessID and signature to access my images in s3 bucket in markdown editor. My question is How can I pass my accessID and signature to the get request? This is the package that i'm using https://github.com/agusmakmun/django-markdown-editor. -
Twitter request token OAuth returns {'code': 215, 'message': 'Bad Authentication data.'}
Where I made mistake, it always return bad authentication data. is it right method to get OAuth token from twitter oauth. otherwise any method belongs to django is thankful. oauth_timestamp = str(int(time.time())) oauth_consumer_key = "xxx" oauth_signture = "xxxx" payload = {'OAuth oauth_nonce': '40575512181348616041501137897', 'oauth_timestamp': oauth_timestamp, 'oauth_version': '1.0', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_consumer_key': oauth_consumer_key, 'oauth_signature': oauth_signture, 'oauth_callback': 'callback url' } url = requests.post('https://api.twitter.com/oauth/request_token/', data=payload) token = url.json() print(token) -
Reveal a foreign kei in the admin site
Django 3.1.5 Model class MacroToponymSynonym(NameMixin, models.Model): """ Synonym of a macro toponym. """ macro_toponym = models.ForeignKey(MacroToponym, on_delete=models.PROTECT, verbose_name="Макротопоним") def get_macro_toponym(self): return "tmp" # Breakpoint get_macro_toponym.short_description = 'Macro toponym' class Meta: verbose_name = "Synonym for macrotoponym" verbose_name_plural = "Synonyms for macrotoponyms" Admin class MacroToponymSynonymAdmin(admin.ModelAdmin): exclude_fields = [] readonly_fields = ["id", ] list_display = ("id", "macro_toponym", "get_macro_toponym", "name") admin.site.register(MacroToponymSynonym, MacroToponymAdmin) In the admin site I can see only id and name. And the interpreter doesn't stop at the breakpoint (marked in the code). Well, neither macro_toponym, nor get_macro_toponym didn't show in the admin site. Could you help me reveal this field? -
saves_null_values (Field) in Django import and export is not working
Hello everyone I have created one webpage where I am using Django ‘import_export’ Resource for .xlsfile upload. I am having below fields name in the .xls file as shown below image. from import_export import resources,widgets,fields class CTAResource(resources.ModelResource): AConnectID = fields.Field(column_name=‘AConnectID’, attribute=‘AConnectID’, saves_null_values=False) class meta: Model=CTA Here When I am uploading records from the .xls file and I am keeping AConnectID empty but I am not getting any error and the file is getting uploaded successfully(I am not doing it from the admin site). Here is my code responsible to upload data. def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded Successfully...') except: messages.info(request, 'Same Email ID has been observed more than once.Except that other records has been added../nPlease Make sure Email field should be unique.') return render(request, 'app/cta.html') Can …