Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin login SSL_do_handshake() failed
I get following in nginx-error log while logging in to admin page of django website 2022/01/28 17:04:50 [crit] 22184#22184: *263 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.184, server: 0.0.0.0:443 2022/01/28 17:08:12 [crit] 22184#22184: *277 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.239.221, server: 0.0.0.0:443 2022/01/28 17:08:30 [crit] 22184#22184: *288 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.251, server: 0.0.0.0:443 2022/01/28 17:10:09 [crit] 22184#22184: *302 SSL_do_handshake() failed (SSL: error:14201044:SSL routines:tls_choose_sigalg:internal error) while SSL handshaking, client: 45.56.98.215, server: 0.0.0.0:443 2022/01/28 17:28:03 [crit] 22184#22184: *344 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 165.227.140.0, server: 0.0.0.0:443 One possible reason is I do not have the secret key I used while making the django project as I lost the .env file. I used this answer to generate a secret key and to store in the .env file. Could this be the reason, or is there some other reason? -
Updating is_issued in Book model after adding a book in Issued. Django restframework
This is models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) is_issued = models.BooleanField(default=False) isbn = models.CharField(max_length=100) def __str__(self): return self.title class IssuedBooks(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) issued_to = models.CharField(max_length=100) issued_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.book.title viewsets.py from rest_framework import viewsets from .models import Book, IssuedBooks from .serializers import BookSerializer, IssuedBooksSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class IssuedBooksViewSet(viewsets.ModelViewSet): queryset = IssuedBooks.objects.all() serializer_class = IssuedBooksSerializer # Add book to IssuedBooks and update book's is_issued field # Also be able to issue books when is_issued is false I assume the solution has something to do with the viewsets. It basically needs to have create and delete methods for Issuedbooks route while also updating and referencing Book model. -
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I am a beginner in Django. I am trying to build an app with user authentication. However I want extra fields like country and phone number, and I don't want any username field (I want the phone number to act as the username), so I built a custom user class. There are questions that have already been asked that have the same error, but they are not exactly relevant to my use case and the solutions don't work for me. models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django_countries.fields import CountryField # Create your models here. class UserProfile(AbstractBaseUser): user = models.OneToOneField(User, on_delete = models.DO_NOTHING) phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False) country = CountryField() uid = models.UUIDField( default = None, blank = True, null = True, unique = True, ) USERNAME_FIELD = "uid" REQUIRED_FIELDS = ['phone_number', 'country'] forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django_countries.fields import CountryField # Create your forms here.. class NewUserForm(UserCreationForm): phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$') country = CountryField() class Meta: model = UserProfile fields = … -
django-filter and django custom pagination with ModelViewSet
I implemented a modelviewset with django-filter and django default pagination comnbined. Its working fine when I use either django-filter or django pagination. But when they are used simultaneously then I am getting duplicate results in response. So whats the correct way to use pagination in django-filter with CBV? class TableMetaView(ModelViewSet): """ This will be used to create new tables. You require to add the table fields in json request and also the job request associated with that table. If you want to create new table then pass CREATE NEW TABLE In response you will get the table list along with the job request for each tables """ serializer_class = TableMetaSerializer queryset = TableMeta.objects.all() renderer_classes = [JSONRenderer] filterset_fields = [ "schema_name", "type", "status", "grouping__name", "dataset__name", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] pagination_class = StandardResultsSetPagination permission_classes = [ UserHasDatasetChangeAccess & IsTableEditable, ] def get_queryset(self): if getattr(self, "swagger_fake_view", False): # queryset just for schema generation metadata return TableMeta.objects.none() return TableMeta.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ) -
Django get Browser of user
I am trying to get the browser of the current logged in user. To do it I put this in the template {{ request.headers.user_agent }} It works but the output is this: (even if i try it with something like edge browser) Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4692.99 Safari/537.36 Edg/96.0.1072.69 My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ...... ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', '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', ] Based on the browser I want to display a different content in the HTML. What is the best way to get the exact browser? -
Django how to upload CSV file using Form to populate postgres database and display all items in browser
Django 3.2.1, Python 3.6, Postgres database I am writing a small Django app that will use the browser to import products from an uploaded csv file via a Form and populate the database. I currently have the app set up so that users can manually add, edit, or delete individual products. These get saved to the database properly. However, I also want an option where a user can upload a csv with many thousands of products using a Django Form. I have written the backend logic for the app using Custom Management Commands and have read the docs but am still really unclear about how to achieve this using Forms while maintaining full functionality. I have tried many variations on using forms and completed the tutorials on Django's site, but have not been successful at actually getting the file to upload via Form, parse all lines correctly, save to database, and display all newly saved items at /show_products alongside where the products that have been manually added are displayed. Example of the csv file: name,sku,description Brian James,skus-will-look-like-this,The products will have various descriptions. And multiple lines too. Here is an example of my backend code that can upload a local csv … -
Structure of models to store a subset of choices to be available dependent on row being edited
I'm building a site that tracks parts, these part belong to a subsection of project, denoted by section codes. I want to be able to limit the choices of codes based on which project the part belongs to, but not sure the best way to store a list of acceptable codes. I started with: class Project(models.Model): name = models.CharField(max_length=40) number = models.IntegerField() class Section(models.Model): code = CharField(max_length=1) class Part(models.Model): number = models.IntegerField() project = models.ForeignKey(Project, on_delete=models.PROTECT) section = models.ForeignKey(Section, on_delete=models.PROTECT) The problem with this is that all parts then get to choose from the same list of section codes. -
models.py order of the models gives NameError: name 'Category/Post' is not defined
I'm new to Django so this is probably a dumb question but, when I put the class Category model above the class Post model I get an NameError: name 'Post' is not defined error. but when I try to put class Category model underneath the Post model (as in the code here) I get categories = models.ManyToManyField(Category) NameError: name 'Category' is not defined error. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) #if is deleted than delete their posts location = models.CharField(max_length=100, default="") tags = TaggableManager() likes = models.ManyToManyField(User, related_name='blog_posts') categories = models.ManyToManyField(Category) def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): post = models.ForeignKey(Post, related_name="categories") name = models.CharField(max_length=20) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Post, Comment, Category #, Konum # Register your models here. admin.site.register(Post) admin.site.register(Comment) admin.site.register(Category) #admin.site.register(Konum) -
Django href for html
How i can make link to this urls.py? I tried to pass the link through all the methods I know but they don't work and gave an error path('category/<slug:gender_slug>/<slug:category_slug>/', views.StuffCategory.as_view(), name='category'), html: {% get_genders as genders %} {% for gender in genders %} <li> <!-- First Tier Drop Down --> <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down" aria-hidden="true"></span> </label> <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a> <input type="checkbox" id="drop-2"> <ul> {% get_categories as categories %} {% for category in categories %} <li><a href="/">{{category.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} views.py class StuffCategory(ListView): model = Stuff template_name = 'shop/shop.html' context_object_name = 'stuffs' def get_queryset(self): queryset = Stuff.objects.filter(draft=False) if self.kwargs.get('category_slug'): queryset = queryset.filter(category__slug=self.kwargs['category_slug']) if self.kwargs.get('gender_slug'): queryset = queryset.filter(gender__slug=self.kwargs['gender_slug']) return queryset -
Cron jobs run ok as script but not @reboot
I'm running a Django (v3.1.7) application on a headless remote Ubuntu (v20.04.3) that I'm looking to have start at reboot using crontab. The script below runs all ok from the command line. I've been through here crontabs-reboot-only-works-for-root and the linked suggestions as well but still haven't identified the issue. I've added logging (see *.log below) but do not get any helpful output. /home/myapp/reboot.sh #!/bin/bash echo "$(date) Starting reboot.sh" start_django () { echo "$(date) Entering start_django" screen -S django -dm bash -c 'cd /home/myapp && /usr/local/bin/gunicorn myapp.wsgi:application --bind 0.0.0.0:8000' > /home/myapp/django_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_django" } start_stream () { echo "$(date) Entering start_stream" screen -S streaming -dm bash -c 'cd /home/myapp/data_api && python3 api_stream_client.py' > /home/myapp/stream_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_stream" } start_test () { echo "$(date) Entering start_test" screen -S testa -dm bash -c 'cd /home/myapp && exec bash' > /home/myapp/test_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_test" } if screen -list | grep -q "No Sockets found"; then echo "$(date) No screens available" echo "$(date) Starting test" start_test echo "$(date) Starting django" start_django echo "$(date) Starting stream" start_stream else if screen -list | grep -q "django"; then echo "$(date) django exists" else echo "$(date) … -
Caching TemplateView
I want to use cache from django to cache one template that makes expensive queries. I am not sure if I can just use render() in the get handler as in snippet below: class MyTemplateView(TemplateView): template_name = "my-template.html" def get(self, request, *args, **kwargs): cached = cache.get("my-view-response") if cached: return cached response = super().get(request, *args, **kwargs).render() # <--- cache.set("my-view-response", response) return response def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... # expensive queries return context Normally TemplateView.get returns TemplateResponse instance so by calling render it feels like I am skipping some steps. So my question is: is it ok to return string from TemplateView.get? inb4: The webpage loads correctly; I can't cache the TemplateResponse instance itself because it throws an exception; I have to use "low-level" cache API cause I am invalidating it when rows are added/deleted or modified (which will not happen often) -
How to list information on another page for a form
I am trying to make a question page where a user can click the questions ID. Upon clicking they will be redirected to another page to answer this question with the question text appearing and showing the multiple choice questions. How would I go around doing this? So far I have this Clicking number one will take the user to the question with the multiple choices for this question and question text Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, … -
display video using django FileField uri [react-native]
Hi I'm working on a react-native and I want to display a video, using expo-av, a django FileField uri, here's my code: <Video source={{ uri: "my/django/HE7sU4ABuNRAvwpFfW3qME.MP4" }} onError={(e) => { console.log(e); }} /> Now the problem is that if I try to load a video using uri for django FileField video the following error occurs: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I configure django to allow video displaying in react-native? -
Django Rest Framework Nested Comments
i am trying to create a backend for blog website. I created a comment model and i have associated with blog post it. When I list the comments, I can also list the answers that have been made to the comment. But there is a problem that even though it appears in the comment as an answer, it also looks like it was the main comment again. How can I solve this. I would appreciate it if someone could help. I may have mistakes in English, I hope I was able to tell you what I wanted to tell you. Thanks in advance. Comment Model: class Comments(models.Model): class Meta: verbose_name = 'Yorum' verbose_name_plural = 'Yorumlar' user = models.ForeignKey(User, verbose_name='Yorum sahibi', on_delete=models.CASCADE) post = models.ForeignKey(Post, verbose_name='Yorum yapılacak Post', on_delete=models.CASCADE,related_name='comments') parent_id = models.ForeignKey('self', verbose_name='Parent Yorum', related_name='subcomments',on_delete=models.CASCADE, null=True, blank=True) comment = models.TextField(verbose_name='Yorum') [enter image description here][1]created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.user.first_name + " " + self.user.last_name + " | " + self.post.title Comment Serializer: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comments fields = '__all__' def get_fields(self): fields = super(CommentSerializer, self).get_fields() fields['subcomments'] = CommentSerializer(many=True, read_only=True) return fields Post Serializer class PostSerializer(serializers.ModelSerializer): tag = serializers.StringRelatedField(many=True, read_only=True) comments = CommentSerializer(many=True, … -
How to connect 2 forms in HTML and Django?
I am creating a web page and i'm wondering if i could make sure that the data on the left is filled before pressing the blue button. On the left you can see a form to pay by entering your address, city etc. but on the right you can see another form with stripe implemented to pay with credit card. I don't know how to get the data from the left and save it in the database so I can create a receipt after successful payment. Here is the code down below. <div class="container-2"> <div class="gray-hover"> <form method="POST"> <div class="item" id="payment"> <div class="row"> <h4>Možnost nakupa 1: Plačilo po povzetju <small><i>(Za plačevanje s kartico je treba izbrati samo količino in vrsto izdelka!)</i></small></h4> {% csrf_token %} {% if form %} <div class="input-group"> <div style="color: red;">{{ form.name.errors }}</div> {{ form.name }} </div> <div class="input-group"> <div style="color: red;">{{ form.last_name.errors }}</div> {{ form.last_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.street_name.errors }}</div> {{ form.street_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.city_name.errors }}</div> {{ form.city_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.email.errors }}</div> {{ form.email }} </div> <div class="input-group"> <div style="color: red;">{{ form.number.errors }}</div> {{ form.number }} </div> {% endif %} </div> </div> <div … -
How do I get the instances of a class with some certain conditions?
I have a model Order from which I want to get all the data in the "ref_code" field but then I want to filter it by the item. So basically what I mean is I want to get all the ref_code of a particular items (which is also a field by a manytomany). I don't know how to tweak it to work. I can only get all the ref_code so far. Any help will be appreciated. Model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) item = models.ForeignKey( 'blog.Post', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True, blank=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.ref_code) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = f'qr_code-{self.ref_code}.png' buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) def get_total(self): total = 0 for order_item … -
how to pass without double " " pass parameters an function in python Django Command
manage.py> generate_stock_nodes --no_of_bays 1 --no_of_racks 5 --no_of_rows 5 --no_of_columns 5 --last_bay_no 17 --creation_type 2 --last_bin_number 0501 --type_id 68 --stock_point_name INDO WESTERN -
How to cache django permissions?
I have implemented permission in django. But for example, {% if perms.application %} <li> </li> {% endif %} Django fetches the permission every time user makes a request, so which means am getting two extra queries: How to cache these permission so that the whole session uses the same ? Is there any better solutions for this ? -
Manually referencing dummy file in Django HttpRequest for testing form submission
In Django, I am trying to create automated tests for a project that includes a file submission via ModelForm. One of the model fields is a FileField, and a test file has already been placed into the project directory so it can be referenced. In order to test the form submission I am creating a dummy user and manually generating an HttpRequest() containing POST data. However, I am unsure of how to manually insert the file into the FileField portion -- I assume I need to reference it somehow, but I don't know exactly how to do that. The test is below: def test_form_submit(self): user = User.objects.create_user( username="testuser", email="asdfasdf@asdf.com", password="asdfasdf" ) request = HttpRequest() request.POST = { "file": [insert file here], # is a FileField "name": "Richard", "date": "2022-01-28", "desc": "A test submission." } form = FileSubmissionForm(request.POST, user=user) form.save() self.assertEqual(Submission.objects.count(), 1) How do I properly reference the file for this test case? The dummy file is located at $MEDIA_ROOT/testing/dummy_file.txt. Thanks! -
django admin mptt: how to show TreeNodeChoiceField instead of ModelChoiceField when add/change with FK
I'm working on a django app that includes some mptt based tree models. I have these models (simplified): class Asset_Type(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', verbose_name='Parent') name = models.CharField(max_length=64, unique=True, verbose_name='Asset Type Name') class Asset(models.Model): name = models.CharField(max_length=64, unique=True, verbose_name='Asset Name') type = models.ForeignKey(Asset_Type, on_delete=models.CASCADE, blank=False, null=False) I have these admin classes declared (simplified): class Asset_TypeAdmin(DraggableMPTTAdmin): mptt_level_indent = 20 admin.site.register(models.Asset_Type, Asset_TypeAdmin) class AssetAdmin(admin.ModelAdmin): list_display = ['name','type'] list_display_links = ['name'] admin.site.register(models.Asset, AssetAdmin) Everything works almost perfect, except this: When I add a new asset I get a template/form with a drop-down list where I can select the Asset_Type. The issue is that the drop-down list is of the class ModelChoiceField so it does not show the tree hierarchy. It shows this in the drop-down list: --------- Root 1 Child 1.1 Child 1.1.1 Root 2 Child 2.1 Child 2.1.1 I would like it to be class TreeNodeChoiceField so it shows this: Root 1 --- Child 1.1 ------ Child 1.1.1 Root 2 --- Child 2.1 ------ Child 2.1.1 I've found information related to this here: https://django-mptt.readthedocs.io/en/latest/forms.html#id4, but honestly I have no clue on how/where should I tell django that the field to use in the add/change form should be TreeNodeChoiceField. I've … -
ModuleNotFoundError: No module named 'spotify'
guys. I made a mistake, when i was creating the file to access the spotify api with my application i accidentally created the folder 'spotify' inside my app folder. Now i tried to move the spotify folder into the django folder, so it would be in the same directory as my app. The issue is that when i try to migrate it shows: "ModuleNotFoundError: No module named 'spotify'. Do you guys have a tip? Thanks in advance! -
annotate - Django ORM optimization
I want to annotate similar product from Order-Line.where Line has a foreign-key relation with products. im showing what ive done so far. recommended_product_ids = Line.objects.all() recommended_product_ids = recommended_product_ids.annotate( rank=Sum('quantity'), ).filter(rank__gte=2).order_by('-rank')[:max_count] -
Django and redis adding :1 to keys
I'm using django-redis to store some data on my website, and I have a problem where Redis is adding :1 at the beginning so my key looks like this: :1:my_key I'm not sure why is it doing this, I've read the documentation on django-redis and I couldn't find anything related, so my guess it has something to do with redis but I can't figure out what. In my settings.py I have the regular: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://xxxxx/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } And in my tasks.py I set keys like the documentation says: from django.core.cache import cache cache.set(my_key, my_value, 3600) So now I can't get the values using the cache.get(my_key) -
Django gives error at {% result_list cl %} when accessing models
unsupported operand type(s) for +: 'Listing' and 'float' Error Django admin The error seems to only happen when trying to access the models on the admin page, whats the cause? Views.py -
Unable to log-in in admi site using aadhaar no in django using custom model
I created a custom django model where I used aadhar number as USER_FIELD which does not give me any error but after creating the superuser I can't log-in in the admin site of django.