Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
handle json data sent via vanillaJS post request in django
i am trying to send post request by vanilla Js to a view the post request should have the id of the image now i have tried to send it with many forms of data like using JSON.stringify and a plain text but anyway i can't get the value from the post request even when i am trying to print the post request itself , it give me this it's empty forever with all tries this is the code document.querySelector('#buttond').addEventListener('click',function(){ var xhttp = new XMLHttpRequest(); xhttp.readystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status == 200){ console.log(JSON.parse(xhttp.response)) } } xhttp.open('POST','{% url 'images:image_like' %}', true); xhttp.setRequestHeader("X-CSRFToken", '{{ csrf_token }}') xhttp.send(JSON.stringify({"id": "{{image.id}}"})) } ) if any one have an idea on handling vanilla Js requests inside django will help, i don't want to use jquery because it needs dependencies -
Django: Using ImageFields in other apps?
I have some apps where pictures are uploaded. Now that almost the same code is present multiple times in every app, I want the images to be loaded from an app named images. is it possible to connect the other apps so that they use the ImageFields of the app1[images] ShareImage class? If not, how can I use the method image_resize and the two @receiver functions so that they can be used by multiple apps, and I only have one code: I've tried heredity before, but I can't get away with it. i also tried to import the ImageFields into another class via Import. app1: import os from io import BytesIO from PIL import Image from django.db import models from django.dispatch import receiver from django.core.files.base import ContentFile from .storage import OverwriteStorage class ShareImage(models.Model): image = models.ImageField( upload_to='images/', verbose_name='Bild', storage=OverwriteStorage(), ) thumbnail = models.ImageField( upload_to='images/', editable=False, storage=OverwriteStorage(), ) def save(self, *args, **kwargs): if not os.path.exists(self.image.path) and not self.images_resize(): raise Exception('Error: Thumbnail not created') super(ShareImage, self).save(*args, **kwargs) def images_resize(self): size = (288, 162) image = Image.open(self.image) image.thumbnail(size, Image.ANTIALIAS) name, extension = os.path.splitext(self.image.name) # to prevent django from creating new folders incorrectly name = os.path.basename(name) extension = extension.lower() file_name = name + '_thumbnail' … -
Celery task fails midway while pulling data from a large database
I'm running a periodic task using celery in a django-rest application that pulls data from a large Postgres database with multiple tables, the task starts well and pulls some data for about 50 mins and then fails with this error client_idle_timeout server closed the connection unexpectedly, This probably means the server terminated abnormally before or while processing the request. What could be the issue causing this and how can I go about to fix it? -
Why can't simple web pages be displayed when used Django2.2?
This is the error it reported: 1:t = DEBUG_ENGINE.from_string(fh.read()) UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737 : illegal multibyte sequence 2:A server error occurred. Please contact the administrator. my solution And i had add (# -- coding: utf-8 --) in view.py and urls.py, but it still not worked. url.py(part) urlpatterns = [ path('admin/', admin.site.urls), path('', GeneView.as_view(), name='gene') ] view.py class GeneView(View): def get(self, request): render(request, "index.html") setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.gene_ex', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] result only the error of "A server error occurred. Please contact the administrator." on my curent page. -
how to display values from dictionary which contains list as value in django
i want to display records form dictionary which contains list as value in table format. my dictionary looks like this and i am passing this dictionary through view.py file as {'data':datas} enroll_number=[1,2,3] names = ['tom','mike','john'] total = [80,90,80] datas={ 'id':enroll_number, 'names':names, 'total':avgs, } in my HTML page my code is something like this: <table class="table table-striped"> <tr class="text-center"> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Total</th> </tr> {% for key, value_list in datas.items %} <tr> {% for value in value_list %} <td>{{value}}</td> {% endfor %} </tr> {% endfor %} </table> so i am getting output like this: Id Name Total 1 2 3 tom mike john 80 90 80 But i want output like this Id Name Total 1 tom 80 2 mike 90 3 john 80 -
How to allow user to hit urls in order
I have sample Django app with 3 layouts. For each layout one url is there. I want that the user should see layout-1 then layout-2 then layout-3 respectively. The problem I am facing is if the user directly hit the url for layout-2 or 3 he will get the corresponding layout. So how to restrict the user to not to see the layout-2 before he sees the layout-1. -
How to post array data through serializers?
I want to post some array data through serializer's create method. How do I get array data in serializer's create method? this is my result which gives error because or array's data. {"csrfmiddlewaretoken":"5JFiFURFu268oFpkdcP0U6s3gqqWMeV9","order_media":{"client_employee":"4","client":"64","narration":"Print ad","vendor":"68","total_amount":"6900.00","discount_rate_client":"10.00","discount_amount_client":"690.00","service_percentage":"10.00","service_amount":"690.00","client_vat":"1035.00","total_receivable":"7935.00"},"pub_date":"2019-04-03","particular":["Banner","Poster ","PLASTIC BANNER"],"inch_first":["2","5","4"],"inch_second":["3","5","4"],"size":["6.00","25.00","16.00"],"quantity":["5","10","5"],"rate":["10","20","20"]} print&production:554:17 error This is my model class RequestPrintProduction(models.Model): particular = models.CharField(max_length=255,null=True,blank=True) inch_first = models.CharField(max_length=45,null=True,blank=True) inch_second = models.CharField(max_length=45,null=True,blank=True) size = models.CharField(max_length=45,blank=True, null=True) quantity = models.CharField(max_length=45,null=True, blank=True) rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal(0.00), null=True, blank=True) pub_date = models.DateField(blank=True, null=True) vendor = models.ForeignKey(Party, blank=True, null=True) request_id = models.ForeignKey(Request, blank=True, null=True, related_name='requestprint') def __str__(self): return self.particular this is my api views: class PrintRequestAPIView(ListBulkCreateAPIView): serializer_class = RequestPrintSerializer this is my serializer: class RequestPrintSerializer(serializers.ModelSerializer): order_media = OrderMediaSerializer(required=False) class Meta: model = RequestPrintProduction fields = '__all__' def create(self, validated_data): service_request = Request() service_request.save() validated_data['request_id'] = service_request order_media = validated_data.pop('order_media') print(order_media) online_service_request = self.Meta.model.objects.create(**data) order_media['request_id'] = service_request order_media = OrderMedia.objects.create(**order_media) return online_service_request I expect to post array's data successfully. -
How to hide response in network (in browser) in Django
I have done one application in Django. In this application I'm getting data through ajax calls. For ajax call, in network I'm able see the response (in browser): Some suggestions I have seen in Google is to use {% block jquery_src %}{% endblock %} but it didn't work I want to hide that response in network. Is it possible in Django? If yes, how? -
How can I set my static files just can access by authenticated user in Django
I want to protect my static file from unauthorized user, How should I do in Django? Ex: /static/public/ : can access by anyone /static/private/: just fror authorized user -
django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'username'")
I have the following custom user model implementation in my Django application : users/models.py class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email: str, password: str, is_staff: bool, is_superuser: bool, **extra_fields): """Creates and saves a User with the given email and password. """ email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email: str, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email: str, password: str, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractUser, UUIDModel): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True, db_index=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' objects = UserManager() class Meta: verbose_name = 'user' verbose_name_plural = 'users' ordering = ('-date_joined', ) def get_full_name(self): return "{} {}".format(self.first_name, self.last_name) def get_short_name(self): return self.first_name def get_email(self): return self.email def __str__(self): return "{}".format(self.email) And my change form in admin.py looks like this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.forms import UserChangeForm as DjangoUserChangeForm from django.contrib.auth.forms import UserCreationForm as DjangoUserCreationForm from .models import User # Forms # ---------------------------------------------------------------------------- class MyUserCreationForm(DjangoUserCreationForm): class Meta: model = User fields = ("email",) class MyUserChangeForm(DjangoUserChangeForm): class Meta: model = User fields = … -
Add Literal Percent Sign (%) to my calculation inside raw query Django
I get an error when I add a percentage symbol in the query. "Exception Type:IndexError Exception Value:tuple index out of range". views.py class groupdatagercekzamanliveriListView(ListAPIView): query2 = gercekzamanlıveri.objects.raw("""SELECT 1 as id, CONCAT(ROUND((SUM(net_uretim_miktari)/SUM(teorik_uretim_miktari)::float*100)),'%') as tee, FROM tee_gercekzamanlıveri INNER JOIN tee_isyerleri ON tee_gercekzamanlıveri.isyeri_id= tee_isyerleri.id INNER JOIN tee_malzemeler ON tee_gercekzamanlıveri.malzeme_id= tee_malzemeler.id INNER JOIN tee_isyerimalzemebilgileri ON tee_isyerimalzemebilgileri.isyeri_id= tee_gercekzamanlıveri.isyeri_id AND tee_isyerimalzemebilgileri .malzeme_id = tee_gercekzamanlıveri.malzeme_id) as a GROUP BY isyeri_id""") queryset = query2 serializer_class = groupdatagercekzamanlıveriserializer serializer.py class groupdatagercekzamanlıveriserializer(serializers.Serializer): id = serializers.IntegerField() tee = serializers.CharField() When ı use "a" as string for "%" no problem; CONCAT(ROUND((SUM(net_uretim_miktari)/SUM(teorik_uretim_miktari)::float*100)),'a') as tee Result: "tee": 80a -
How can i receive variables from django-template?
I want to receive variable value in my python code from django-template. I have two button Yes and No. When I click one of buttons, my python code must receive this django variables and check True or False. But i can`t find information how to take these variables. {% with word=words|random %} <h1>{{ word }}</h1> <h1>{{ word.word_ru }}</h1> <form method="POST"> {% csrf_token %} <input type="submit" value="no" name="Answer" > <input type="submit" value="yes" name="Answer" > {% endwith %} -
url with AND giving 403 Forbidden error in nginx
my nginx setting is as follow: server { listen 80; server_name 172.16.0.150 ; charset utf-8; access_log /var/log/nginx/project.access.log; error_log /var/log/nginx/project.error.log info; client_max_body_size 1600M; location / { root /var/www/project_200; try_files $uri @wsgiapp; } location @wsgiapp { uwsgi_read_timeout 10800; uwsgi_pass unix:///tmp/project.sock; include /etc/nginx/uwsgi_params; } location /geoserver/ { proxy_set_header Host $host; proxy_read_timeout 600s; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://172.16.0.160:8080/geoserver/; } } when I hit the following request to the browser, it gives me 403 Forbidden error as below: request: http://172.16.0.150/geoserver/wfs/?service=WFS&request=GetFeature&typeName=geonode:new_lccs&startIndex=0&count=10&maxFeatures=10&sortBy=&version=1.0.0&outputFormat=json&exceptions=application/json&CQL_FILTER=LCCS_code%20IN%20(%27BH%27%2C%20%27BNl%27%2C%20%27Ba%27)%20AND%20BBOX(the_geom,80.57373046874999,17.560246503294877,103.271484375,30.675715404167747) response I came to figure out that, AND in my url is the problem for nginx. but could not get any solution. -
Select a Valid Choice. __ is not one of the available choices
models.py supplier_type_choices = (('transporter', 'Transporter'), ('broker', 'Broker'), ('fleet Owner', 'Fleet Owner')) class Supplier(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) trucktypes = models.ManyToManyField(Subject, related_name='interested_suppliers') supplier_type = models.CharField(choices=supplier_type_choices, default=0, max_length=100) supplier_name = models.CharField(max_length=100, default=0) forms.py Version 1 class SupplierTruckForm(forms.ModelForm): supplier_type = forms.ChoiceField(choices=supplier_type_choices) class Meta: model = Supplier fields = ( 'trucktypes', 'supplier_address', 'supplier_company_name', 'supplier_email', 'supplier_gst', 'supplier_name', 'supplier_origin_city', 'supplier_pan', 'supplier_service','supplier_type') widgets = {'trucktypes': forms.CheckboxSelectMultiple,'supplier_type':forms.CheckboxSelectMultiple} This is working perfectly but when I Change this choice Field to Multiple Check Box it throws the error as below: Can Someone explain what am I doing wrong here ? Here's the code of MultipleCheckBoxes: class SupplierTruckForm(forms.ModelForm): supplier_type = forms.CheckboxSelectMultiple(choices=supplier_type_choices) class Meta: model = Supplier fields = ( 'trucktypes', 'supplier_address', 'supplier_company_name', 'supplier_email', 'supplier_gst', 'supplier_name', 'supplier_origin_city', 'supplier_pan', 'supplier_service','supplier_type') widgets = {'trucktypes': forms.CheckboxSelectMultiple,'supplier_type':forms.CheckboxSelectMultiple} -
Django: change field from Int / Char to ForgeinKey
If I have the following model: Order: customer_id = models.CharField(max_length=256, null=True) Can I just a create an empty migration, with code to create a fk on the table and just change the code to: Order: customer = models.ForeignKey('Customer', on_delete=models.CASCADE, null=True, related_name='orders') Or do I really need a complex migration to save the data etc? -
How to throw exception if input params is invalid in Django Template
Is there any way to throw exception if template input params are invalid? In django old version, we can do it like code below. But how about the latest django version? There is an option to set string_if_invalid = 'string' but the only reason we need to throw exception for this is that we obviously do not expect mail server to send trash emails to customers. Thanks. # settings.py in old versions class InvalidVarException(object): def __mod__(self, missing): try: missing_str=unicode(missing) except: missing_str='Failed to create string representation' raise Exception('Unknown template variable %r %s' % (missing, missing_str)) def __contains__(self, search): if search=='%s': return True return False TEMPLATE_DEBUG=True TEMPLATE_STRING_IF_INVALID = InvalidVarException() -
Cannot assign "'5'": 'user.clearance' must be a "clearance" instance
I'm trying to do a register user page that makes use of Django and while adding a user, I encounter a problem that keeps returning as per the title of this article. Some of the works I have posted below. I would appreciate very much if there is anyone who can help me out and tell me what is wrong. this is my views.py if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') pwd = make_password(form.cleaned_data.get('password1')) mail = form.cleaned_data.get('userEmail') fname = form.cleaned_data.get('firstname') lname = form.cleaned_data.get('lastname') contact = form.cleaned_data.get('userContact') company = form.cleaned_data['company'] clearance = form.cleaned_data['clearance'] args = (username, pwd, mail,fname, lname, contact, company, clearance) db = MySQLdb.connect(host=var.host, user=var.user, password=var.password, db=var.db) cur = db.cursor() cur.callproc('sp_NewSignUp', args) db.commit() cur.close() db.close() messages.success(request, f'Account created for {username}!') return redirect('homepage') else: print("form error") else: form = UserRegisterForm() return render(request, 'main/register.html', {'form': form}) `````forms.py`````` db = MySQLdb.connect(host=var.host, user=var.user, password=var.password, db=var.db) cur = db.cursor() cur.callproc('sp_getClearanceRegister', args='') account_choice = [] for i in cur.fetchall(): account_choice.append(i) cur.nextset() user = 'root' companyid = '1' args = user, companyid cur.callproc('sp_getUserCompany', args) company_choice = [] for i in cur.fetchall(): company_choice.append(i) cur.close() db.close() class UserRegisterForm(UserCreationForm): userEmail = forms.EmailField(label='Email') firstname = forms.CharField(label='First Name') lastname = forms.CharField(label='Last Name') userContact = forms.IntegerField(label='Contact No.') … -
Want to programmatically add git for "media files" to track their history from views.py
I want to add git to media files stored by django in the media folder I looked at different modules of python to track the media files (gitpython, sh) but all of them give error "Permission denied". I think it is some environment problem. Help would be appreciated def simple_upload(request): username = None if request.method == "POST" and request.FILES["myfile"]: myfile = request.FILES["myfile"] if request.user.is_authenticated: username = request.user.username user_dir = "/media/" + username fs = FileSystemStorage(location="media") fs.save(myfile.name, myfile) if not is_git_repo(user_dir): sh.git.init(user_dir) rep = sh.git.bake(_cwd=user_dir) rep.init() rep.add(user_dir + "/" + myfile.name) rep.commit(m="hmmm") t = rep.head.commit.tree print(rep.git.diff(t)) return render(request, "simple_upload.html", {"uploaded_file_url": ""}) return render(request, "simple_upload.html") -
GIN Index is not being used when COALESCE is used
I am trying to implement a full text search in Django and PostgreSQL. Functionally it is working. But I have been having difficulty adding a GIN index to improve its performance. Here is how I created an index: CREATE INDEX make_model_gin_index ON public.vehicle USING gin (to_tsvector('english'::regconfig, (((make)::text || ' '::text) || (model)::text))) Now, when I query like this: select make, model from vehicle where to_tsvector('english', make || ' ' || model) @@ to_tsquery('mersedes') limit 1000; The index is being used: -> Bitmap Index Scan on make_model_gin_index (cost=0.00..721.10 rows=35847 width=0) However, if I add a COALESCE into the query like this: select make, model from vehicle where to_tsvector('english', coalesce(make, '') || ' ' || coalesce(model, '')) @@ to_tsquery('mersedes') limit 1000; the index is not used. The reason I want to add COALESCE is that I will be using Django's ORM and it will automatically add COALESCE into the query. What am I doing wrong? -
How can we join two tables in django?
Is it possible to join two models(tables) based on a common key(foreign key) in Django? If so, please explain it with an example. I went through the Django documentation for this. But I landed on how to perform raw SQL queries in django. Thanks -
How to filter List View queryset based on the user status
Hey i have a listView that outputs list of events created. How can i filter based on the super user? Basically i want the admin to see all the events: closed and open, but my users only see open one class EventView(ListView, LoginRequiredMixin): template_name = "chat/events.html" model = Event context_object_name = 'events' def get_queryset(self): kwargs = super(EventView, self).get_form_kwargs() print(kwargs) user_pk = self.kwargs['user_id'] user = User.objects.get(pk=user_pk) print(user) if user.is_superuser: queryset = Event.objects.all() return queryset else: queryset = Event.objects.filter(is_open=True) return queryset return queryset -
Overriding Form Constructor with Pre-existing Data Makes Form Un-editable
I want to override a form that I have created with existing data if the user's profile exists so that the user can edit the data they may have already submitted. My code overrides the the init method of the Form, but when the form is rendered the form has the text, but it not editable. I need it to be editable. The form code looks as below: class ProfileForm(forms.Form): aboutme = forms.CharField( widget=forms.Textarea ) aboutmeprivate = forms.BooleanField(required=False) interestsprivate = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(ProfileForm, self) self.aboutme = kwargs.pop('aboutme') self.aboutmeprivate = kwargs.pop('aboutmeprivate') self.interestsprivate = kwargs.pop('interestsprivate') The call looks like: form = ProfileForm(aboutme=exisitingprofile.aboutme, aboutmeprivate=exisitingprofile.aboutmeprivate, interestsprivate=exisitingprofile.interestsprivate) Can anyone advise? -
How to properly use dates in object filters
I'm using Django ORM to access database models, it works well when I use objects.all(), it returns all the objects in the database. But when I want to filter on a date I add a filter using the new date type it doesnt return anything, I get a blank QuerySet. After searching and trying different things for many hours I discovered object.filter(date__gte=date) works. For example: This works, I get all the records where date = today: today = date.today() Model.objects.filter(date__gte=today) These do not work, they return empty QuerySets: Model.objects.filter(date__contains=today) Model.objects.filter(date__startswith=today) Model.objects.filter(date__date=date.today())` My question is what am I doing wrong that one type of query works but not the other, when they should all return the same data? -
How to get all the choices of a choicefield when using django restframework on the frontend
I am using django restframework on the backend to create an API. I have a 'Post' model that stores text and also has a field 'privacy_settings'. When creating a new 'post' object on the frontend, if one of the values is a choicefield, then how can we retrieve all the choices for that field from the backend so the user can select and option? ONLYME = 'ME' FRIENDS = 'FR' PUBLIC = 'PU' POST_PRIVACY_CHOICES = ( (ONLYME, 'Onlyme'), (FRIENDS, 'Friends'), (PUBLIC, 'Public'), ) privacy_setting = models.CharField( max_length = 2, choices = POST_PRIVACY_CHOICES, default = ONLYME ) -
Validate file size for multiple files uploads
I have django inline to uploads files, so it can upload multiple files at same time. (one file for a one file field) And my nginx limits upload size to 20MB. Now I want to check the total size of all files, and give proper error massage if it exceeds 20MB before nginx does. Any helps? please.