Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Couldnot resolve URL for hyperlinked relationship using view name "snippet-detail"or incorrectly configured the `lookup_field` attribute on this field
""ImproperlyConfigured at /snippet/5 Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field."" ----models.py from email.policy import default import imp from tkinter import CASCADE from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight from django.contrib.auth.models import User import snippets # Create your models here. LEXERS=[item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES=sorted([(item[1][0],item[0]) for item in LEXERS]) STYLE_CHOICES=sorted([(item,item)for item in get_all_styles()]) class Snippet(models.Model): created=models.DateTimeField(auto_now_add=True) title=models.CharField(max_length=100,blank=True,default='') code=models.CharField(max_length=250,default="0") linenos=models.BooleanField(default=False) language=models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100) style=models.CharField(choices=STYLE_CHOICES,default='friendly',max_length=100) owner=models.ForeignKey('auth.User',related_name='snippets',on_delete=models.CASCADE) class Meta: ordering=['created'] ------permissions.py import imp from rest_framework import permissions class IsOwnerReadOnly(permissions.BasePermission): """custom permissions to only allow owners of an oject to edit """ def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user -------serializers.py from operator import mod from numpy import source from .models import * from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model=Snippet fields = ['url', 'id', 'owner', 'created', 'title', 'linenos', 'language', 'style'] # fields='__all__' # fields=['id','url','owner'] from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): snippets=serializers.HyperlinkedRelatedField(lookup_field = 'username',many=True,view_name='snippet-details',read_only=True) owner=serializers.ReadOnlyField(source='owner.username') class … -
ModuleNotFoundError: No module named 'drf_spectacular.views'
urls.py from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/redoc/', SpectacularRedocView.as_view(url_name='api-schema'), name='api-redoc'), path('api/user/', include('user.urls')), path('api/recipe/', include('recipe.urls')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'drf_spectacular', 'core', 'user', 'recipe', ] requirements.txt drf-spectacular # drf-spectacular>=0.15,<0.16 REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } I'm trying to add Swagger UI in Django API, but I'm getting this error ModuleNotFoundError: No module named 'drf_spectacular.views'. -
List all online users in a Django Project
You see I am trying to make a simple chatting web app in Python/Django and I was trying to make the mock-up of the whole project first. But when i got to the part where other users would be able to see who was online or not i totally got stuck. I mean I HAVE NO IDEA AT ALL. any ideas??? -
type object 'PizzaMenu' has no attribute '_default_manager'
I have following error while i try to reach PizzaDetailView on template: AttributeError at /pizza/6/ type object 'PizzaMenu' has no attribute '_default_manager'. Where is the problem? models.py class PizzaMenu(models.Model): name = models.CharField(max_length=30) description = models.TextField() ingredients = models.CharField(max_length=100) price = models.DecimalField(max_digits=4, decimal_places=2) def __str__(self): return self.name class Meta: ordering = ["price"] views.py from django.views.generic import TemplateView, ListView, DetailView from .models import PizzaMenu class IndexView(TemplateView): template_name = "index.html" class PizzaMenu(ListView): model = PizzaMenu template_name = "menu.html" context_object_name = "pizza_menu" # ordering = ["price"] class PizzaDetailView(DetailView): model = PizzaMenu template_name = "pizza_detail.html" context_object_name = "pizza_detail" class About(TemplateView): template_name = "about.html" urls.py from pizza.views import IndexView, PizzaMenu, About, PizzaDetailView urlpatterns = [ path("", IndexView.as_view(), name="home"), path("menu/", PizzaMenu.as_view(), name="menu"), path("about/", About.as_view(), name="about"), path("pizza/<int:pk>/", PizzaDetailView.as_view(), name="pizza_detail"), path("admin/", admin.site.urls), ] -
DRF/django-filter programmatically calling a Filterset class without using the Viewset/request
I am building functionality to allow users to save a set of filters from a query-builder component on my Angular frontend. I am also using the django-filter package to power most of the search ability in my app. Say I have a model named MyModel (with a FK field 'category') and a ViewsSet wherein I've specified filterset_class = MyModeFilter from django_filters import rest_framework as filters class MyModelFilter(filters.Filterset): category_in = filters.BaseCSVFilter(field_name='category', method='filter_category_in') def filter_category_in(self, qs, name, value): # filters happen return qs This works well when my frontend calls https://api-url/mymodel/?category_in=1,2,3 What I want to do now is programmatically call this filter from inside the django app. Use case: I need to program a CRON job to build and email an excel report based on a queryset that would match the ?category_in=1,2,3 param filter. This is very straightforward with the ViewSets when using DRF requests, but I don't know where to start looking at his to use this filter without going the requests route. The the filter is saved in a JSONField (saved_query_statement) in a model called SavedQuery. It will look something like this: sqs = { 'name': 'category', 'lookup_expr': 'in', 'value': '1,2,3' } So the CRON job function, when executed, will … -
list index out of range Django overlapping
Hi When I am checking overalapping i am getting list index out of range, how i can solve that , for i in range(count): start_value=(self.data.get(f'applicationvalue_set-{i}-start_value', [])) end_value=(self.data.get(f'applicationvalue_set-{i}-end_value', [])) if start_value is not None or end_value is not None: value1=[] value2=[] for start in start_value: if start not in value1: value1.append(start) for end in end_value: if end not in value2: value2.append(end) a=range(value1[0],value1[-1]) b=range(value2[0],value2[-1]) if a in b.exists(): raise ValidationError("overlap not allowed")djangp -
I want to create a chart label with code like this, but I got an error. what's the solution?
I think there's something wrong with the labels and I don't know what. Please I need your help. I want to create a chart label with code like this, but I got an error. what's the solution? <div class="container"> <div class="row my-5"> <div class="col-md-6"> <div class="bg-white"> <canvas id="myChart1" width="400" height="300"></canvas> <script> var ctx = document.getElementById('myChart1').getContext('2d'); var myChart1 = new Chart(ctx, { type: 'pie', data: { labels: [{% for product in product %} '{{product.name}}', {% endfor %}], datasets: [{ label: 'Orders', -
Changing the language in Firefox Selenium Django / Python for behave tests
I am running local Selenium Behave tests on Firefox for a Django / Python project. My Firefox browser is set to English and I visit my local website via the browser manually everything is in English. However, when I run the Behave tests with Selenium, the browser is in German, as well as the standard language selected on my website. When I use the fix in this thread it changes the browser language to English but not the default language of the website. This would be the code of the before_all script: from selenium.webdriver import Firefox, FirefoxOptions from selenium.webdriver.support.ui import WebDriverWait def before_all(context): """Run once before any testing begins.""" options = FirefoxOptions() options.set_preference('intl.locale.requested', 'en') options.headless = False context.driver = Firefox(options=options) context.driver.implicitly_wait(5) context.driver.set_window_size(1024, 768) context.wait = WebDriverWait(context.driver, 30) logging.disable(logging.ERROR) (The problem is that the behave tests do not find the German button texts) -
Django Production Server Server Error 500 nginx -t shows something different
I need to deploy my website urgently and when I finally did that I was playing around with certbots and so on and it worked fine. Both Http and Https website with domain was running. I made changes to my code and the settings and reloaded the nginx and gunicorn and I thought it is still working fine. But then I had some code changes that weren't taking effect so I did a reboot. Now the server isn't working coming back with Server Error 500. python manage.py runserver runs fine. Debug is true in setting.py nginx -t comes back with this problem: ubuntu system django Version 4.x, python 3.9. nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2022/05/24 08:44:59 [warn] 4182#4182: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1 2022/05/24 08:44:59 [emerg] 4182#4182: cannot load certificate "/etc/letsencrypt/live/domain.com/fullchain.pem": BIO_new_file() failed (SSL: error:8000000D:system library::Permission denied:calling fopen(/etc/letsencrypt/live/domain.com/fullchain.pem, r) error:10080002:BIO routines::system lib) I need to get this server up and running again. Please help. Thank you -
django 3.2.9: update time stamp on view function call
I am using django 3.2.9 as a back-end for my app. This is an excerpt of my Project model: class Project(TimeStampedModel): """ A collection of projects completed """ uuid = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True) account = models.ForeignKey('accounts.Account', on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=250, blank=True, null=True) # I need to add a time stamp here copied_on I need to add a time stamp to my Project model that gets updated every time the following view is called: @action(detail=True, methods=['post']) def copy_to_account(self, request, *args, **kwargs): user = request.user project = self.get_object() do yo know how to do it? Thank you -
How to implement date range filter in django-filters
I want to filter upload_date in date range (upload_date__lte, upload_date__gte) My models is class MetaData(models.Model): # Video Info tag = models.CharField(max_length=100, default="") category = models.CharField(max_length=100, default="") upload_date = models.DateField() upload_time = models.TimeField() caption = models.CharField(max_length=2000, blank=True, default='Not Set') comments = models.IntegerField() likes = models.IntegerField() shourtcode = models.CharField(max_length=200, default='', unique=True) owner_id = models.PositiveIntegerField(default=0) # Post link = models.URLField(unique=True) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=20, choices=( ('Pending', 'Pending'), ('Acquired', 'Acquired'), ('Rejected', 'Rejected'), ('Approved', 'Approved')), default='Pending') public = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) My views is class FetchMetaData(ListCreateAPIView): queryset = MetaData.objects.all() serializer_class = s.MetaDataSerializer name = 'metadata-list' pagination_class = DefaultPagePagination filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filter_fields = ( "tag", "category", "public", "status", "user", "upload_date", ) ordering_fields = ( '-upload_date', '-upload_time', 'likes', 'comments', ) search_fields = ( "$tag", "$caption", "$category" ) ordering = ['-upload_date'] What I want is filter range in upload_date Like http://localhost/tags/filterMetadata/?upload_date__lte=2022-01-05?upload_date__gte=2022-01-05 -
starting a website project in python and django in windows 10
Whenever I type django-admin start project project name the console returns Django-admin : The term 'Django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 Django-admin start project emart + CategoryInfo : ObjectNotFound: (Django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException. -
AssertionError: Class UserSerializer missing "Meta" attribute while performing User Accounts Management on Django
my views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("User created") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_data}, status=200) return Response({'msg': "error: no user created"}, status=400) my serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop(password, None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token' 'username', 'password', 'first_name', 'last_name', 'email', 'id' ) my urls.py file: from django.urls import path from .views import TestView, UserView from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token urlpatterns = [ path('test', TestView.as_view()), path('user-view/', UserView.as_view()), ] Postman request: as you can see, i'm sending a username … -
Django translations with parler - show default language text when adding translation
I'm working on a Django CMS with content to be translated into multiple languages. I'm using django-parler. To make the translations easier I would like to have the text from the default language visible when adding the translated text, preferable just above the input field/textarea. Any ideas on how to solve it? -
how to improve many to many relationship in django
I have 2 models User and Content and they have relationship called Watched which is many-to-many. this relationship will be using a third table (using through in Django) and how it works is that for each set of user and content we are going to keep what was the last position before they stopped watching and there is going to be one row per each user-content so if a user watches a content multiple time first time that row is created and next times that row only updates to keep the last data. our database engine is mariadb. currently we have about 10000 users and 4000 contents. so at max that third table would have 40,000,000 and we expect to have about 15000 users and 6000 content so it need to be able to handle 90,000,000 record at most. Question 1: someone suggested we handle the third table ourselves and don't use the many-to-many relationship offered by Django because it might use some joins and queries that will be heavy for database. (so it would be a table with 2 integer fields for id and 1 other field for last position) is this a good solution or we should stick … -
Django: How to display the average of all rating using django?
i am creating a function where users can rate a book using django, i have achieved the part where users can rate the book using a form from the front end and it get saved in the backend. Now what i want to achieve is a way to display an average of all the rating that the user make. e.g let say there are usera - 1.0, userb - 3.0, userc -5.0. i want to display the average which is 3.0 and i dont know how to achive this. let men put some of the code i have written below models.py class BookRating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=True) rating = models.CharField(max_length=1000, choices=USER_BOOK_RATING) review = models.TextField() view.py - only what i am doing is listing out all the reviews but not the average of star rating -
how to implement Applepay for django ecommerce website?
I want to implement applepay for django ecommerce website. How to implement applepay with django framework? -
Encoding issue when opening text file with Django url
I have a simple text file with accents in django media. The file is encoded in UTF8. When I open it with my browser (/home/xxx/my_django_app/media/changelog.txt), the accents are displayed. On the other hand, when I open it via django directly with the url (localhost:8000/media/changelog.txt), the accents are not displayed, as if the file was not in UTF 8. How to solve this problem ? -
replace 'Null' with zero in python
I'm replacing Null or None with zero when there is a value I want to show the value in Django Even when there is a value for the 'Requester' in SQL it still showing as zero. In SQL, I'm getting 'Requester' value as 5 but still it's showing as 0. I don't know where I'm going wrong Here, what I tried @apiview(['GET']) def GetCurrentRunningActivityAudit(UserID): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set =cursor.fetchall() IsActive = 'true' data = [] for row in result_set: TaskId = row[0] data.append({ 'TaskId':row[0], 'TaskName' : row[1], 'Source' : row[2], 'Requester' : 0 if row[3] == 'NULL' or 'NONE' else row[3], 'type' : row[4], }) return Response(data[0], status=status.HTTP_200_OK) return Response(data) -
Import model methods in other model
I'm using Django Rest Framework for API where I need to use methods from one model into another. But, this results in ImportError: cannot import name '...' from partially initialized module '...' (most likely due to circular import) My models samples are as follows: Model A from ..B.models import B Class A: @classmethod def foo(): b = B() b.bar() Model B from ..A.models import A Class B: @classmethod def bar(): a = A() a.foo() I understand the error is being caused to due to ciruclar import. Is there any way to import methods in each other's model? -
Can't Upload Image to ImageField through csv file
My Django application: In my model, I use ImageField to allow the upload of images. In my csv file I have an image path for an image like this: C:/Users/blah/DjangoProject/abc/abc/csvs/photos/product_1/product-1_1.jpg In my csv's view I got: Product.objects.create(product_name=row[0], slug=row[0].lower().replace(' ', '-'), product_description=row[1], price=row[7], image_1=ImageFile(open(row[8], 'rb'))) The row[8] contains the image's path. When I'm going to my csv.html using Django's FileField to upload csv file which contain the image's path and product's info, after uploading the product should be created in my database which image should also be uploaded to a filesystem - not storing in database. Instead, I got this error: OSError at /csvs/ [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\Users\blah\DjangoProject\abc\abc\media\photos\products\C:' When I removed the image_1 row in Product.objects.create(), the product was uploaded and added to the database successfully. If I restore the image_1 row in the object creation, I got the same error again. Does anyone know why? -
Set JWT access token
which one is better and why : set JWT token in request headers by frontend developers or set in cookie by backend developers ? -
Django, save only resized image, not the original
So I have this model in my Django project: class Image(models.Model): image = ... def save(self, *args, **kwargs): super().save(*args, **kwargs) ... # resizing and saving the image Just a simple model with ImageField. I wonder how to save only resized images. As I know "super().save(*args, **kwargs)" saves the original image with its original sizes. But it takes too long to save for example 10-15 MB photo. In my resizing logic the image is compressed and resized to about 1-3 MBs. And I want to save in my MEDIA root only this resized image and not the original one. I don't want the original image even appear in my project (it takes way too long to process this image while saving). How to avoid "super().save(*args, **kwargs)"? Hope you got it, thanks in advance! Any suggestions are appreciated! -
Django set a connection proxy
I have long time seeking for a solution to set a proxy for my Django application. 1st I am using Django==2.0 and I run it in Windows Server 2016 in a local network that uses a Proxy to connect 10.37.235.99 and Port 80. and I'm deploying the application using nginx-1.20.1 I have to scrape a data as http_proxy = "10.37.235.99:80" https_proxy = "10.37.235.99:80" ftp_proxy = "10.37.235.99:80" proxyDict = { "http" : http_proxy, "https" : https_proxy, "ftp" : ftp_proxy } import socket if socket.gethostname() == "localhost": os.environ["PROXIES"] = proxyDict else: os.environ["PROXIES"] = {} URL='my_site.com' page = requests.get(URL) print(page) I tried many solutions on the internet but no way! Working with django : Proxy setup when I remove the proxy configuration and I use Psiphon3(with proxy) everything works perfectly. is there any solution? -
manage.py runworker: error: the following arguments are required: channels
we have a chat application with daphne and Redis servers. web socket is working when there are few requests but as requests increase we start to get 503 error and the connection closed out. We are trying to run daphne on workers with the below command. (venv) expert@expert-X542UQ:~/PycharmProjects/Asktalos/asktalos$ python manage.py runworker but we are getting an error message saying it requires channels parameter. usage: manage.py runworker [-h] [--layer LAYER] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] channels [channels ...] manage.py runworker: error: the following arguments are required: channels can anyone help with what channels parameter needs to pass here? below is our docker-compose file for Redis and daphne images. version: "3" services: redis: image: redis:alpine ports: - "6379:6379" networks: - backend daphne: build: . image: "channel_prod:latest" working_dir: /code/ command: bash -c "daphne -b 0.0.0.0 -p 9542 Bot.asgi:application" networks: - backend ports: - "9542:9542" environment: - DJANGO_SETTINGS_MODULE=Bot.settings depends_on: - redis links: - redis worker: build: . command: python3 manage.py runworker channel_layer links: - redis depends_on: - redis networks: backend: driver: bridge