Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
Can you have button inside a tag
So my problem is that I have those 2 buttons inside this card and when i click them it redirects to a link which the card itself is redirecting, so can i make this work? <a class="panel-product-div-a" href="{{ item.get_absolute_url }}"> <div style="color: {{ item.checks_color }}" class="p-checks"> <p>{{ item.checks|safe|linebreaks }}</p> </div> <span> <img {% if item.image %} src="{{ item.image.url }}" {% else %} nop {% endif %} alt="ehm.."> </span> <h1 class="mdh2">{{ item.title }}</h1> <div class="panel-button-div"> <button onclick="window.location.href='{{ item.get_add_to_cart_url }}'" class="btn btn-lg btn-primary panel-btn">To cart</button> <button onclick="window.location.href='{{ item.get_absolute_url }}'" class="btn btn-lg btn-light panel-btn">More info</button> </div> <div class="con-div"> {% if item.discount_price %} <h1 class="mdh1-discount"> {{ item.price }}€ </h1> <h1 class="mdh1"> {{ item.discount_price }}€ </h1> {% else %} <h1 class="mdh1"> {{ item.price }}€ </h1> {% endif %} </div> </a> -
Redis installation Windows 10
I am having an issue where I need a feature from a later redis version than the latest one for windows, is there a way I can install a newer version in windows without a vm? -
Django cached sessions: Is using Redis ok?
Django documentation on configuring cached sessions says this: You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments. It specifically, only mentions Memcached. Does this mean Redis is not a good choice? -
Why using filter() giveswhat I want, by get() raises an error
I created cusom QuerySet and Manager to serialize my data. class UpdateQuerySet(models.QuerySet): def serialize(self): return serialize("json", self) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Update(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = UpdateManager() Then, when I'am trying to get this data, it worked with this: json_data = Update.objects.filter(id=1).serialize() but raises AttributeError ('Update' object has no attribute 'serialize') with this: json_data = Update.objects.get(id=1).serialize() -
How to select students for teachers automatically in Django
This is my students class class Students(AbstractUser): mobile_number = models.TextField() My Teacher Class class Teacher(models.Model): students = models.TextField() How can associate 6 students to one teacher automatically in Django -
problem with django :__call__() missing 1 required keyword-only argument: 'manager'
so basically i am completing the project 2 of cs50 harvard course called commerce. i have a class named auction inside a model which has some fields and a user as mentioned in this picture.auction model i use django- admin interface to input the data. so when i try to add everything i get the error each time :"call() missing 1 required keyword-only argument: 'manager'" i need to solve this problem asap. -
What is the URL when I DELETE an object
I'm running a local server playing around with an API using Django. I have a model called 'Users' populated with a few objects, and am using DefaultRouter. I want to know what the URL would be if I were to DELETE a specific object from this model. For example, if I wanted to GET all of the users in this model, the URL would be: "localhost:8000/Users/". I found an explanation of this on the REST API website (below), however, I don't understand what any of the syntaxes means. What is {prefix}, {url_path}, {lookup} and [.format]? If anyone could provide an example of what this might be using a localhost that would be really helpful. Thanks -
Django Modal Close after submit
i have developed a simple form loading into bootstrap modal, the form gets rendered and everything is ok. however when i submit the form the modal does not submit and close as i get the Error of redirect is incorrect. i am using Bootstrap Modal without Jquery for ease of implementation, the form is loaded through the Detail View function and the submit is through another View function 'test1'. i get the following Error: NoReverseMatch at /split/3 Reverse for 'applicationdetail' with no arguments not found. 1 pattern(s) tried: ['applicationdetail/(?P[0-9]+)$'] below is my concept code : models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( max_length = 32 , null = False , blank = False ) class Score_Appeal(models.Model): appeal_score = models.ForeignKey(Startup, on_delete = models.CASCADE) appeal_evaluator = models.ForeignKey(User, on_delete = models.CASCADE) appeal = models.CharField ('Appeal', max_length = 100 , null = False , blank = False , choices = Choice.EVALUATION , default = '' ) appeal_comment = models.TextField(max_length = 100, blank = True) views.py: @login_required @inv_required def global_list(request): startup = Startup.objects.all() return render(request, 'inv_template/global_list.html', {'startup': startup}) @login_required @inv_required def applicationdetail(request, pk): obj = Startup.objects.filter(pk = pk) form = SplitForm1 … -
how to fix InternalError at /search when i search in Arabic for example using Django
Server error (500) when I try to search in any language other than English , I Make DEBUG = True and it show this error for me (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'") Exception Location: /home/example/virtualenv/django/3.7/lib/python3.7/site-packages/pymysql/err.py in raise_mysql_exception, line 109 and the problem i was search in Arabic word بحث in search box and when i do the search the URL show like this Request URL: https://example.com/search?q=%D8%B3%D8%B4%D9%8A%D8%B3%D9%8A&submit=Search Do not recognize Arabic letters or any language other than English -
Django group by one field and get max by other
I have this model: class Order(models.Model): symbol = models.CharField(max_length=30, default='') b_id = models.IntegerField(null = True, blank = True, unique=True) I use this for storing trade orders from exchange that I get from api the usual orders I get looks like this: #order1 (symbol='btc/usdt', b_id =1) #order2 (symbol ='btc/usdt, b_id=2) #order3 (symbol = 'eth/usdt', b_id=8) #order4 (symbol = 'eth/usdt', b_id=9) #b_id is unique id I get from exchange To get correct history of orders I need to get order with biggest b_id grouped by symbol so I need function that will return object something like: result = {'btc/usdt': 2, 'eth/usdt': 9} Right now I just use simple cycle: symbols=['btc/usdt', 'eth/usdt','link/usdt'] for symbol in symbols: last_order = Order.objects.filter(symbol=symbol).latest('b_id') since = last_order.b_id sinces[symbol]=since But it queries database to often. Any ideas how to reduce database calls?