Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass request to a Field Serializer in Rest Framework?
Hi I am using a Field Serializer to be able to serialize a PK field then deserialize it as object. Inside the serializer is a SerializerMethodField to build a custom url. It works when I use the itself from serializing its own record. However when I use it to a different serializer as a FieldSerializer, the request object is not passed. class TelemetryFileSerializer(serializers.ModelSerializer): telemetry_type = serializers.SlugRelatedField( slug_field='name', queryset=TelemetryFileType.objects.all()) receiving_station = serializers.SlugRelatedField( required=False, slug_field='name', queryset=ReceivingStation.objects.all()) link = serializers.SerializerMethodField() class Meta: model = TelemetryFile fields = '__all__' def get_link(self, object): request = self.context.get('request') print(self.context) # request is not passed here from RawImageSerializer/TelemetryFileField return request.build_absolute_uri('/data_management/telemetry_files/{}'.format(object.id)) class TelemetryFileField(serializers.PrimaryKeyRelatedField): def to_representation(self, value): pk = super(TelemetryFileField, self).to_representation(value) item = TelemetryFile.objects.get(pk=pk) serializer = TelemetryFileSerializer(item) return serializer.data class RawImageSerializer(serializers.ModelSerializer): from_telemetry_file = TelemetryFileField(queryset=TelemetryFile.objects.all()) link = serializers.SerializerMethodField() I want to pass a request of itself to be able to create a url of it. This is the returned when I use the RawImageSerializer: AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' -
group by integer range Django & posgres
i have a table which i would like to group by integer range (ages). table for example: Name Age John 21 Steve 24 Dan 29 Mike 31 my expected result is to group the name by age ranges for example [21-28] [29-33] so what i'll get is the following result: [21-28] [29-33] John Dan Steve Mike i was playing around with the annotate function of Django but couldn't figure it out so far. any suggestions? -
Django valudation email restriction
How to restrict to certain emails so that only they can register within my web? Taking all lists such as gmat, yahoo etc is lengthy. Any thought? -
how i can dynamically select page/product on form django
hello i want to save on data base where the form is comming from from any page (the page is product page) i want create ecomerce website(cash on delivery) and i have truble to now any the product is ordered on this form ,the form is work i need just this last field the product id the problem i think is there on the views to see all fiels scroll down : form = Modelform(request.POST) Modelform.Product.filter(id=p_id) if form.is_valid(): post = form.save(commit=False) #p_id =Product.objects.filter( id=p_id) #Modelform(initial={'p_id':p_id}) post.save() form = Modelform() the models: from django.db import models class Product(models.Model): title = models.CharField(max_length=50 , default='product title') price = models.CharField(max_length=10 , default= int('0')) delPrice = models.CharField(max_length=10, default=int('0')) img1 = models.ImageField(upload_to='product_gallry',default='img') img2 = models.ImageField(upload_to='product_gallry',default='img') img3 = models.ImageField(upload_to='product_gallry',default='img') description = models.TextField(max_length=5000 , default='description') Video_Link = models.TextField(max_length=5000 , default='Video_Link') def __unicode__(self): return u'%d' % self.id class Form (models.Model): Product = models.ForeignKey(Product,null=True, blank=True,on_delete=models.SET_NULL) name = models.CharField(max_length= 100 , default=None) number = models.CharField(max_length=13,default=None) adresse = models.CharField(max_length=500,default=None) city = models.CharField(max_length=20, default=None) the views: from .form import Modelform from .models import Product , Form from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.utils import timezone def p_page(request,p_id): obj = Product.objects.all() template = "index.html" product = get_object_or_404(obj,id=p_id) if request.method =='POST': form … -
Wagtail large files 403 when serve
In my Wagtail project I use custom document model with specified file upload path. I'm able to upload large files to specified directory, but, when I try do serve them,there is nginx 403 forbidden error. Tried a lot of different solutions from similar questions, but nothing helped :( -
django - database - from sqlite to postgres, not fully migrated, lacking language support?
I just deployed my very first django project, and I am trying to use pgloader v3.5 to migrate some important data from sqlite3 to postgres. It's successful, well, semi-successful since the data written in English are migrated whereas the data written in Russian (Cyrillic) aren't. Tried: Then, I tried a generic way - dump a datadump.json file of db.sqlite3 and python manage.py loaddata datadump.json, then the error: django.db.utils.DataError: Problem installing fixture '/home/user/project/datadump.json': Could not load boutique.Category(pk=1): character with byte sequence 0xd0 0x90 in encoding "UTF8" has no equivalent in encoding "LATIN1" datadump.json Then, I checked the datadump.json file: [{"model": "boutique.category", "pk": 1, "fields": {"gender": 1, "name": "\u0410\u043a\u0441\u0435\u0441\u0441\u0443\u0430\u0440\u044b", "description": "", "uploaded_date": "2020-03-02T08:20:49.786Z"}}, ... checked I checked the data in db.sqlite3 is intact, and data (mainly strings) in Russian aren't transferred in the new postgres database. system Ubuntu 18, bionic django 3.0.3 Question: I think the question is how to load/convert non-English json data? Not sure where to start to solve the problem. Thanks in advance! -
Django Heroku Scheduler once a week
I've set up a Heroku Scheduler for my Django app and it works great as a daily process. This is the command I insert in the scheduler to run the job: $ python manage.py update_db I want it to run only once a week. I researched and found a bunch of posts including - How can I schedule a 'weekly' job on Heroku? if [ "$(date +%u)" = 1 ]; then MY_COMMAND; fi How do I combine MY_COMMAND with my command above? I tried replacing it directly but it doesn't work. The job is run daily, but the function is not executed. Thanks -
How to create multidimensional array in python from list?
I have a list containing elements like list1 = [['Test Name', 'Results', 'Units', 'Bio. Ref. Interval'], ['Cholesterol, Total', '243.00', 'mg/dL', '<200.00'], ['Triglycerides', '365.00', 'mg/dL', '<150.00'], ['HDL Cholesterol', '48.56', 'mg/dL', '>50.00'], ['LDL Cholesterol, Calculated', '121.44', 'mg/dL', '<100.00'], ['VLDL Cholesterol, Calculated *', '73.00', 'mg/dL', '<30.00'], ['Non-HDL Cholesterol', '194', 'mg/dL', '<130']] I want to use list1[0] that is, ['Test Name', 'Results', 'Units', 'Bio. Ref. Interval'] to make it as key and want output something like the following multidimensional dictionary. { Testname : 'Cholesterol, Total' { Result : '243.00', Units : 'mg/dL', Bio. Ref. Interval : '<200.00' },.... .... { Testname : 'Non-HDL Cholesterol' { Result : '194', Units : 'mg/dL', Bio. Ref. Interval : '<130'}} } I'm newbie to python. Help out please. -
pythonanywhere refused to connect while serving PDFs
enter image description here When I am serving pdfs through my backend written in Django pythonanywhere to my frontend website written in react, I am getting this error yashshah2820.pythonanywhere.com refused to connect. code in models.py name = models.CharField(max_length=20, blank=True) pdf = models.FileField(upload_to="pdfs", blank=True) def __str__(self): return self.name code in settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # for media under development MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
django data in form only appear after refresh
I am using custom user authentication for verifying user. I have table named voter and I am tacking username and password via from and matching that with username and password of table if it match user will be logged in and allowed them to pass to next page which contain form. In that form I initiated data but it will not appear automatically it will appear only when i refresh the page code of my files is bellow (for some big file only relevant code is included that's why it is partial) model.py (partial) class Voter(models.Model): serial_voter_id = models.AutoField(primary_key=True) voter_id = models.CharField(unique=True, max_length=10) voter_name = models.CharField(max_length=255) voter_constituency = models.ForeignKey(Constituency, models.DO_NOTHING, blank=True, null=True) username = models.CharField(unique=True, max_length=32) password = models.TextField() voter_address = models.CharField(max_length=255, blank=True, null=True) area = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=10, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) adhar_no = models.BigIntegerField(unique=True) birth_date = models.DateField() age = models.IntegerField() fingerprint = models.TextField(blank=True, null=True) authenticity = models.CharField(max_length=3, blank=True, null=True) wallet_id = models.TextField() class Meta: managed = False db_table = 'voter' forms.py from django import forms from .models import Voter class VoterForm(forms.ModelForm): class Meta: model = Voter fields = [ 'serial_voter_id', 'voter_id', 'voter_name', 'voter_constituency', 'username', 'voter_address', 'area', 'city', 'pincode', 'adhar_no', 'birth_date', 'age', 'authenticity', 'wallet_id' … -
Translate this linux script command to windows commands
I need to create a .bat file script to run python manage.py collectstatic --noinput Below is the bash script.. i need to to work on windows.. it cd in folder named chefables, portal is application name #! /bin/bash cd chefables rm -rf static/ rm -rf assets/portal/ python manage.py assets build cp -R ./assets/portal/* ./portal/static/portal/ python manage.py collectstatic --noinput -
users.models.Profile.user.RelatedObjectDoesNotExist: Profile has no user
I am designing a website to take in and store a users information under a profile. The main issue I am running into seems to be between the profile and user relationship. When I try and delete empty profiles from the admin page it gives me this error: (py3) (base) Ethans-MBP-2:opinions_app ethanjay$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 05, 2020 - 00:09:33 Django version 2.2.10, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [05/Mar/2020 00:09:42] "GET / HTTP/1.1" 200 3142 Not Found: /favicon.ico [05/Mar/2020 00:09:42] "GET /favicon.ico HTTP/1.1" 404 4608 [05/Mar/2020 00:09:46] "GET /admin/ HTTP/1.1" 200 8342 [05/Mar/2020 00:09:47] "GET /admin/ HTTP/1.1" 200 8342 [05/Mar/2020 00:09:50] "GET /admin/users/profile/ HTTP/1.1" 200 6300 [05/Mar/2020 00:09:50] "GET /admin/jsi18n/ HTTP/1.1" 200 3223 Internal Server Error: /admin/users/profile/ Traceback (most recent call last): File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, … -
filtering Django models by JSONField's date attribute when less that or greater then criteria
I have run into a situation where I have a JSONField as one of my model fields (running Postgres as DB). Json stored in DB looks something like this: {"date": "2020-06-06", "reason": "test reason"} I would like to write a filter which would get me all rows where date is less than today. I'm using Q object to setup my filter, but read somewhere that such lte and gte queries aren't supported yet. ex: query = Q(my_json_field__date__lt=today) &= Q(another_field=some_value) MyModel.objects.filter(query) Is there anyway to get around that limitation and may be combine raw sql with the other Q objects? There are several more Q objects in that query, so I don't want to drop to a complete SQL just yet if possible -
What is the best way to download log file (large text file) from server service
In my production have folder to store the log file. I want to make the html page to download 'log file' (large .txt file, around 1.5 gb/file) from server to client computer using Django (python) views. What is the best solution to do that (no lose data in downloaded file, good performance) now i use this code but the size of downloaded file is less than the original file in the server :C with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response -
How to use Customize Model extends from User Model in Django?
I'm new to Django and I have a problem that makes me quite confused. I have a page when users click to change profile, the corresponding page shows up and lets users update their profile. Here is my model: from django.db import models import os from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Account(models.Model): user = models.ForeignKey(User, on_delete="CASCADE") phone = models.CharField(max_length=18) room = models.CharField(max_length=8) dob = models.DateField(default=timezone.datetime.now()) active = models.BooleanField(default=True) avatar = models.ImageField(upload_to='images/', default=os.path.join(settings.STATIC_ROOT, 'avatar.png')) def __str__(self): return self.user.username Here are my forms: class UserForm(forms.ModelForm): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) class Meta: model = User fields = ['first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Account fields = ['phone', 'room', 'dob', 'active', 'avatar'] And I have my views.py like this: def show_form(request): user_basic_info = UserForm(request.POST) form = ProfileForm(request.POST) if form.is_valid() and user_basic_info.is_valid(): form.save() and user_basic_info.save() messages.sucess(request, _('Your profile has been successfully updated')) redirect('my_account') else: UserForm() ProfileForm() context = { 'user_basic_info': user_basic_info, 'form': form, } return render(request, 'my_account.html', context) Here is my_account.html template: {% extends 'base.html' %} … -
choice: flask, django api render to user search
I'm totally new to Django and working on a project to query data from a MongoDB usually my project is meant for the data, but in order to give it a sense and let the user see how is it, I'm required to create an API to fetch data based on queries sent by the user. My questions are: is there any preexisted views in rest_framework that can satisfy my needs(All I want is let the user search the data, based on fields that he can enter) Or should I use react as a frontend to send queries? Another Q, would it be easy, how is this task on flask can it be done so quickly? Please, if something is not clear, just ask? -
django model form modelform multipart
I'm newbie to web development. started with Django since I already do Python for AI. I'm trying to use multipart to model. but it appears doesn't support. /models.py from django.db import models from django.forms import ModelForm class ImageData(models.Model): lot_number = models.CharField(max_length=100) images = models.FileField(widget=ClearableFileInput(attrs={'multiple': True})) class ImageDataForm(ModelForm): class Meta: model = ImageData fields = ('lot_number', 'images') It seems I need to use 'forms' https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/ than... do I need to write same code for forms? like /forms.py from django import forms class ImageData(forms.Form): lot_number = forms.CharField(max_length=100) images = models.FileField(widget=ClearableFileInput(attrs={'multiple': True})) guess must be a way to handle model and form in one code but could find it. -
Why is max_length being ignored in BinaryField?
I am attempting to create an invite system to register users, which stores a md5 hashsum based on the object's ID. Here's how my model is defined: class Invite(TimestampedModel): user = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.CASCADE) _code = models.BinaryField(max_length=16, unique=True) @classmethod def create(cls): invite = cls.objects.create() hash_obj = hashlib.md5() hash_obj.update(str(invite.id).encode('utf-8')) invite._code = hash_obj.digest() invite.save() return invite Thus when I call Invite.create(), I see a row in the database that has a _code that is 16 characters long (e.g. ��#�"��Zo�n�%��V). The problem arises, however, when I adjust max_length to 2. I expected Django to either throw an error or truncate the value to two bytes, but it did neither; I am still seeing 16 bytes in new rows. Yes, I ran makemigrations and migrate. What is going on here? This is a bit concerning that I can't limit the length at all. I assume it's defaulting to 50 but I have no idea why. Any thoughts are appreciated. BinaryField description here. -
How do I properly configure my app to use the Django phonenumber field module?
I'm using the Django 2.0, Python 3.7, and the Django PhoneNumber field -- https://github.com/stefanfoulis/django-phonenumber-field and have set up my model thusly ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have added this in my settings.py file ... PHONENUMBER_DB_FORMAT="RFC3966" However, when I submit my form using the following JSON ... { "name": "3999", "type": { "name": "Coworking Space" }, "address": { "street_number": "222", "route": "1212", "raw": "222 W. Merchandise Mart Plaza, Suite 1212", "formatted": "222 W. Merchandise Mart Plaza, Suite 1212", "latitude": 41.88802611, "longitude": -87.63612199, "locality": { "name": "Chicago", "postal_code": "60654", "state": 1 } }, "enabled": true, "phone": "303-234-1234", "email": null, "web_site": "http://www.1871.com/" } I get this error (a 400 response) ... {"phone":["The phone number entered is not valid."]} How else can I configure my server to recognize my phone number format (or do I need to change the format)? -
Django, Ajax and GET requests
There are plenty of similar questions here but I can't solve that problem I have. Situation is simple in theory - I send json to Django view, I get a json response. I did it with python, with Django, with REST framework. But with Ajax I can't do it, there's something with URLconf and ajax's relative url kind of stuff and I can't figure out what's wrong and how to make it work. I mean with some URL confs I can send a request with my chrome plugin and I have a response I need, but ajax is getting 404 with that confs. If I change it Django starts to return my html page instead of json response. What am I missing here? My ajax request: $.ajax({ url: 'ajax/apply_city/', type: 'GET', data: { 'city': obj.textContent }, dataType: 'json', success: function(data) { var str = ''; data.districts.forEach(function (district) { str += '<a class="dropdown-item" href="#" onclick="applyDistrict(this)">' + district + '</a>'; }); window.alert(str); document.getElementById("district_dropdown").innerHTML = str; }, }); urls that works with requests from everything but not ajax: re_path('^index/$', views.index, name='index'), re_path('^index/ajax/apply_city/', views.apply_city, name='apply_city'), Logs show Not Found: /index/... when ajax makes request and GET /index/... 404. I've seen that for ajax I … -
django drf big querys is very slow, how to optimize?
I'm new to python,and I'm doing my project with django, drf and postgreSQL,and my model has millions data,here is my model: class FetchdataByno(models.Model): bureau_name = models.CharField(max_length=16) station_name = models.CharField(max_length=20) board_train_code = models.CharField(max_length=10) start_station_name = models.CharField(max_length=16) end_station_name = models.CharField(max_length=16) corporation_name = models.CharField(max_length=20) sale_count = models.IntegerField(blank=True, null=True) price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price1 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price2 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price3 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price4 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price5 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) date = models.CharField(max_length=8, blank=True, null=True) class Meta: managed = False db_table = 'fetchdata_byno' and the station/bureau/traincode has three possible values, my api is: @api_view(['GET', 'POST']) def report_no_list(request, format=None): if request.method == 'GET': # now = datetime.datetime.now() # date_end = datetime.datetime(now.year, now.month, now.day, 0, 0) # date_start = date_end - datetime.timedelta(7) # start = time.time() date = str(request.GET.get('date', '')) date = re.sub('-', '', date) try: bureau = request.GET.get('stations', '') station = request.GET.get('saleStation','') traincode = request.GET.get('trains','') except: raise if bureau == '' and station == '' and traincode == '': data = get_train() snippets = data.all_data(date=date) #111 elif bureau !='' and station == '' and traincode == '': if bureau == '[]': data = get_train() snippets = data.all_data(date=date) #211 else: select_data … -
Weird Behaviour in Django Forms
I was working with Django Forms , I was doing custom validation for a field, but encountered weird problem. forms.py class RegistrationForm(forms.Form): username = forms.CharField(max_length=50) email = forms.EmailField(required=False) password = forms.CharField(max_length=50) password1 = forms.CharField(max_length=50) def clean_password(self): password = self.cleaned_data['password'] print(self.cleaned_data) # all fields are present except password1 in cleaned Data re_password = self.cleaned_data['password1'] #Gives Key Error here # Do something Here when I try to do some validation for password field in clean_password function, It gives key error for password1 field ,I don't get why that happens. I tried searching a lot but couldn't find anything relevant, about what causes this error.But then I tried making some change in code and It worked but I don't know why it worked. modified_forms.py class RegistrationForm(forms.Form): username = forms.CharField(max_length=50) email = forms.EmailField(required=False) password1 = forms.CharField(max_length=50) #swapped position password = forms.CharField(max_length=50) def clean_password(self): password = self.cleaned_data['password'] print(self.cleaned_data) # all fields are present in cleaned Data re_password = self.cleaned_data['password1'] #Doesn't Give Key Error here # Do something The changes I made was I just swapped the line position of password1 and password ,that is I just changed the order of password and password1. I changed order password1 at line of password, password at position where … -
How to concatenate django countries with primary key to create custom code
Below is my Participant class. I want to create a custom code that concatenates the country field with the auto-generated primary key. Whatever I've tried till now has failed, can anyone help me, please. The structure of the code is supposed to be the country first and the primary key second. I need this because when I print my report the code should be present in it class Participant(models.Model): first_name = models.CharField(max_length=100) last_Name = models.CharField(max_length=100) country = CountryField()`enter code here` trainer = models.CharField(choices = trainer, max_length=100, ) gender = models.CharField(choices= gender, max_length=50) title = models.CharField(choices= title_Choice, max_length=100, blank=True, null=True) date_of_birth = models.DateField(null=True, blank=True ) contact_address = models.CharField(max_length=1000, blank=True, null=True) work_phone = models.CharField(max_length = 30, blank=True, null=True) fax_number = models.CharField(max_length = 100, blank=True, null=True) home_phone = models.CharField(max_length=30, blank=True, null=True) email = models.EmailField #previous_employment = models.CharField(max_length=100, blank=True, null=True) organization = models.ManyToManyField(Organization, blank=True) #role = models.ForeignKey(Role, on_delete=models.CASCADE) education_level = models.CharField(choices = education_level_choice, max_length=100, blank=True, null=True) comments = models.CharField(max_length=1000, blank=True, null=True) -
Django Celery Beat
My times keep drifting with django-celery-beat, and seems to be related to the last_run_date being wrong. The time drift gets worse over time and seems to be related to Will resetting the last_run_at on every run fix this? >>> from django_celery_beat.models import PeriodicTask, PeriodicTasks >>> PeriodicTask.objects.all().update(last_run_at=None) >>> PeriodicTasks.changed() -
I need a button to redirect me to other page
I am trying to redirect to other page when clicking a button, i have been using href but this time it does not work. Html <div class="float-right"> <a href="edit/{{ created_items.id }}/" class="btn btn-outline-warning btn-sm" style="margin-right: 5px;" role="button">Edit</a> </div> views.py def edit(request, id): created_items = Create.objects.get(id=id) if request.method == "POST": new_item = request.POST.get("content") item_id = request.POST.get("id") Create.objects.filter(id = id).update(text = new_item) return HttpResponseRedirect("/") else: return render(request, 'my_app/edit.html', {"created_items": created_items}) urls.py path('edit/<int:id>/', views.edit, name='edit'),