Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Anyone can you help about CSP in ckeditor in djang
enter image description here Help me about this CSP -
in django data base stored image not display in application and i have no error while running the code
I have no error while run the code the images will stored database but it will not display in webpage ,I post my source code here my application page code {% extends 'shop/layouts/main.html' %} {% block title %} registration | onlineshopping {% endblock title %} {% block content %} <section class="py-5 text-center container" style="margin-top: 70px;"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <h1 class="fw-light">Bestsellers</h1> <p class="lead text-muted">Our most popular products based on sales.updated honourly</p> <p> <a href="#" class="btn btn-primary my-2">Already User</a> <a href="#" class="btn btn-secondary my-2">Register</a> </p> </div> </div> </section> <section class="bg-light py-4 my-5"> <div class="container"> <div class="row"> <div class="col-12"> <h4 class="mb-3">Categories</h4> <hr style="border-color:#b8bfc2"> </div> {% for item in category %} <div class="col-md-4 col-lg-3"> <div class="card my-3"> <img src="{{item.image.url}}" class="card-image-top" alt="Categories"> <div class="card-body"> <h5 class="card-title text-primary">{{item.name}}</h5> <p class="card-text">{{ item.description }}</p> <a href="" class="btn btn-primary btn-sm">View Details</a> </div> </div> </div> {% endfor %} </div> </div> </section> {% endblock content %} models.pycode from django.db import models import datetime import os def getFileName(request,filename): now_time=datetime.datetime.now().strftime("%Y%m%d%H:%M:%S") new_filename="%s%s"%(now_time,filename) return os.path.join('uploads/',new_filename) # Create your models here. class Catagory(models.Model): name=models.CharField(max_length=150,null=False,blank=False) image=models.ImageField(upload_to=getFileName,null=True,blank=True) description=models.TextField(max_length=500,null=False,blank=False) status=models.BooleanField(default=False,help_text="0-show,1-Hidden") created_at=models.DateTimeField(auto_now_add=True) def __str__(self) : return self.name class Product(models.Model): catagory=models.ForeignKey(Catagory,on_delete=models.CASCADE) name=models.CharField(max_length=150,null=False,blank=False) vendor=models.CharField(max_length=150,null=False,blank=False) product_image=models.ImageField(upload_to=getFileName,null=True,blank=True) quantity=models.IntegerField(null=False,blank=False) original_price=models.FloatField(null=False,blank=False) selling_price=models.FloatField(null=False,blank=False) description=models.TextField(max_length=500,null=False,blank=False) status=models.BooleanField(default=False,help_text="0-show,1-Hidden") trending=models.BooleanField(default=False,help_text="0-default,1-Trending") created_at=models.DateTimeField(auto_now_add=True) def __str__(self) : return self.name setting.py … -
How to Filter Children Model In Django RestFramework
I have been trying to build an api to filter out country_name. How can i filter multiple data from multiple model connected to each other through Foreign key. when I query url https://www.localhost:8000/api/country/?country_name={}. It give me exact country that i want. { "count": 1, "next": null, "previous": null, "results": [ { "id": "7f0cf3bd-0a67-4c57-b192-5cf6cba8b203", "country_name": "Usa", "state": [ { "id": "6a070973-11bd-4f9e-9bbf-652f171b028b", "state_name": "Alaska" }, { "id": "6ed508ce-5ea0-441b-a02e-22cc9b70e6ae", "state_name": "Texsas" } ] } ] } I want same for state_name inside country_name if there are multiple states. How can I do it. Models.py from django.db import models import uuid # create your models here # Forename Model class COUNTRY(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) country_name = models.CharField(max_length=100, default=None) def __str__(self): return self.country_name class STATE(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) state_name = models.CharField(max_length=100, default=None) # PARENT_COUNTRY parent_country = models.ForeignKey(COUNTRY, on_delete=models.PROTECT, related_name='state') def __str__(self): return self.state_name Serializer.py from rest_framework import serializers from .models import COUNTRY, STATE # Name Serializer class STATE_Serializer(serializers.ModelSerializer): class Meta: model = STATE fields = ["id", "state_name"] class COUNTRY_Serializer(serializers.ModelSerializer): state = STATE_Serializer(many=True, required=True) class Meta: model = COUNTRY fields = ["id", "country_name", "state"] Views.py from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from .serializers import COUNTRY_Serializer, from … -
How to test api with session in django
I am currently building an auth app that provides register, login, logout ... functionalities. Everything seems to work fine, however when I log the user in, I cannot logout, I get an Anonymous user error instead. After searching on the internet I came to the conclusion that it is not the best to build an api with sessions and instead to use tokens(JWT). With sessions I cannot test my API with tools like POSTMAN because that requires cookies (technically you can use cookies in POSTMAN though). Having said that, sessions seem to be more stable and secure so how would I go about testing my API using the sessions stored in the cookie? Thanks. -
Developing a web application with python
I would like to learn to write a web application using python. The application will write information into and retrieve data from a PostgreSQL database I will be hosting on a personal web URL. I would like to securely log into the application and select (or create a new) item/file to work on. The file will have a structure like an indented bill of material a user can dig down into if the data exists or can build if it does not. I am expecting to build the structure with Python classes, but I don't know where to start with building the GUI for the web browser. I would like to have a slick interface with a tree structure on the left of the screen I can expand and dig down or add items, and a form containing information on the right (or blank properties if the item is being added). Eventually I would like to show analysis and various other views of the data contained in the database including graphs and summary tabs. Would Django be the right tool to use to build the web app or Flask or is there something better I should spend my time learning. … -
How to order by queryset by Saturday to Sunday in django?
i want to order an attendance queryset by Saturday to Friday. how can i achieve it? class ReportsTogether(models.Model): user = models.ForeignKey(User,on_delete=CASCADE,verbose_name=_("Report For User")) user_log = models.ManyToManyField(UserTimeInOut,verbose_name=_("User Attendance")) user_break = models.ManyToManyField(UserBreak,verbose_name=_("User Break")) user_lunch = models.ManyToManyField(UserLunchBreak,verbose_name=_("User Lunch Break")) time = models.DateField(verbose_name=_("Date"),null=True) -
Django interal server error 500 while creating home page
Currently trying to set up a sign-up page, as well as the start of a project I am going to try to accomplish. But after adding in bootstrap (it seemed like might not have been) that I couldn't load the page, I had also added in a urls to my main/site directory as well. Let me know if I should include the html as well. App/ App\__init__.py analysis_app\asgi.py analysis_app\settings.py ... Main/ main\migrations main\templates main\__init__.py main\admin.py main\urls.py main\views.py .... Traceback: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'tuple' object has no attribute 'get' [11/Sep/2022 00:43:07] "GET / HTTP/1.1" 500 63663 App\urls.py: from django.contrib import admin from django.urls import path, include from main import views urlpatterns = [ path('admin/', admin.site.urls), #path('', views.home, name=""), path('', include('main.urls')), path('', include('django.contrib.auth.urls')), ] Some of the App/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'crispy_bootstrap5', 'main.apps.MainConfig', ] 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', ] ROOT_URLCONF = 'analysis_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['analysis_app/main/templates'], 'APP_DIRS': True, … -
Why for loop is not running in django template?
for loop is not running in django template. For loop is working in terminal but showing nothing in the template.. -
ugettext_lazy not working in model validator
I'm using ugettext_lazy in a model validator to return the proper message to the frontend with the right language but it is not working. from django.utils.translation import ugettext_lazy as _ class User(AbstractUser, BaseModel): mobile_number = models.CharField( 'Mobile Number', validators=[ RegexValidator( regex=r'^A Validator regex', message=_('Mobile Number is not Valid'), code='invalid_mobile', ) ], max_length=32, blank=True, ) I am using Django Rest Framework and some of the errors are handled in the serizliers and the ugettext_lazy is working properly in the serializer errors but when it comes to the model messages, the translation is not working and it returns the English version of the error. -
How to create API by Django Rest Framework for minio bucket creation?
I Can't understand how to create minio bucket for authenticate user. this API will be create by Django rest Framework . -
CurrentUserDefault doesn't work with AnonymousUser
I'm trying to use CurrentUserDefault with a field that can be null: # model class Package(models.Model): # User can be empty because we allow anonymous donations owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, ) # serializer class PackageSerializer(serializers.ModelSerializer): owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) Everything works fine when a user is logged in. However, if a user is not authenticated I get this: ValueError at /api/organizations/village/packages/ Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fc97ad6d940>": "Package.owner" must be a "User" instance. Is there a reason why CurrentUserDefault doesn't work with anonymous users? P.S. I know I can use this instead of CurrentUserDefault and it will work: class AuthorizedUserOrNone: requires_context = True def __call__(self, serializer_field): user = serializer_field.context["request"].user if user.is_authenticated: return user return None def __repr__(self): return "%s()" % self.__class__.__name__ -
Is it possible to display the HTML provided by the admin panel app on-site?
I've built a site where I can create new posts (essays) by the admin panel. The output is visible to users. But when I place some HTML as content in the form it doesn't render itself on the page. example: Output on the page (with marked unrendered HTML): I would like to know how to fix it and also, how to name the topic I want to know ( I couldn't find anything related to my problem, probably because I don't know how to express it). -
Python - Django MySql raw sum returns single value
Beginning in Django, I try to query data from MySQL and running with an issue while I try to use raw. I return, I correct values, grouped, but not summed (only return last value for that group I guess). My query works good when I run it on MySQL directly, just not with objects.raw. Any idea why that is / How to work with that? My code is as below. yesterday = date.today() - timedelta(days=1) list_parts = PqList.objects.raw('SELECT id, SUM(quantity), equipment_id, so_number FROM pq_list WHERE date > %s group by equipment_id, so_number', [yesterday]) context['list_parts'] = list_parts -
Django message framework doesn't show messages
I have a flow where one page adds a message to Django's message store (CookieStore) and another page displays that message (by rendering it onto a template). All works nicely in most environments. However I have one environment where the message doesn't show. I can see the cookie being set, but it is not getting removed in the "other" page load. My question is - are there any env variables that may be preventing the messages from being cleared from store and rendered onto a page, or any other settings to look out for? This environment is not easy to debug, so I can't set any breakpoints and searching the code didn't reveal anything obvious. -
How to create view and serializer to add to many to many field in DRF
I implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. Furthermore, I have been struggling and could not get answer anywhere how to update created card with dish. Or create a card with dishes in it. Should I try to create a middle filed with IDs of card and dish or there is some other way to do it in DRF? I have been struggling with this for some time and would greatly appreciate some tip please. Here is the code: class Dish(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) price = models.DecimalField(max_digits=5, decimal_places=2) preparation_time = models.IntegerField() date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) vegan = models.BooleanField(default=False) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) dishes = models.ManyToManyField(Dish, blank=True) def __str__(self): return self.name class DishSerializer(serializers.ModelSerializer): class Meta: model = Dish fields = ['id', 'name', 'description', 'price', 'how_long_to_prepare', 'date_added', 'update_date', 'vegan'] read_only_fields = ['id'] class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ['id', 'name', 'description', 'date_added', 'update_date', 'dishes'] read_only_fields = ['id'] class CreateCardView(generics.CreateAPIView): """Create a new user in the system.""" serializer_class = serializers.CardSerializer class AddToCardView(generics.CreateAPIView): serializer_class = serializers.CustomUserSerializer -
Optimal way to fetch related model and through model together in ManyToManyField
Given schema: class Investor(models.Model): name = models.CharField(max_length=30) advisors = models.ManyToManyField("Advisor", related_name="investors", through="Connection") class Advisor(models.Model): name = models.CharField(max_length=30) class Connection(models.Model): investor = models.ForeignKey("Investor", related_name="connections", on_delete=models.CASCADE) advisor = models.ForeignKey("Advisor", related_name="connections", on_delete=models.CASCADE) blocked = models.BooleanField(default=False) And given an Advisor "a", what is the optimal to fetch a list of all Investors and their Connection to "a" when it exists? The best I've figured out so far is: from django.db.models import Prefetch for investor in Investor.objects.prefetch_related( Prefetch( 'connections', queryset=Connection.objects.filter(advisor=a), to_attr='connection', ) ): name = investor.name blocked = None if investor.connection: blocked = investor.connection[0].blocked print(f"{name} (blocked={blocked})") -
REACT: using a functional component in a class-defined class modal
I have a problem which I cannot solve: I started a ReactJS project and used the class definition for all components. Now I would like to add the following tool to my webapp: DragandDropApp. This tools uses the functional definition and now I need help on how to implement this / add this componenent to a modal, which was defined as a class. Is it in general possible to do that? If yes, could you help me on how to return/ render the component, so that I can add it to my app? Thank you very much in advance! Best, Simon -
How to display text in HTML from an array?
I have a project that I am working on. I call my Django API and I get a ManyToMany array back as seen below. [ {"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"} ] What is the best way to display the below in HTML as: Money Django Test Instead of [ {"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"} ] I am trying to pass the above into an HTML element and display on the frontend. Any and all help is appreciated! -
Django model form this field is required
I am new to Django. Trying to add data to database using ModelForm. But getting an error "This field is required.." My model: class Docstest(models.Model): uploader =models.ForeignKey("auth.User",blank=False,null=False,on_delete=models.CASCADE) nameOfApplicant = models.CharField(max_length=50,blank=False) serviceRequestedName= models.ForeignKey(ServicesOffered,on_delete=models.CASCADE,blank=False,null=False) nameOfDocument = models.ForeignKey(DocumentsRequired,on_delete=models.CASCADE,blank=False,null=False) documentFile = models.FileField(upload_to='documents/%M', blank = False, null = False) def __str__(self): return str(self.nameOfDocument)+str(self.uploader) forms.py class MyForm(forms.ModelForm): class Meta: model = Docstest fields = ["uploader", "nameOfApplicant","serviceRequestedName","nameOfDocument","documentFile",] labels = {"uploader":"uploader", "nameOfApplicant":"nameOfApplicant","serviceRequestedName":"serviceRequestedName","nameOfDocument":"nameOfDocument","documentFile":"documentFile",} my html {% extends 'base.html' %} {% block columncard %} <div class="container"> <form method="POST"> <fieldset> <legend>Form</legend> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </fieldset> </form> </div> {% endblock %} There is a error "This field is required". Data not saved in Database. Help. -
403 error trying to access main site - Django Apache Ubuntu
I am learning Django and have been trying to follow the tutorial here: https://www.youtube.com/watch?v=Sa_kQheCnds&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=14 This is a Python Django application which should run on Apache engine on Ubuntu on a Linode Server. However I can't get the production to work. When I was on the step of running the app on Django server via 0.0.0.0:8000 port it worked, when I got to the point where according to video everything should work, via HTTP 80 port, it gives me 403 error saying "You don't have permission to access this resource" I have looked through some similar posts, but they have not helped to solve my problem or I did not understand how should I apply the solution. How can I check what causes this problem? What parts of code can I provide to help to solve it? -
How to solve dependency conflicts in requirements.txt file in Django deployment
I am trying to deploy my Django app on GCP using google appengine. First I deployed the app after testing on localhost by following this documentation by Google appengine. deployed the app using gcloud app deploy But there is some issue and the server is not running showing the error as 502 Bad Gateway Then I checked the logs and then realized that I forgot to upload the requiremts.txt file. the uploaded file and tried to deploy the app again. But got an error as ERROR: Cannot install -r requirements.txt (line 19), -r requirements.txt (line 21), -r requirements.txt (line 27) and grpcio==1.48.1 because these package versions have conflicting dependencies. Here is some dependency conflict between modules Gcloud suggested a documentation https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts to solve this but I'm not getting it actually how to solve the conflict of modules in requirements.txt Here is the requirements.txt file APScheduler==3.6.3 asgiref==3.5.2 backports.zoneinfo==0.2.1 beautifulsoup4==4.11.1 cachetools==4.2.2 certifi==2022.6.15 charset-normalizer==2.1.1 dill==0.3.5.1 Django==4.0.6 django-environ==0.9.0 django-social-share==2.3.0 environ==1.0 google==3.0.0 google-api-core==2.10.0 google-auth==2.11.0 google-cloud-secret-manager==2.12.4 google-cloud-speech==2.15.1 googleapis-common-protos==1.56.4 grpc-google-iam-v1==0.12.4 grpcio==1.48.1 grpcio-status==1.48.1 idna==3.3 Pillow==9.2.0 proto-plus==1.22.1 protobuf==4.21.5 psycopg2==2.9.3 pulumi==3.39.3 pyasn1==0.4.8 pyasn1-modules==0.2.8 pytz==2022.2.1 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0 requests==2.28.1 rsa==4.9 semver==2.13.0 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.2 tornado==6.2 tzdata==2022.1 tzlocal==4.2 urllib3==1.26.12 And an error log Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build … -
How to pass a dict to a unit test using parameterized?
I have a list of dicts: MY_LIST = [ { 'key1': {'a': 1, 'b':2 } }, { 'key2': {'a': 1, 'b':2 } } ] How do I pass the dict to a django unit test using parameterized? E.g. @parameterized.expand(MY_LIST): def test_mytest(self, dict_item): print(dict_item.items()) Results in AttributeError: 'str' object has no attribute 'items' because the dict is being converted to a string. -
Django ImageFiled thumbnail from video
I need to make a thumbnail from a video and save it to Django's ImageField. I already have the working code which saves the thumbnail to a specified folder but what I want is to redirect the output of FFmpeg directly to Imagefield (or to a in memory uploaded file and then to Imagefield) This is my current code: def clean(self): file = self.files['file'] output_thumb = os.path.join(settings.MEDIA_ROOT, 'post/videos/thumbs', file.name) video_input_path = file.temporary_file_path() subprocess.call( ['ffmpeg', '-i', video_input_path, '-ss', '00:00:01', '-vf', 'scale=200:220', '-vframes', '1', output_thumb]) self.instance.video = self.files['file'] self.instance.video_thumb = output_thumb I'd like to do it so that I wouldn't need to specify the folder to save the thumb in (output_thumb in the code) and for Django to save it automatically using the upload_to='post/videos/thumbs option in the model definition Please point me in the right direction of how to do this. -
Django filter queryset for each item
I cant think of a good logic myself so I hope that somebody could help me out. The goal is this: I have a date which a user can enter, a from_date, prognosis_hour, to_date and default_hour. I need to filter from the employee_set each employer who has a from_date with his prognosis_hour within the range of the date which a user enters, to sum it with other employee hours, the twist is, when there are employees without from_date with prognosis_hours, then default_hour should be used. Now I have this @property def prognosis(self): mylist = [] for e in self.employee_set.exclude(prognosis_hours__isnull=True, from_date__isnull=True): for i in self.employee_set.filter(from_date__gte=self.entered_date, to_date__lte=self.entered_date): e.default_hours mylist.append(i.prognosis_hours) mylist.append(e.default_hours) return mylist right now it filter everybody within the entered date and append it to the list, showing default and prognosis hours, but ignores everybody else with default hours In the end it should just sum all default and prognosis hours together when prognosis hours are within range of the date today or the entered date from user I know that the sum is missing and that I can append it together etc. it is copied from my debugging process class work(models.Model): entered_date = DateField() @property def prognosis(self): mylist = [] for … -
convert django to nextjs mongoose
I need convert this django code to mongoose nextjs BonusRefill.objects.values('user').order_by('user').annotate(total_price=Sum('amount')).order_by('total_price').last() i tried this but not working BonusRefill.find().sort('user')