Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi, I m learning the djano, py -Pands - The below code is working fine in python, how to pass parameter values from html
import pandas as pd import pandas_profiling read the file df = pd.read_csv('Dataprofile.csv') run the profile report profile = df.profile_report(title='Pandas Profiling Report') save the report as html file profile.to_file(output_file="pandas_profiling1.html") save the report as json file profile.to_file(output_file="pandas_profiling2.json") -
Django UUIDField docs say can be serialised but migrations mark it `serialize-False`
What causes Django's UUIDField type to be marked serialize=False? How can I specify that it should be True? The documentation for database migrations, under “Serializing values”, explicitly states that uuid.UUID instances can be serialised: Django can serialize the following: […] uuid.UUID instances That sounds good to me. So I define a model with a UUIDField primary key: import uuid from django.db import models class Lorem(models.Model): id = models.UUIDField( verbose_name='ID', default=uuid.uuid4, editable=False, serialize=True, primary_key=True) dolor = models.CharField([…]) Despite specifying serialize=True explicitly, the makemigrations management command produces this field, where all the arguments are the same except it has changed to serialize=False: […] migrations.CreateModel( name='Lorem', fields=[ ('id', models.UUIDField([…], primary_key=True, serialize=False, verbose_name='ID')), ('dolor', models.CharField([…])), ], ) […] What is causing the makemigrations command to insist that the UUIDField should not be serialized? How can I get it to work the way the documentation for “Seralizing values” describes, and serialize=True? -
Django filter liked Posts by User
Post model class Post(models.Model): likes = models.ManyToManyField(User, related_name="liked_by", blank=True) I am trying to query all posts that are liked by a particular user but I couldn't find the right __ query for it. This is the query I'm trying to make. Post.objects.filter(likes__liked_by=User.objects.get(pk=1)) How can I achieve that? -
What is the correct format for adding extra parameters in action decorator?
I'm trying to pass an extra parameter to my custom ModelViewSet method: urls.py: router.register(r'mail_template', MailTemplateViewSet) view: @action(detail=False, methods=['GET'], url_path='get_template/(?P<slug>[\w-]+)') def get_template(self, request, slug=None): I also tried: @action(detail=False, methods=['GET'], url_path='mail_template/get_template/(?P<slug>[\w-]+)') @action(detail=False, methods=['GET'], url_path='dashboard/mail_template/get_template/(?P<slug>[\w-]+)') test call: self.client.get('/dashboard/mail_template/get_template/test-template') However, the path to get_template is not being found. If I remove the 'url_path', I can reach the method. Am I formatting the url_path correctly? -
I have an issue with the changeStock method of a Product class in views.py in Django
I am doing a Product class in Django for fun and I have ran into a problem regarding changing the Product's (the model name) regarding its variable qtyOnHand, which is used to check to see how much of that product is in stock. The goal is to change the product's qtyOnHand by a specified amount using the changeStock method and redirect to the home page where the updated qtyOnHand will be stored. The amount can be negative if taking out stock, and +ve if receiving stock. The error I got when typing in the URL http://127.0.0.1:8000/products/1/changeStock/2 is unsupported operand types for +: int and str, which was Here's my code for the changeStock method in the views.py. The comments there are to guide my approach to the problem. Change the stock of a specific product by the specified amount. A -ve number means that you are taking out product, while a +ve one means you are receiving that product. def changeStock(request, pk, amount): # We need the id of a specific product, plus we have to check if it's not found. product = get_object_or_404(Product, pk=pk) # Then we have to update its qtyOnHand. product.qtyOnHand = product.qtyOnHand + amount -> error … -
Trying to deploy Django on SiteGround
I am trying to deploy a Django app on Siteground through SSH. I have transferred all the files through Filezilla. Every thing is setup. I have developed several apps on AWS using ubuntu. But in siteground Fedora OS is provided in SSH, I am not familiar with that much. I can't have superuser privileges. Running my Django server on port 8000: python manage.py runserver 0.0.0.0:8000 Host name is already added in ALLOWED_HOST of setting.py: ALLOWED_HOSTS = ["himeshp7.sg-host.com","*"] Server is running in SSH, but I am unable to open my web app on browser. In AWS we get option to enable ports in Security Groups, but I couldn't find anything like that on Siteground, I also talked with customer care but they are telling to upgrade, I still doubt that if it will work or not after that as I couldn't find anything proper for deploying Django on Siteground. -
How to deploy Django REST framework on Windows server
What's a good/easy way to deploy a Django REST project on Windows server (2019)? I've been searching for a guide but can't seem to find anything on REST, just regular Django. Nginx and Waitress seems like the way to go for Django but there's no project.wsgi in a DRF project so I get stuck there. Could anyone steer me in the right direction? -
How to save equations and formulas in Django Database?
Working on a Project I need to save different articles which contains formulas and equations, Django core models support TextField which does not seems to save equations, they are all stored as plain text. I also tried adding CKEDITOR to my project but no chances on that too. so the question is : How can I save texts containing formulas and equations in my SQLite DB? -
Getting error while reloading webapp in pythonanywhere
I am trying to write my first django app on pythonanywhere with the help of django documentation(Part 1). All the things are successful until I try to add a new file named urls.py as mentioned in Documentation, I can't reload my webapp after that..I am getting following error: "Your webapp took a long time to reload. It probably reloaded, but we were unable to check it". There is no error in my code as I have checked through this command "python3 manage.py check". As a beginner, Any help would be appreciated. I am also following the tutorial "Django for everybody" on coursera and followed the instructor step by step, But I can't get rid of this error -
Django: can't optimize N+1 with image.url field
I'm trying to optimize a Django app. I iterate over and join some related info in a json I'll send to the template. I already know about select_related or prefetch_related, but when you try to get the url of an image field it seems to query again because url is not actually a value in the model but a property. This makes my view too slow because I need many images. How can I avoid this pseudo N+1 problem? Example model Obvioulsy this is not all my real code, but I just want to illustrate the process. class example_model(models.Model): name = models.CharField(max_length=200, help_text="", blank=True, null=True) logo = models.ImageField(upload_to='', default="", blank=True, null=True) def __str__(self): return str(self.name) View result_list = [] for x in example_model: result_list.append({'name': x.name, 'image': x.logo.url}) -
How do i filter an obj belong to its group using django
I have this two models Product and ProductCategory Model, how do I group the product according to their category? Product Data product = {"Apple", "Pineapple", "Pork", "Chicken", "beans", "tomato"} Category Data category = {"Fruits", "Meat", "Vegetables"} Expected Result Fruits = {"Apple", "Pineapple"} Meat = {"Pork", "Chicken"} Vegetables = {"beans", "tomato"} this is my views.py def Homepage(request): category = ProductCategory.objects.all() products = Product.objects.filter(category__in=category.values_list('id')) return render(request, 'customAdmin/Homepage.html', {"products":products, "category":category}) this is my models.py class ProductCategory(models.Model): category = models.CharField(max_length=500) def __str__(self): suser = '{0.category}' return suser.format(self) class Product(models.Model): product = models.CharField(max_length=500) category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Category") def __str__(self): suser = '{0.product}' return suser.format(self) this is the result ive got <QuerySet [<Product: Apple>, <Product: Chicken>, <Product: cabbage>, <Product: ampalaya>, <Product: okra>]> -
Setting up Heroku addons as a student with no credit card
I am a student and I don't have a credit card and I am using Heroku to deploy my Django application. Files uploaded onto Heroku are not saved so I intended to use Cloudinary to store media files uploaded via my Django app. Is there no other way to set up Cloudinary to work on Heroku without using the addon which requires verifying my account with credit card info? I have tried Googling but all the results I found are people who requires more than 5 apps running and suggested solution was to create multiple accounts, so I am kind of at a loss. Thanks in advanced, to those who could answer my question. -
Django Multiple search views in one html search field + dropdown
I hope you're well. I've different search views : #search profile in user app ({% url 'user:userprofile_result' %}) @method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch") class UserProfileResultsView(ListView): model = UserProfile template_name = 'search_results_user.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) ) return object_list #search article in nutriscore app ({% url 'search_results' %}) class SearchResultsView(ListView): model = Post template_name = 'search_results.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = Post.objects.filter( Q(title__icontains=query) | Q(slug__icontains=query) ) return object_list ... I'd like to have all this searchs in one form with Dropdown (something like that): Anyone has an idea about it? Thanks in advance, <form action="" method="get" class="div-only-desk mr-2 my-auto w-100 order-1"> <div class="input-group"> <div class="dropdown"> <button class="bouton-catego dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Looking for... </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> User Profile Article ... </div> </div> <input class="form-control border border-right-0h" name="q" type="text" value="{% if query %} {{ query }} {% endif %}" aria-label="Search"> </div> </form> -
Django - Create href elements from a comma seperated list
each of my post elements has multiple tags which are separated by a comma like so: Tags: Peter Silver, Philippa, Politics, Sweden, October Now I want a href element to my search function for every tag in that "list" so basically after each "," symbol. The problem now is that my tags are just a single CharField based String and not some kind of special field that could maybe manage this problem: tag = models.CharField(verbose_name="Tags", max_length=70, blank=False) Can smb. help me out here? Thanks for reading -
Accessing cookies set at django backend server from the React client server
My frontend and the backend are decoupled and client runs on localhost:3000 and the backend runs at localhost:8000. I have the csrf and the refresh tokens which are 'Httponly' and I set them as cookies on the server side. Now I need those cookies on the client side. This is the react code that I have written : fetch('http://localhost:8000/api/Acutes/SignIn/', { method: 'POST', headers: { 'Content-Type': 'application/json', withCredentials: true }, body: JSON.stringify(values) }) .then(data => data.json()) .then(data =>{ console.log(data) }) .catch(error =>{ console.error(error); }) Django settings CORS_ORIGIN_WHITELIST = [ "http://localhost:9001", "http://localhost:3000" ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] The error that seems to be there upon using this is as follows. Access to fetch at 'http://localhost:8000/api/Acutes/SignIn/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field withcredentials is not allowed by Access-Control-Allow-Headers in preflight response. How should i deal with this error and get my cookies onto the client side?TIA -
How to implement UDP server and Django app so that data send from UDP server update Django models
In the following task you need to implement simple UDP protocol. Write UDP server that sends a binary message with the following params. username (max of 32 bytes) username_length (1 byte) password (max of 32 bytes) password_length (1 byte) uuid (max of 16 bytes) Write a client to receive the messages and do the following tasks. Parse the message to python object. save message log in Django DB Model. create a query to receive the last 25 message in the last 30 min. Bonus task: Send in receive messages in simple queue. Min Requirements: Python 3.8 Django. GraphQL and graphene. -
binascii.Error: Incorrect padding in python django
I am trying to save the base64 encoded image in the django rest framework. First of all, we make a code to insert the base64 encoded image into the imagefield and test it, and the following error appears. binascii.Error: Incorrect padding What I don't understand is that I've used the same code before and there was no such error. Can you help me? Here is my code. serializers.py from rest_framework import serializers from .models import post, comment class Base64ImageField (serializers.ImageField) : def to_internal_value (self, data) : from django.core.files.base import ContentFile import base64 import six import uuid if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data : header, data = data.split(';base64,') try : decoded_file = base64.b64decode(data) except TypeError : self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension (self, file_name, decoded_file) : import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension class commentSerializer (serializers.ModelSerializer) : class Meta : model = comment fields = '__all__' class postSerializer (serializers.ModelSerializer) : author = serializers.CharField(source='author.username', read_only=True) image1 = Base64ImageField(use_url=True) image2 = Base64ImageField(use_url=True) image3 = Base64ImageField(use_url=True) image4 = Base64ImageField(use_url=True) image5 = … -
Different between limit_choices_to and queryset in Django form
I want to use ModelChoiceField in my Form. I familiar with queryset argument of this field, but I don't any clue about limit_choices_to and different between them. So, what is main different between queryset and limit_choice_to in Django Form? -
How do I save PhoneNumberField data to database?
My forms.py file class CreateUserForm(UserCreationForm): phone=PhoneNumberField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'phone'] widgets={ 'username':forms.TextInput(attrs={'placeholder':"Username"}), 'email':forms.TextInput(attrs={'placeholder':"Email Address"}), 'password1': forms.PasswordInput(attrs={'placeholder': 'Your Password'}), 'password2': forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), 'phone':PhoneNumberField(), } My models.py file class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) def create_profile(sender, **kwargs): if kwargs['created']: user_profile=CustomerReg.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) My views.py file def registerPage(request): if request.user.is_authenticated: return redirect('form') else: form=CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if(form.is_valid()): form.save() user=form.cleaned_data.get('username') phone=form.cleaned_data.get('phone') user.User.phone_number=phone user.save() messages.success(request, 'Account created for '+ user) return redirect('login') context = {'form': form} return render(request, 'customer/register.html', context) Upon clicking the register page an error is displayed AttributeError at /register/ 'str' object has no attribute 'User' So is there no way I can save the data from my form and hence I would have to make new Custom User Model to save phone number of a user on register page? -
NOT NULL constraint failed: blog_userpost.user_id
Im trying to create a way for people to post their ideas but is giving me this error: NOT NULL constraint failed: blog_userpost.user_id. I want the user to have to be registered and login in order to make/read the posts. views.py: #create view @login_required(login_url='login') def userposts_create_view(request): form= UserPostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form = form.save() form.save() return HttpResponseRedirect("/Blog/posts/") context= {'form': form, } return render(request, 'posts/userposts-create-view.html', context) #list view @login_required(login_url='login') def userposts_list_view(request): allposts= UserPost.objects.all() context= {'allposts': allposts, } return render(request, 'posts/userposts-list-view.html', context) #detail view @login_required(login_url='login') def userposts_detail_view(request, url=None): post= get_object_or_404(UserPost, url=url) context= {'post': post, } return render(request, 'posts/userposts-detail-view.html', context) models.py This are the categories I want the post to have, I can 'create' the post but whenever I submit it gives me the error. User= settings.AUTH_USER_MODEL class UserPost(models.Model): user= models.ForeignKey(User, null=False,editable=False, verbose_name='Usuario', on_delete=models.CASCADE) title= models.CharField(max_length=500) content= models.TextField() categories = models.ManyToManyField(Category, verbose_name='Categorias', blank=True,related_name="articles") created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ') updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ') def save(self, *args, **kwargs): super(UserPost, self).save(*args, **kwargs) forms.py from django import forms from .models import UserPost class UserPostForm(forms.ModelForm): class Meta: model= UserPost fields= ["title", "content","categories"] -
CommandError: You appear not to have the 'psql' program installed or on your path. MacOS Catalina
I am working on a django web app and trying to connect and verify connection to a PostgreSQL database I had created to store webscraped data I'd like the webapp to be able to query. I have correctly set up the database in Settings.py When I enter python manage.py dbshell my Atom terminal returns CommandError: You appear not to have the 'psql' program installed or on your path. As per instructions elsewhere, I tried running this is iTerm2 export PATH="/Applications/Postgres.app/Contents/Versions/12.3/bin:$PATH" but nothing seemed to change and I am still receiving the error. I have PSQL 12.3 installed on my computer through postgress.app and it is functioning normally. -
not showing the server address while using django
while running python manage.py runserver , getting this error as given below. using pycharm (venv) C:\Users\User\PycharmProjects\PyShop>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\template\backends\d jango.py", line 121, in get_package_libraries module = import_module(entry[1]) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", li ne 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\contrib\admin\templ atetags\admin_static.py", line 5, in <module> from django.utils.deprecation import RemovedInDjango30Warning ImportError: cannot import name 'RemovedInDjango30Warning' from 'django.utils.deprecation' (C: \Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\deprecation.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, i n _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, i n run self._target(*self._args, **self._kwargs) File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\utils\autoreload.py ", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\com mands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\User\PycharmProjects\PyShop\venv\lib\site-packages\django\core\management\bas e.py", line 396, in check databases=databases, File … -
Template tag has no effect Django
I am trying to modify django-better-admin-arrayfield a little, so the ADD button will be on the admin page only. However, a very basic template tag doesn't seem to work. Am I missing something or there is a reason for it? {% load static %} {% load i18n %} {% spaceless %} <div class="dynamic-array-widget"> <ul> {% for subwidget in widget.subwidgets %} <li class="array-item" {% if widget.is_none %}data-isNone="true" style="display: none"{% endif %}> {% with widget=subwidget %} {% include widget.template_name %} {% endwith %} <div class="remove"><div class="remove_sign"></div></div> </li> {% endfor %} </ul> {% if 'admin' in request.path%} #MY TEMPLATE TAG <div><button type="button" class="add-array-item">{% trans "Add" %}</button></div> {% endif %} </div> {% endspaceless %} -
Django App Served in EBS (Elastic Beanstalk Service) using Traefik and Docker error: 502 Bad Gateway
I am practicing in deploying a multi-container application using Django Cookiecutter (https://github.com/pydanny/cookiecutter-django) with TravisCI, Docker, and also using Traefik as router. I already successfully deployed my application to an EBS (Elastic Beanstalk Service) application in AWS with a green health check. The only problem I am currently encountering is if I try to access the hostname or domain that I assigned, I am getting a 502 bad gateway error. My suspicion is that there is a misconfiguration in either my traefik.yml file or my port mappings in Dockerrunaws.json file. Please help me find the error. Here are the configurations: Please note that "myhostname.com" refers to my actual dns hostname and "myusername" refers to my actual docker hub username. Also, I used Route 53 to map my hostname with an A name record to my ELB instance. traefik.yml: log: level: INFO entryPoints: web: # http address: ":80" flower: address: ":5555" http: routers: web-router: rule: "Host(`myhostname.com`)" entryPoints: - web middlewares: - csrf service: django flower-router: rule: "Host(`myhostname.com`)" entryPoints: - flower service: flower middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 flower: loadBalancer: servers: - url: http://flower:5555 providers: # https://docs.traefik.io/master/providers/file/ file: filename: /etc/traefik/traefik.yml watch: true … -
Got AttributeError when attempting to get a value for field `choice_option_set` on serializer `QuestionSerializer`
I got this error when trying to create a new django models into a database AttributeError at /api/problemset/create Got AttributeError when attempting to get a value for field `choice_option_set` on serializer `QuestionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Question` instance. Original exception text was: 'Question' object has no attribute 'choice_option_set'. Here's my django models class Problemset(BaseModel): class ProblemsetType(models.Choices): Exam = 'Exam' Assignment = 'Assignment' topic = models.CharField(max_length=25) classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() created_by = models.ForeignKey(UserAccount, on_delete=models.DO_NOTHING) subject = models.ForeignKey(Subject, on_delete=models.DO_NOTHING) type = models.CharField(max_length=10, choices=ProblemsetType.choices) def __str__(self): return str(self.classroom) + " " + str(self.subject) class Question(BaseModel): class QuestionType(models.Choices): Multiple_Choices = 'Multiple Choices' Short_Answer = 'Short Answer' Essay = 'Essay' question_no = models.IntegerField() question_type = models.CharField( max_length=20, choices=QuestionType.choices, default='Multiple Choices') body = models.TextField() max_points = models.IntegerField(null=True, blank=True) answer_key = models.TextField(null=True, blank=True) problemset = models.ForeignKey(Problemset, on_delete=models.CASCADE) def __str__(self): return str(self.question_no) + " " + str(self.body) class ChoiceOption(BaseModel): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=512) def __str__(self): return self.text and here's my serializer class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = ChoiceOption fields = ('text',) class QuestionSerializer(serializers.ModelSerializer): choice_option_set = ChoiceSerializer(many=True) class Meta: model = Question fields = ('question_no', 'question_type', 'body', 'max_points', …