Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create urls like Instagram posts or youtube video
I'm building a social network and I're going to create my own urls at random the question that has been on my mind for a long time is how to create urls like Instagram posts like Django like the following: https://www.instagram.com/p/CeqcZdeoNaP/ or https://www.youtube.com/watch?v=MhRaaU9-Jg4 My problem is that on the one hand these urls have to be unique and on the other hand it does not make sense that on a large scale when the number of uploaded posts by the user is more than 100,000 I set unique = True Because the performance of the database decreases Another point is the use of uuids, which solves this problem of uniqueness to a large extent, but the strings produced by uuid are very long, and if I shorten these strings and reduce the number of letters in the string, there is a possibility of a collision. And that several identical strings are produced I wanted to know if there is a solution to this issue that generated urls are both short and unique while maintaining database performance Thank you for your time 💙 -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001D4CBCD96A0>": "Album.owner" must be a "User" instance
I don't know why I have this error, I didn't have it befor, I'm sure that I'm logged in before trying call the api, please find below the code : views.py class AlbumCreate(generics.CreateAPIView): serializer_class = AlbumsSerializer def perform_create(self, serializer): owner2 = self.request.user serializer.save(owner=owner2) class AlbumList(generics.ListAPIView): permission_classes = [IsAuthenticated] queryset = Album.objects.all() serializer_class = AlbumsSerializer class AlbumDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Album.objects.all() serializer_class = AlbumsSerializer Serializer class AlbumsSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField(read_only=True) class Meta: model = Album fields = "__all__" models def upload_path(instance, filname): return '/'.join(['covers', str(instance.title), filname]) class Album(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) cover = models.IntegerField(default=0) photos_number = models.IntegerField(default=0) image = models.ImageField(blank=True, null=True, upload_to=upload_path) def __str__(self): return self.title -
Django Email sending, Rich textbox image triggers email function
I created a Rich Textbox field for emails. Over there I am setting up Some text and inserting a picture. At the email_template.html I added another image, right after the rich textbox field that triggers a link, to see if the mail was opened. The problem is that the image that I insert in the email body triggers the link as well, even if the email has not been opened. I wonder if anyone is stumbled over this problem and how it could be solved? It looks like it triggers because the image is a link as well, so maybe there is an option to load all content only when email is opened? Any thoughts would be helpful. The mail template (email_template.html) : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie=edge"/> <title>Email Trace</title> </head> <body> <div class="container"> {{ content | safe }} {# Rich textbox is here #} <img src="{{ request.get_host }}/campaigns/email/tr-{{ key }}.png" width="0" height="0" /> </div> </body> </html> The function which triggers img is: def email_seen(request,key): Emails.objects.filter(key=key,email_open=False).update( email_open=True,email_open_times_counter=1,email_open_timestamp=datetime.datetime.now() ) print('Email is opened') with open(os.path.dirname(os.path.abspath(__file__))+"/res/1x1.png","rb") as f: return HttpResponse(f.read(),content_type="image/png") -
Style issue from datatables.net
When I use this database from datatables.net the two buttons of table isn't styling. The next page and previous page buttons. In default it shouldn't be like that. How can I change their style? Here is my html: <h1>MyTable</h1> <table class="table" border=1 id="mydatatablem"> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> </tr> </thead> <tbody> {% for x in x_list %} <tr> <td>{{x.full_name}}</td> <td>{{x.company}}</td> <td>{{x.email}}</td> <td>{{x.phone_number}}</td> <td>{{x.note}}</td> </tr> {% endfor %} </tbody> </table> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatablem').DataTable(); }); </script> And this is how it looks in the site: enter image description here -
Django Admin is using the wrong UserManager
I have created a custom user class: class User(AbstractUser): objects = UserDashManager() custom_field = models.CharField(max_length=84) And a UserManager to populate that field at creation: class UserDashManager(UserManager): def create_user(self, username, email, password, **extra_fields): extra_fields.setdefault('custom_field', 'custom field value') extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) I have registered User in admin.py: class CustomAdmin(UserAdmin): model = User list_display = ['username', 'email', 'first_name', 'last_name','is_staff','custom_field'] # Register your models here admin.site.register(User, CustomAdmin) But if I use the admin page http://127.0.0.1:8000/admin/my_app/user/add/ then the user's custom field is blank. I have done the migration, so the field is in the data base. If I create the user in the django shell then the field gets populated, just not from the admin page. Is there something else I need to register? Do I need to create a custom form? How can I get the admin site to use the correct UserManager? -
What could be causing an if statement in a Django template to not change anything?
I am trying to display a message once the user presses the Close Listing on my webpage. Currently, nothing happens to the webpage when the button is clicked. How could I fix this and what is wrong? part of views.py #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q( user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True #what happens if listing is closed if closeListing == True: closeListingButton = False has_watchlists.delete() winner = max_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) else: return redirect('listing', id=id) part of listing.html <!--close listing code--> {% if closeListing == True %} <div>{{ closedMessage }} <br> {{ winner }} has won the auction! </div> {% endif %} -
News Feed hidden from users who aren't administrators
On my social media platform, the news feed (called post_list) seems to be hidden from any user that isn't an admin. Even when text is entered into the box and 'post' is pressed, the page refreshes but the text box isn't emptied and no posts appear belowhand. If I log in as an admin, the feed appears immediately and so do all the posts that I just posted from the non-admin account that didn't appear on the non-admin account. As shown here. I have just recently added the ability to share posts, so maybe that has influenced this issue in some manner. (The news feed) post_list.html: > {% extends 'landing/base.html' %} {% load crispy_forms_tags %} > > {% block content %} <div class="container"> > <div class="row justify-content-center mt-3"> > <div class="col-md-5 col-sm-12 border-bottom"> > <h5>Create a Post</h5> > </div> > </div> > > <div class="row justify-content-center mt-3"> > <div class="col-md-5 col-sm-12 border-bottom"> > <form method="POST" enctype="multipart/form-data"> > {% csrf_token %} > {{ form | crispy }} > <div class="d-grid gap-2"> > <button class="btn btn-light" style="background-color: #CC64C3; mt-3 mb-5">Post</button> > </div> > </form> > </div> > </div> > > {% for post in post_list %} > <div class="row justify-content-center mt-3"> > … -
Is it possible to deliver django toast messages via frontend
Tryna achieve sending notifications through Javascript logic instead of Django views, I want to replace alert() in this Javascript function with Django contrib messages(toasts). Something that would look like this in views messages.success(request, f"test successful") Is it possible to achieve the same thing with javascript? js function TestBtn(id) { alert("test successful"); } html <a onclick="TestBtn('btn');return false;"></a> -
How to get the value of or Parse HTML dropdown selected:option text as python variable in views.py in Django?
I have a 3 way dropdown list generated from 3 different tables linked via foreign keys. model.py is a follows #################################################################################### class State(models.Model): state_name = models.CharField(max_length=50, unique=True) state_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(100)]) class Meta: db_table = 'State_Names' def __str__(self): return self.state_name #################################################################################### class District(models.Model): state_name = models.ForeignKey(State, on_delete=models.CASCADE) state_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) district_name = models.CharField(max_length=50, unique=True) district_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(1000)]) class Meta: db_table = 'District_Names' def __str__(self): return self.district_name #################################################################################### class Block(models.Model): state_name = models.CharField(max_length=50) state_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) district_name = models.ForeignKey(District, on_delete=models.CASCADE) district_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) block_name = models.CharField(max_length=50) block_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(8000)]) class Meta: db_table = 'Block_Names' def __str__(self): return self.block_name views.py is as def get_state_district_and_block_string(request): if request.method == "POST": state_name_is=request.POST.get('state_dropdown') print("state_name_is", state_name_is) district_name_is=request.POST.get('district_dropdown') block_name_is=request.POST.get('block_dropdown') return render(request, 'index.html') Dropdown.html is as <div class="form-group"> <label for="state_dropdown">Select State</label> <select class="form-control" id="state_dropdown" name="state_dropdown" aria-label="..."> <option selected disabled="true" class="col-md-12 school-options-dropdown text-center"> --- Select State --- </option> {% for state in stateDetailsInDropdown %} <option class="col-md-12 school-options-dropdown text-center" value="{{state.state_name}}">{{state.state_name}} </option> {% endfor %} </select> </div> <div class="form-group"> <label for="district_dropdown">Select District</label> <select class="form-control" id="district_dropdown" name="district_dropdown" aria-label="..."> <option selected disabled="true" class="col-md-12 school-options-dropdown text-center"> --- Select District --- </option> {% for district in DistrictDetailsInDropdown %} <option class="col-md-12 school-options-dropdown text-center" value="{{district.state_name}}">{{district.district_name}} </option> {% endfor %} </select> … -
BadHeaderError("Header values can't contain newlines (got %r)" % value) in drf_social_oauth2
Describe the bug I got the access_token from google which I'm supposed to use to authenticate users. Everything works fine when the user is authenticating for the first time. But when the user logs out and tries to login again, it gives this wired error. This never happened when I was using the old gapi for login. I am currently using the new recommended GSI google provided. To Reproduce Steps to reproduce the behavior: Go to Google playground to get an access token Send the details to /auth/convert-token endpoint and make sure the user is registered in the database. Try sending the same credentials to the same endpoint. NB: it doesn't matter whether it's a new access_token. as long as it belongs to the same user, the error will be the response. Expected behavior A response with JSON data of tokens generated by the backend Screenshots A screenshot of the error in vscode thunder client. Django Version: 4.0.1 drf-social-oauth2: 1.2.1 Google Auth system: New Google Identity Services Additional context I used to work with the Old gapi.$Auth system. The issue appears to be coming from ConvertTokenView class in site-packages/drf_social_oauth2.py. When a user registers for the first time, these are the … -
Django Rest Framework Choices Field Serializer -- I'd like to get second element in a tuple
This is a model class BookModel(models.Model): """The model to represent books.""" class BookRating(models.IntegerChoices): AWFUL = 0, 'Awful' BAD = 1, 'Bad' NORMAL = 2, 'Normal' GOOD = 3, 'Good' GREAT = 4, 'Great' AWSOME = 5, 'Awesome' rating = models.PositiveSmallIntegerField(choices=BookRating.choices, null=True, blank=True) And this is a serializer Class BookSerializer(serializers.ModelSerializer): rating = serializers.ChoiceField(choices=BookModel.BookRating.choices, source='rating') class Meta: model = BookModel fields = '__all__' How do I serialize it properly in my case? I saw the answer here were we somone used a tuple of tuples and it worked with the logic I have, but idk how to do it when I use another class's choices for creating choices (sorry for tautology) -
Django Token Authentication doesn't work when I access to server via domain name
I have a Django application with token authentication and I serve it via Apache2. When I do my auth required requests to the server with the domain name it returns with 401 Unauthorized HTTP error. When I do it with ip:port, it returns success. Same token is sent to the server. What might cause that? May apache server be related to this? -
Django/Apache2 ALLOWED_HOSTS settings doesn't work
I have my ALLOWED_HOSTS configured as below in my settings.py file: ALLOWED_HOSTS = [ 'localhost', 'semanticspace.io', 'www.semanticspace.io' ] I also configured apache2 ServerName as below: ... ServerName semanticspace.io ServerAlias www.semanticspace.io ... Despite these, when I try to access my web page it gives this error: Invalid HTTP_HOST header: 'www.semanticspace.io'. You may need to add 'www.semanticspace.io' to ALLOWED_HOSTS. What might be the cause of that? -
Why am i having AttributeError: 'QuerySet' object has no attribute 'answer' on django serializer "PUT" method
I am trying to update the nested serializer in it but, it saying queryset has no attribute, this is the code below , please help out. Views.py class QuizQuestionDetail(APIView): def get(self, request, format=None, **kwargs): quizz = Question.objects.filter(id=kwargs['pk']) serializer = QuestionSerializer(quizz, many=True) return Response(serializer.data) def put(self, request, format=None, **kwargs): quizz = Question.objects.filter(id=kwargs['pk']) serializer = QuestionSerializer(quizz, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer.py class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = [ 'id', 'answer_text', 'is_right', ] class QuestionSerializer(serializers.ModelSerializer): answer = AnswerSerializer(many=True) class Meta: model = Question fields = ['id','quiz', 'title','answer', ] def create(self, validated_data): answers_data = validated_data.pop('answer') question = Question.objects.create(**validated_data) for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return question def update(self, instance, validated_data): answers_data = validated_data.pop('answer') answer = instance.answer.all() answers = list(answer) instance.quiz = validated_data.get('quiz', instance.quiz) instance.title = validated_data.get('title', instance.title) instance.save() for answer_data in answers_data: answer = answers.objects.get(pk=answer_data['id']) answer.answer_text = answer_data.get('answer_text', answer.answer_text) answer.is_right = answer_data.get('is_right', answer.is_right) answer.save() return instance -
List of forms in django
i'm trying to create a list of items that belong to a specific contract of a user in django. In this list, the user must be able to acces a form with all the items that belong to this specific contract, and edit their value. I've tried to use formsets, but the Items are not related to the contract, despite of a M2M field in the contract itself, so the error that i've been facing is: 'contract_generator.Item' has no ForeignKey to 'contract_generator.ClientContract'. The are the models that are in use: class ClientContract(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) original_contract = models.ForeignKey(Contract, on_delete=models.CASCADE, null=True, blank=True) contract_name = models.CharField(max_length=60) address = models.TextField(blank=True, null=True) # Value related information total_value = models.DecimalField(blank=True, null=True, max_digits=12, decimal_places=2) installments = models.IntegerField(null=True, blank=True) # Items and clausules of the contract items = models.ManyToManyField(Item, blank=True, null=True) clausules = models.ManyToManyField(Clausule, blank=True, null=True) def __str__(self): return self.contract_name class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item_name = models.CharField(max_length=90) item_type = models.CharField(max_length=90) item_value = models.FloatField(blank=True, null=True, max_length=12) item_qt = models.FloatField(blank=True, null=True, max_length=12) item_total = models.FloatField(blank=True, null=True, max_length=12) # Unity options METERS = 'MT' LITERS = 'LT' UNITY_CHOICES = [ (METERS, 'Meters'), (LITERS, 'Liters'), ] unity = models.CharField(choices=UNITY_CHOICES, default=METERS, max_length=20) def __str__(self): return self.item_name This is the … -
How can I quickly delete entries that should not exist in the database?
Imports entries from the old database. I download a specific object by name and these are objects taken from the old database. Now I check if such an object exists in the new database. There are, for example, 20 such old objects and 25 in the new base. How can I automatically remove these 5 objects from the new database? I tried something by using for e.g. obj = Model.objects.all() kr = Model.objects.filter(name=name).first() obj_list = [] for op in obj: if op in obj_list: continue else: obj_list.append(op) spec_list = [] for item in obj_list: if kr == item: continue else: spec_list.append(item) -
How can I get all Django groups and optionally get associated user record?
This should be pretty simple since it's very simple with pure SQL. I have the following query which gets exactly what I want in Django: SELECT auth_group.id, auth_group.name, auth_user.username FROM auth_group LEFT JOIN auth_user_groups ON auth_group.id = auth_user_groups.group_id LEFT JOIN auth_user ON auth_user_groups.user_id = auth_user.id WHERE auth_user.id = 3 OR auth_user.id IS NULL; How can I get this result using the ORM properly? -
How to stop the user from being able to submit all other Django forms once a specific form is submitted?
I am trying to create an e-commerce site (CS50 Project 2) that allows its users to make comments, bids, and add listing items to their watchlists. I want the user who created the listing to be able to close the listing so that the winner (highest bidder) is displayed and no other of the forms will work (I also want to delete the listing from the watchlist). Currently, when the user who created the listing closes the listing, it saves (because it is a Django model), but the forms do not disappear, the listing does not delete off the watchlist, and the messages do not appear. How do I fix this? (I think it has to do with the if statement.) views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) #code for comment and bid forms listing_price = listing.bid sellar = listing.user comment_obj = Comments.objects.filter(listing=listing) #types of forms comment_form = CommentForm() bid_form = BidsForm() #watchlist_form = WatchListForm() #closelisting_form = CloseListingForm() #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_object_or_404(CloseListing, Q( user=request.user) & Q(listing=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True … -
Django creating a new model for genre or include it in book model?
I have a book model and every book has a genre. I'm confused if 1) I should create a new Model for genre then create a many to one relationship between book and model..... or 2) should I just include genre as a field in the Book model? If I wanted to get all books for a specific genre would using 1) make the search faster/more efficient since I could get all the books associated with a genre object? Because If I use 2) I would have to filter through every book to see if it has the specified genre. -
display a json through a GET request in django permission denied
I'd like to display the contents of a JSON file through a GET request. In views.py I use a GET request to open data2.json. The file is in the same directory as views.py. But I get the following error: File "C:\Users\Kaik\Documents\djangoPractice\shopping_cart\api_app\views.py", line 134, in get with open(pdfPath2,"r") as file: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Kaik\\Documents\\djangoPractice\\shopping_cart\\api_app' [12/Jun/2022 11:14:04] "GET /study/data2.json HTTP/1.1" 500 90058 Here is the GET in views: from django.views import View from django.http import JsonResponse import json from shopping_cart import settings from .models import CartItem from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from . import studyduck_all from . import iniStudyduck from iniStudyduck import initiateDuck import os def get(self, request, pdfname): path = os.getcwd() pdfPath = os.path.join(path, 'api_app') pdfPath2 = os.path.join(settings.MEDIA_ROOT, 'textfile.txt') jsonData = '' with open(pdfPath2,"r") as file: jsonData = json.load(file) return JsonResponse(jsonData) Here is my SETTINGS: """ Django settings for shopping_cart project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # new from pathlib import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print("HERE IS THE BASE DIR ", BASE_DIR) … -
Geodjango: different geometry fields in a single leaflet map
I have two geometry fields in a model, a PointField and a PolygonField. class Site(models.Model): name = models.CharField(max_length=254) location = models.PointField(null=True, blank=True) surrounding_polygon = models.PolygonField(null=True, blank=True) When I load this model into a form, two maps appear, one for each geometry field. How can I put both the Point and Polygon in a single map on the form, and then save the information in their respective fields? I am using the leaflet map. -
Django simple upload function
Getting this error: Exception Type: AttributeError Exception Value: 'InMemoryUploadedFile' object has no attribute 'save' When trying to have a Django function as simple as: def upload(request): file = request.FILES["picture"] file.save("hello.png") return HttpResponse("done uploading") Note: I know there is a longer way to make this simple procedure but I need it for now to be as simple as this one -
Django intersection between two ranges of hours
I am trying to do an intersection between two ranges of hours. As an example let's say we have: current user interval -> 09:30 - 12:30 other user in database -> 10:30 - 14:30 What I am trying to do is actually have a match between my current interval and other users in the database, returning me not only the user BUT also an extra field "available: 2 hours" My code: related_users = UserProfile.objects\ .filter( Q(start_date="9:30") & Q(end_date="12:20") )\ .exclude(user_id=current_user_profile.id) How could I do this intersection? thanks -
bool object is not callable
I am trying to get the user order but I got the following error bool object is not callable. How can I solve this problem? django version 4.0.5 def shop(request , id): blog = Blog.objects.get(id = id) user = request.user if blog.number > 0 : if user not in blog.cart.all() : if request.method == 'POST' : try: orders = Order.objects.get(user = user , current=True) except: orders = Order.objects.create(user=user) orders.save() order = Order.objects.get(user = user , current=True) color = request.POST['color'] size = request.POST['size '] form = Num(request.POST) if form.is_valid(): num = form.cleaned_data['num'] nums = Num.objects.create(num=num , model=blog) item = OrderItem.objects.create(blog=blog , num=num , order=order , color=color , size=size) item.save() blog.number -= num blog.save() blog.cart.add(user) form = Num() return redirect('blog:detail' , id) return redirect('blog:list') -
Upload and process csv in Django
I want to upload a csv file in django. API enabled to receive a csv, clean and structure the data, and return it in the call. Have another API that says something interesting about the data it has received. Here the top 3 lines of the csv: enter image description here 2022-06-07 07:10:58.314000,"{""data"": {""Sensor settings"": null}, ""offset"": {""Sensor settings_offset"": null}}" 2022-06-07 07:15:58.495000,"{""data"": {""Co2"": 152, ""Light"": 200, ""Humidity"": 0.47, ""Temperature"": 27.4, ""Motion (PIR)"": 0}, ""offset"": {""Co2_offset"": 0, ""Light_offset"": 0, ""Humidity_offset"": 0, ""Temperature_offset"": 0, ""Motion (PIR)_offset"": 0}}" 2022-06-07 07:25:58.303000,"{""data"": {""Co2"": 166, ""Light"": 195, ""Humidity"": 0.48, ""Temperature"": 27.3, ""Motion (PIR)"": 8}, ""offset"": {""Co2_offset"": 0, ""Light_offset"": 0, ""Humidity_offset"": 0, ""Temperature_offset"": 0, ""Motion (PIR)_offset"": 0}}"