Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
simple search in django. Please any help on why it is not showing the result
Please any help on why it is not showing the result. views.py def display_object(request): obje= ObjectName.objects.all().order_by('objectName') paginator = Paginator(obje, 3) page = request.GET.get('page') obj= paginator.get_page(page) query_list = ObjectName.objects.all() query= request.GET.get("q") if query: query_list= query_list.filter(objectName__icontains = query) imp = { "Objects":obj, } return render(request,'Impact/displayObject.html',imp) displayObject.html <form method='GET' action=''> <input name='q' type="text" value='{{ request.GET.q }}' placeholder="Search..."/> <input type="submit" value="search"/> </form> output output -
How to replace some specific characters in django template?
Some values from database get fetched and passed to the template like this :['2'] In controller : book = Book.objects.get(id=id) return render(request, 'file.html', {'book': book}) In template: {{book.pages}} output : ['140'] How to delete brackets and ' before delivering the result? -
Application logs appear only after a restart in Docker
I have a Django app that I am developing. I am using Docker Compose locally. I sometimes like to do print(some_variable) for debugging purposes. However, when I run the code that print() statement has no effect. Only after I change something in the code, the logs appear in the console. For example, if I change print(some_variable) to print('Behold: ' + some_variable), the old print will work and in logs I see the value of the variable. How can I make it real time so that I don't have to change the code to make it restart? -
Elasticbeanstalk; can't reach the page after trying to foward http to https
My project that is deployed into elasticbeanstalk doesn't work after updating it. What I was trying to do is to configure https. I was following this tutorial and add https.config file. files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: | RewriteEngine On <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'"> RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L] </If> But after redeployting it, the site doesn't work. (It says can't reach this page.) So I removed the file and redeploy it. But seems like it's still looking for https:// page. How can I fix this problem and how to forward http to https correctly? -
Rename file during upload Django CreateView
I need to now if there is a way to rename a file during the upload using the Django generic CreateView or UploadView. -
Django with NGINX Server not allowing request on port 443 SSL
A piece of code in Python 3.5 was scrapping correctly in order to save products in a mysql server via api-rest, where a project in Django 1.10.4 is running. When the server got changed, it has started to throw an error 500 when executing the method PUT in order to save products, which come in Json format. The configuration of the server, running with Nginx and Gunicorn, is as follows: server { listen 80; server_name www.xxxxxxxx.es; return 301 https://www.xxxxxxx.es$request_uri; } server { listen 443 default ssl; ssl_certificate /etc/letsencrypt/live/xxxxxx.es-0001/fullchain.pem; # ssl_certificate_key /etc/letsencrypt/live/xxxxxx.es-0001/privkey.pem; client_max_body_size 5M; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/thebest5; } location /media/ { root /home/ubuntu/thebest5; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/thebest5/thebest5.sock; } } The code of the scrapper in python which is storing products fails in this line when doing a debug: response = requests.put(API_URL + 'scan/' + str(self.search_tag[id]), data= json.dumps(self.search_tag), headers={'Authorization': 'JWT ' + self.token, 'Content-Type':'application/json'}) The scrapper runs well until it tries to save products in the database server, then the PUT method fails with a 500 error. The error says: C:\Users\ana\Anaconda3\lib\site- packages\requests\packages\urllib3\response.py in _update_chunk_length(self) 534 try: 535 self.chunk_left = int(line, 16) 536 except … -
Django ForeignKey create
i want to assigin many Region to a UserProfile model, how to do it ? the code class Region(models.Model): name = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now=True) class UserProfile(models.Model): user = models.OneToOneField( region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True) -
Django getting a data from another function in views
I want to use a data from another view function. Description: Firstly, I get a internship period input as integer from the user and then I want to use and get this data in another function. The function that I want to use is "period" in Internship view. I use it in AttendanceCounter view function. I don't know how can I do that. My codes: views.py @login_required(login_url='/login/') def AttendanceCounter(request): response = Internship(request) internship_period = InternshipModel.objects.only('period') attendance_user = AttendanceModel.objects.filter(name=request.user) return render(request, 'attendance_counter.html', {'attendances': attendance_user, 'response': response} ) @login_required(login_url='/login/') def Internship(request): if request.method == 'POST': form = InternshipForm(request.POST) if form.is_valid(): internship = InternshipModel() # internship.period = form.cleaned_data['period'] internship.name = form.cleaned_data['name'] internship.save() return redirect('myattendance') else: form = InternshipForm(initial={"name": request.user.username}) return render(request, 'internship_period.html', {'form': form}) models.py class AttendanceModel(models.Model): name = models.CharField(max_length=100, default=User) date = models.DateTimeField(default=datetime.now) class Meta: unique_together = ('name', 'date',) class InternshipModel(SingletonModel): name = models.CharField(max_length=100, default=User) period = models.IntegerField() sorry for my bad English. -
Django Admin--show choices based on a date--parking_on
I want to implement in my django admin a function that will display only the available parking plots. Today in my database there are only 2 parking plots occupied(P1 and P6) therefore i want to show to the user only the spaces that are free for the day when he wants to book the plot ==> the filed's name is parking_on. If all are books then would be nice to have a message like "No luck for today! :)" My models look like this: class ParcareManager(models.Manager): def active(self, *args, **kwargs): return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now()) class Parcare(models.Model): PARKING_PLOT = ( ('P1', 'Parking #1'), ('P2', 'Parking #2'), ('P3', 'Parking #3'), ('P4', 'Parking #4'), ('P5', 'Parking #5'), ('P6', 'Parking #6'), ('P7', 'Parking #7'), ('P8', 'Parking #8'), ('P9', 'Parking #9'), ('P10', 'Parking #10'), ('P11', 'Parking #11'), ('P12', 'Parking #12'), ('P13', 'Parking #13'), ('P14', 'Parking #14'), ('P15', 'Parking #15'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, default=1, on_delete=True) # name = models.CharField(max_length=120,blank=True, null=True) # slug = models.SlugField(unique=True) email=models.EmailField(blank=True, null=True) # email = models.EmailField(settings.AUTH_USER_MODEL) parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True) parking_off = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) #plecarea din parcare numar_masina=models.CharField(max_length=8, default="B100AAA", blank=True, null=True) location =models.CharField(max_length=3, default="P1", blank=True, null=True, choices=PARKING_PLOT) updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True) timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True) venire … -
Updating the value of another model in Django Models
I cannot find a way to update the value of 'no' in Class A from Class B in Django Models class A(models.Model): no = models.IntegerField() class B(models.Model): a = models.ForeignKey(A) def UpdateNo(self) #update no of class A How to update 'no' field from -
Communication between Django and React
I'm trying to setup a project using Django for backend and React for frontend. The project has several screens, a lot of information in DB and images generated by the backend, and will include some authentication and user permissions for different screens. According to what I found - the best way to do it is having Django render an html file: def index(request): return render(request, 'frontend/index.html') which references a .js file: <script src="{% static "frontend/main.js" %}"></script> Which is created using Webpack. This main.js retrieves the data it needs from Django using a REST api: fetch("...some Django endpoint..").then(response => ... this.setState(...retrieved data...)) Unlike when just using Django for backend + Django templates for frontend where the backend can just send the context directly to the template: def index(request): context = {'information': .... retrieve info from DB} return HttpResponse(loader.get_template('bla/index.html').render(context, request)) and the template can use this info directly, without referencing the backend again: {% for bla in information %} I'm wondering if it is a reasonable setup? It seems excessive to have the frontend use REST for retrieving each piece of information it needs and the backend exposing another REST api for each part of data it needs to supply (Instead of … -
Django response error 'unicode' object has no attribute '_meta' json
I'm using django 1.11 and i'm getting a tough time in storing a Json response.Here's my views.py code views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from .models import addinfomodels from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.core import serializers import json # Create your views here. def addinfo(request): batch_year = [2016, 2017, 2018] dept = ['AERO', 'BME', 'CIVIL', 'CSE', 'ECE', 'EEE', 'E&I', 'MECH'] type = ['onecredit', 'core', 'professional', 'openelective'] return render(request, "cbcsportal/addinfo.html", {'type': type, 'batch': batch_year, 'dept': dept}) def rollvalue(request): return request.POST.get('rollno') # d ={} def jsonvalue(request): d = {"courses":[{"choices": [request.POST.get('choices00') ,request.POST.get('choices10')], "code": request.POST.get('code0'), "name": request.POST.get('name10')}]} ds = serializers.serialize('json', d) print ds return JsonResponse(ds, content_type="application/json", safe=False) def posttodb(request): if request.method == "POST": data = addinfomodels() data.batch = request.POST.get('batch') data.dept = request.POST.get('dept') data.typeid = request.POST.get('typeid') data.type = request.POST.get('type') data.rollno = [rollvalue(request)] data.renderJSON = jsonvalue(request) data.starttime = request.POST.get('starttime0') data.endtime = request.POST.get('endtime0') data.save() return redirect('addinfo') please help me i'm getting this error 'unicode' object has no attribute '_meta' -
django ORM turns two conditions on related table into two separate JOINs
I have the case that I need to filter on two attributes from a related table. class Item(models.Model): vouchers = models.ManyToManyField() class Voucher(models.Model): is_active = models.BooleanField() status = models.PositiveIntegerField() When I query the ORM like this: Item.objects.exclude( vouchers__is_active=False, vouchers__status__in=[1, 2]) The created query looks like this: SELECT * FROM `item` WHERE NOT (`item`.`id` IN ( SELECT U1.`item_id` FROM `itemvouchers` U1 INNER JOIN `voucher` U2 ON (U1.`voucher_id` = U2.`id`) WHERE U2.`is_active` = FALSE) AND `item`.`id` IN ( SELECT U1.`item_id` FROM `itemvouchers` U1 INNER JOIN `voucher` U2 ON (U1.`voucher_id` = U2.`id`) WHERE U2.`status` IN (1, 2)) ) I want to exclude vouchers which are both inactive AND have status 1 or 2. What the query does is creating two separate joins. This is at first unnecessary and bad for performance. Second it's just wrong. Case: voucher_a = Voucher.objects.create(status=3, is_active=True) voucher_b = Voucher.objects.create(status=1, is_active=False) If I have an item in related with voucher_a and voucher_b it does not get found because it is in JOIN 1 but not in JOIN 2. It looks like a bug in django but I wasn't able to find anything useful on the web to this topic. We are on django==2.1.1 and tried out switching exclude with filter … -
how to call another api in view.py and add responce to first api responce in django
I want to call the second API using the reverse function in view.py and after successful response want to add in response to first API. How do this please give me any example. -
django rest framework context is not passed to serializer during POST
I have two serializers for an EmployeeViewSet as EmployeePOSTSerializer and EmployeeUPDATESerializer: class EmployeePOSTSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=None, min_length=None, allow_blank=False) class Meta: model = Employee fields = ('email', 'access') def validate_access(self, value): requester = self.context['user'].works.get(business__id=self.context['business_id']) if requester.access>value: raise serializers.ValidationError("Not allowed.") return value class EmployeeUPDATESerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['access'] def validate_access(self, value): requester = self.context['user'].works.get(business__id=self.context['business_id']) if requester.access>value: raise serializers.ValidationError("Not allowed.") return value views.py class EmployeeViewSet(viewsets.ModelViewSet): serializer_class = EmployeeSerializer action_serializers = { 'create': EmployeePOSTSerializer, 'update': EmployeeUPDATESerializer, 'partial_update': EmployeeUPDATESerializer } def get_serializer_context(self): return {'user': self.request.user, 'business_id': self.kwargs['business_id']} def get_queryset(self, **kwargs): #some queryset def create(self, request, *args, **kwargs): #create def get_serializer_class(self): assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ ) if hasattr(self, 'action_serializers'): if self.action in self.action_serializers: return self.action_serializers[self.action] return self.serializer_class As you can see both EmployeePOSTSerializer and EmployeeUPDATESerializer have a validate_access method(same methods). I am passing the context to the serializers through the get_serializer_context method in the EmployeeViewSet. But it appears that the context data is passed only for the EmployeeUPDATESerializer and not EmployeePOSTSerializer. During update I was able to get the context data and validate_access with the data. But during post i.e, creation of an object the … -
How to generate unique 8 length number, for account ID for example (Python,Django)
I need to generate unique account ID for each user.(only numeric) UUID can't solve this problem, pls help me! -
django latex build-in
I am building blog site for myself by using django, as I come from math and economics, it should be trivial to write equations and/or latex. I have searched google and tried some solution but I don't have a clue even now. I want to do this easily in posting Post, like writing $c = SN(d_1) - Ke^{-rT}N(d_2)$, and then it will be presented. -
Django TabularInline Admin: put instance value in formfield_for_foreignkey
I wanna get student study class name and match with the subject then filtering her subject within my TabularInline Admin section. I did try to match StdSubject with model admin student instance. I know whole problem in here kwargs["queryset"] = StdSubject.objects.filter(std_subject_class__std_class_name_N__exact=self.std_name) and problem with self.std_name in that line I want to match with std_name. But showed error. This is my code. class MarksSubjectInstanceInline(admin.TabularInline): model = Marks fk_name = 'std_name' extra = 2 exclude = ['subject_gradepoint', 'subject_gpa','subject_gpa_sub', 'subject_marks', 'subject_total_marks'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "subject_name": kwargs["queryset"] = StdSubject.objects.filter(std_subject_class__std_class_name_N__exact=self.std_name) return super().formfield_for_foreignkey(db_field, request, **kwargs) @admin.register(StudentInfo) class StudentAdmin(admin.ModelAdmin): search_fields = ('std_name','std_roll','std_group') list_filter = ('std_class', 'std_gender', 'std_group',) list_display = ('std_name', 'std_class', 'std_group', 'std_gender', 'std_roll') inlines = [MarksSubjectInstanceInline] exclude = ['std_total_marks', 'std_gpa','std_grade_point_total_sum','std_marks_with_fail_sub', 'std_grade_point_total_subject_avg', 'std_fail_subject','school_rank','class_rank'] -
How to parse json data and load it to django template
How would i parse it to load store address id and title from the api to the select option value ? what i have tried so far <select> {% for store in stores.store_address %} <option value="{{ store.store_address.id}}">{{ store.store_address.title}}</option> {% endfor %} </select> code in getting the data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) stores = requests.get('https://api.myjson.com/bins/16tdlw').json() context['stores'] = stores return context URL : https://api.myjson.com/bins/16tdlw (json data) Template : <select> {% for store in stores.store_address %} <option value="{{ store.store_address.id}}">{{ store.store_address.title}}</option> {% endfor %} </select> -
Change default data in forms
I have this form: https://imgur.com/NUJH2f7 And I have a question, how to make the user be able to set the default value in choice field which will be in the form ? Or how to make the form remember the last entered data ? -
Model field length constraint with validation response in serializer
I am validating data from a request in django's rest framework with data validation in the serializer. I need all error messages to be sent in a single response. On sending a string that is too long, i get the error: django.db.utils.DataError: value too long for type character varying(3) In my model I've defined the max length of the character field as 3 (max theoretically needed). I've added validation in the serializer to catch requests with too many characters: validators.py class CustomUserValidators(): errors_to_return = {} if len(role) > 3: self.errors_to_return["role_length"] = "Ensure this field has no more than 3 characters." serializers.py from Sea.validators import CustomUserValidators class LagoonUserCreateSerializer(UserCreateSerializer, CustomUserValidators): class Meta: model = User fields = ('id', 'username', 'role',) def validate(self, attrs): self.val_role(attrs['role']) if len(self.errors_to_return) > 0: raise serializers.ValidationError(self.errors_to_return) return attrs models.py class SeaUser(AbstractUser): ... role = models.CharField(_('Role'), max_length=3) But the request still returns the error (value too long... as above). I expected the erorr to be caught in the serializer and the values not passed to the model, why is the value ever reaching the model? I have researched this, and all the solutions say make the field length 255. This doesn't answer why the value is ever being tested … -
Django open floder in windows expoler
I try add button to my website that will open drive c: in windows explorer. I try subprocess.Popen('explorer "%s"' % win_dir) webbrowser.open('file:///C:/', new=2) The above works only in my django local server, when i try run this in my iis server subprocess and webbrowser function not works. -
How create trigger in Django Rest Framework to change booleanfield?
I have a question in django rest framework. Since I'm learning how to use some advanced options, I do not quite understand. I need to currently change a booleanfield every time a foreignkey is inserted into table. How can I do this in model ? Model: class Persona(models.Model): name = models.CharField(max_length=32) cart = models.ForeignKey(Credit,null=True) rg = models.IntergerField() end = models.CharField(max_length=256) details = models.TextField(blank=True, null=True) order = models.ForeignKey(Order, null=True) class Meta: db_table='person' app_label = 'bank' class Credit(models.Model): number = models.CharField(max_length=16, unique=True) create_at = models.DateField(auto_add_now=True) updated_at = models.DateField() available = models.BooleanField() def __str__(self): return self.number class Meta: db_table = 'credit' app_label = 'bank' Serializer: class PersonaSerializer(serializers.ModelSerializer): order__id = serializers.ReadOnlyField(source='order.id') class Meta: model = Persona fields = '__all__' class Persona(viewsets.ModelViewSet): allowed_methods = ('GET', 'POST', 'PUT', 'PATCH') queryset = Persona.objects.all() serializer_class = PersonaSerializer -
Django crispy forms in base.html
I'm trying to set a newsletter form in the base.html. However, due to lack of personal ability and available examples, I cannot find a way to render the newsletter specific form in the base.html footer. Currently, I have the following model form based on a application model (Newsletter) at BioPyApp/forms/newsletter.py: from django import forms from BioPyApp.models import Newsletter from crispy_forms.bootstrap import Field from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, Column, Row, Div class NewsletterForm(forms.ModelForm): email = forms.EmailField(required=True,label="E-mail",max_length=254) class Meta: model = Newsletter fields = ['email'] def __init__(self, *args, **kwargs): super(NewsletterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '/newsletter' self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) self.helper.form_class = 'form-vertical' self.helper.help_text_inline = False self.helper.form_tag = False self.helper.layout = Layout(Row(Field('email'))) def clean_email(self): email = self.cleaned_data['email'] if Newsletter.objects.filter(email=email).exists(): raise forms.ValidationError("Email already in newsletter.") return email My view currently at BioPyApp/views.py: from .forms.newsletter import NewsletterForm def newsletter(request): form = NewsletterForm(request.POST or None) if form.is_valid(): form.save() return {'success': True} Which I set in url as : path('newsletter/',views.newsletter), My questions are: is this the correct structure for a global project form? What should I write in base.html? (Note: If I put {% crispy form %} other forms (depending on the url) are displayed instead.) Best … -
How Can I run a python function in script file or in the views.py using javascript for not loading the page
I have a Django page that has a form that has a button that calls functions in the views.py, but I want to validate some input text of the form via running a python script function (in views.py or I can separate this function in another file) but I don't want to load the page. where and How can I make js code to run this function?