Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to form ORM queryset in Django
I am required to include a field present in a parent table to a grandchild table. I have to form a queryset to achieve the mentioned to return list of records for my mobile application. Refer below my models to have a clear picture. #models.py class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) contact = models.CharField(max_length=10, unique=True) email = models.EmailField(null=True) address = models.TextField() modified_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'clients' ordering = ['id'] verbose_name = 'Client' verbose_name_plural = 'Clients' def __str__(self): return str(self.id) + ". " + self.name class Rent(models.Model): id = models.AutoField(primary_key=True) address = models.TextField() rent_amount = models.IntegerField() deposit_amount = models.IntegerField() rent_date = models.DateField() document = models.TextField(null=True) remarks = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) client_id = models.IntegerField() class Meta: db_table = 'rent' verbose_name = 'Rent' verbose_name_plural = 'Rents' def __str__(self): return self.id def get_client_name(self): client = Client.objects.get(pk=self.client_id) return client.name class RentSchedule(models.Model): id = models.AutoField(primary_key=True) rent_due_date = models.DateField() paid_amount = models.IntegerField(default=0) remaining_amount = models.IntegerField() payment_status = models.IntegerField(choices=[(0, 'Unpaid'), (1, 'Paid')], default=0) created_at = models.DateTimeField(auto_now_add=True) rent_id = models.IntegerField() class Meta: db_table = 'rent_schedule' verbose_name = 'Rent Schedule' verbose_name_plural = 'Rent Schedule' def __str__(self): return self.id def get_client_name(self): rent = Rent.objects.get(pk=self.rent_id) client = Client.objects.get(pk=rent.client_id) return client.name … -
Azure Deployment - Server Error (500). Environmental Variables Error?
my azure environmental variables OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') This doesn't seem to be working for azure deployment? What other steps do I need to make to ensure my azure deployed website can access my openai api key? I have created a vector database driven website using django. I am able to run the webapp and perform searches using the api key on local host. I am able to do this while connected to the azure database. However, when I access my website through the public domain, I can't seem to perform searches. I've added the api key to the azure environmental variables already. It says Server Error 500 when I try to perform searches. Is there anything else I need to do? What could be causing server error 500? -
How do I reference the author name column from the Author table in my InsertBook function?
(https://i.sstatic.net/EiBqboZP.png) In the browser, I'm trying to add a new book to my books table but I keep receiving a Value error from django where for example I can't assign "'Virginia Woolf'": "Book.author" must be a "Author" instance. After I enter all the fields to add a new book and then click the Insert button in the browser, I receive the Value error. Below is the structure of my sql table as well as related python scripts for reference: --Create the books table CREATE TABLE books ( book_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, author_id INTEGER REFERENCES authors(author_id), genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), --Adding the column for the ISBN to populate the table with an extra instance isbn VARCHAR(20) ); --Create the videos table CREATE TABLE videos ( video_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), release_date DATE ); views.py: from django.shortcuts import render from bookstore.models import Author, Book from django.contrib import messages from bookstore.forms import Authorforms, Bookforms def index(request): return render(request, 'index.html') def author(request): allauthor=Author.objects.all() return render(request, 'author_list.html', {'authors': allauthor}) def Insertauthor(request): if request.method=="POST": if request.POST.get('author_id') and request.POST.get('name') and request.POST.get('birthdate') and request.POST.get('nationality'): saverecord=Author() saverecord.author_id=request.POST.get('author_id') saverecord.name=request.POST.get('name') saverecord.birthdate=request.POST.get('birthdate') saverecord.nationality=request.POST.get('nationality') saverecord.save() messages.success(request,'author … -
Django Logout request returning forbidden 403 CSRF related
from rest_framework import views, status from rest_framework.response import Response from django.contrib.auth import authenticate, login,logout from rest_framework.permissions import AllowAny, IsAuthenticated from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse class LoginView(views.APIView): permission_classes=[AllowAny] def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({'message': 'Logged in successfully'}, status=status.HTTP_200_OK) return Response({'message': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) class LogoutView(views.APIView): def post(self, request): logout(request) return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) @csrf_exempt def logoutView(request): print(request.COOKIES) logout(request) return JsonResponse({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) class UserInfoView(views.APIView): permission_classes=[IsAuthenticated] def get(self, request): user = request.user return Response({'username': user.username}, status=status.HTTP_200_OK) When sending request to login or userinfoview it works fine with csrf tokens. however the class LogoutView returns forbidden 403. The logoutView FUNCTION works fine ONLY when csrf_exmpt is applied. when printing request.cookies its returning: {'csrftoken': 'DdQZJC56QBSAcDqXVlrXz4mMeVWitpNV', 'sessionid': 'poul3qidl8xw4k5bp2rwazbxo76eq9sq'} which is what it returns in all the other classes as well. i tried to csrf exmpt the class because thats what i ultimitly want to use instead of the function for the cleaner looking code but couldnt figure out how to exmpt the class. moreover, i dont want to exmpt the csrf to begin with unless its the only solution. -
Why do I get the email but not the ID of the user in Django when using users_data = validated_data.pop(‘users’, [])?
I am working on a Django project and encountering an issue related to extracting user data in a serializer's create method. In the code, users_data contains email addresses of users, but I need to associate users with the task using their IDs instead. However, when I replace User.objects.get(email=user_data) with User.objects.get(id=user_data), I encounter an error. How can I modify my serializer's create method to correctly associate users with their IDs instead of emails? Any insights or suggestions would be greatly appreciated. Thank you! Here is a snippet of my code. Payload: { "id": null, "title": "Task Title", "description": "Task Description", "due_to": "2024-06-28T22:00:00.000Z", "created": null, "updated": null, "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "task_id": null, "description": "Subtask 1", "is_done": false } ], "users": [ 1 ] } class BaseTaskSerializer(serializers.ModelSerializer): """Serializes a task object""" subtasks = SubtaskSerializer(many=True, required=False) class Meta: model = Task fields = ['id', 'title', 'description', 'due_to', 'created', 'updated', 'priority', 'category', 'status', 'subtasks', 'users'] read_only_fields = ['created', 'updated'] def create(self, validated_data): #print('self: ', self) users_data = validated_data.pop('users', []) subtasks_data = validated_data.pop('subtasks', []) task = Task.objects.create(**validated_data) print(users_data) #print('validated_data', validated_data) #print('users_data', users_data) for user_data in users_data: #print(user_data) #print('users_dataaa: ', users_data) #user = User.objects.get(id=user_data) user = User.objects.get(email=user_data) task.users.add(user) for subtask_data in … -
Error in verify_key function from discord_interactions library for Python: Signature was forged or corrupt
I have this code snippet: def interactions_view(request): if request.method == 'POST': try: raw_body = request.body signature = request.headers.get('X-Signature-Ed25519') timestamp = request.headers.get('X-Signature-Timestamp') logger.debug(f"Signature (type: {type(signature)}): {signature}") logger.debug(f"Timestamp (type: {type(timestamp)}): {timestamp}") logger.debug(f"Raw Body (type: {type(raw_body)}): {raw_body}") if not signature or not timestamp: return JsonResponse({'Error': 'Missing signature or timestamp'}, status=400) try: verify_key(raw_body, signature, timestamp, PUBLIC_KEY) except Exception as e: logger.error(f"Signature verification failed: {e}") return JsonResponse({'Error': 'Signature verification failed'}, status=401) . . . And it returns this error on the server logs: 2024-06-29T22:14:41.227687+00:00 app[web.1]: Signature was forged or corrupt With a status code of 200 OK everytime Discord attempts to send it a POST request for verification (I want my server to be an interactions endpoint for a bot) I have tried decoding and encoding the keys to bites and strings and it returns different errors each time like "could not concatenate str object to bytes" and viceversa, among other things like debugging and capturing logging info as shown above, but nothing works. Can someone please tell me if I'm missing something? Or if I did something wrong? -
TypeError: 'staticmethod' object is not callable during Django migrations
When I run python manage.py migrate, I encounter the following error: File "/home/seyedbet/virtualenv/WanderSight/3.9/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) TypeError: 'staticmethod' object is not callable Django Version: 4.2, Python Version: 3.9 How can I resolve this? -
Static in django
How can I add a static template tag for this in Django?{% static %} <body style="background-image: url('path') "></body> I try this, but it does not work <body style="background-image: url('{% static "path" %} ') "></body> -
How to configure django templates and webpack
I am using a django project created by django-cookiecutter template.I want to use webpack to bundle my js files (normal js) and css files..previously I used django-compressor to compress css files. I am a newbie in webpack and I would like to ask the following direct questions How do I configure my entry point to include all static files How do I render bundled js files from form Media class I am seeing a substantial increase in js size from my browser network tab.(from 500b to 132kb for example)..Am I doing something wrong or is webpack meant for larger js files only.. Also webpack is not producing any bundle files on my output directory set although I can see bundled js served.Is this the intended behaviour. -
I'm trying to ensure that only the Person that will be at an Event will only be able to view the Events they're attending. How do I do this?
I'm using Django for the purposes of this project and I have a Many-to-Many relation between Person and Event (many people can be at many [existing] Events) and I want to make sure that each Person can only view the Events they're attending, not any other. I'm trying to do this through the admin panel with the use of has_view_permission, but I haven't a clue how to go on about this. I'm trying to use request.user for the purposes of this check. I know that using a through table with models.ForeignKey also works, but since Django already has that implementation invisible to the end user, I wanted to try this idea with a models.ManyToManyField. So far, I have this for my models.py: class Person(models.Model): # fields in the model such as id, name, etc. class Event(models.Model): # fields similar to Person - id, name, date, etc. attendees = models.ManyToManyField(Person) and for the admin.py from django.contrib import admin from .models import Person, Event class EventAdmin(admin.ModelAdmin): def has_view_permission(self, request, obj=None): if Event.objects.filter(attendees = request.user): return True else: return False However, as one might imagine, this disallows anyone but the people in events to actually view the events, thus giving me a ValueError … -
Add Payment Method on my SAAS using an API from local gateway
I have a SAAS program on Django and Python, that manage Clients accounts (one or many). As for now, we handle all payment manually, adding a new client manually to reoccurring monthly payment 3'rd party system For a client with many accounts we have a payment calculator and we charge the amount manually. The major issue we handle is that each month most of our clients have different payment cost, according to number of accounts running. we don't have Stripe here. So my Questions are of 2 types, the way to calculate the payments and the way to execute it. is it safe to add a payment gateway by a simple API, and handle the payment from the backend of the server side ? is it done with a cron job kind of tasker? this it the API: https://documenter.getpostman.com/view/16363118/TzkyNLWB how can I calculate the payment monthly, should I make a smart way to do it, are there more existing solution for the case ? for example an account was running 1.7-5.7 stopped and resumed in 15.7-30.7 is there an recommended algorithm for storing the data? We charge clients world wide. how to manage all payments ? how to enable more … -
Django CreateView get_context_context_data not passing additional object to template
I'm creating a forum app in django. A user can reply to a Thread by pressing a button. This takes them to a new page containing a form with a textbox to post their reply. The PK of the thread being replied to is passed it through the url and saved as the parent_post of the reply within the CreateView. This all works fine (so far...) but I also want to display the title of the thread that is being replied to at the top of the page, but I can't seem to be able to use this passed in pk to display the title of the thread at the top of the html page. URLS: path('reply/<int:pk>/', NewReplyView.as_view(), name='new-reply'), View: class NewReplyView(generic.CreateView): form_class = NewReplyForm initial = {'key': 'value'} template_name = 'forum_app/new_reply.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['x'] = "hahaaha" p = Post.objects.get(pk=self.kwargs.get('pk')) # Why does this not work, seems to work in the def post() method context['thread'] = p return context def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form':form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): submission = form.save(commit=False) submission.author = request.user submission.parent_post = Post.objects.get(pk=self.kwargs.get('pk')) submission.save() #return redirect(to='/') # TODO: redirect … -
Changes not being saved to user profile in Django
I'm having an issue with my Django application where changes are not being saved to a user's profile. I've created a form to edit the user's profile, but when I submit the form, the changes are not being saved to the database. Here's my code: views.py: def customerprofile(request): profile = get_object_or_404(Profile, user_name=request.user) if request.method == "POST": print(request.POST) # Check what data is being sent image = request.FILES.get("image") full_name = request.POST.get("full_name") phone = request.POST.get("phone") address = request.POST.get("address") country = request.POST.get("country") golden_user = request.POST.get("golden_user") == 'on' diamond_user = request.POST.get("diamond_user") == 'on' if image != None: profile.image = image profile.full_name = full_name profile.phone = phone profile.address = address profile.country = country profile.golden_user = golden_user profile.diamond_user = diamond_user try: profile.save() print("Profile saved successfully") # Check if the profile was saved messages.success(request, "Profile Updated Successfully") return redirect("useradmin:customerprofile") except Exception as e: print("Error saving profile:", e) # Check for errors context = { "profile":profile, } return render(request, 'useradmin/customerprofile.html', context) customerprofile.html: {% load static %} {% block content %} <div class="container mt-4"> <div class="card"> <div class="card-header"> <h2 class="card-title">Edit Profile</h2> </div> <div class="card-body"> <form method="post" enctype="multipart/form-data" id="profileForm"> {% csrf_token %} <div class="row"> <div class="col-md-6 text-center"> <img id="imagePreview" src="{% if form.instance.image %}{{ request.user.Profile.image.url }}{% else %}https://static.vecteezy.com/system/resources/thumbnails/009/292/244/small/default-avatar-icon-of-social-media-user-vector.jpg{% endif %}" alt="Preview" … -
Django static files not working on cpanel
my settings.py static settings are STATIC_URL = 'static/' STATIC_ROOT = '/home/mywebsite/public_html/dj/static/' I have run: manage.py collectstatic successfully I restarted the app. But when i hit the URL http://mywebsite/admin there is no CSS. Maybe there's something to do with .htaccess somewhere. I need help -
getting NoReverseMatch error even after correct urls and views
getting the error message of NoReversedMatch even after creating path in urls.py and function in views.py when i type url manually its working properly so the path is not wrong pleaze someone help me NoReverseMatch at /mcq_web/ Reverse for 'quizes' not found. 'quizes' is not a valid view function or pattern name. the html where it is giving error is href = "{% url 'quizes' quiz_type.id %}" here is my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.show_quiz, name="quiz_show"), path('add/',views.add_user, name ="new user"), path('show_quiz/', views.show_quiz, name="quiz_types"), path('<int:quiz_type_id>/quizes/', views.quizes, name="ShortedQuizTypes"), ] this is my views.py part to that error def quizes(request,quiz_type_id): quiz_type = get_object_or_404( Quiz_types,pk = quiz_type_id) quizes = quiz_data.objects.all() quiz_types = Quiz_types.objects.all() details = {'quiz':quizes,'quiz_type':quiz_type,'quiz_types':quiz_types} return render(request,'shorted_show_quiz.html',{'details':details}) just in case this is my whole views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import quiz_data,quiz,quiz_history,Quiz_types,options,user from .forms import user_form # Create your views here. # function to show quiz by type def quizes(request,quiz_type_id): quiz_type = get_object_or_404( Quiz_types,pk = quiz_type_id) quizes = quiz_data.objects.all() quiz_types = Quiz_types.objects.all() details = {'quiz':quizes,'quiz_type':quiz_type,'quiz_types':quiz_types} return render(request,'shorted_show_quiz.html',{'details':details}) # function to add new users def add_user(request): if request.method == 'POST': form = user_form(request.POST) if form.is_valid: form.save() … -
How do i record an audio in .wav file format that would meet the standard of Google Speech To Text API in React Native Expo
I have a function that starts and stops recordings, when the recording stops, i can playback the recording and everything works well, but whenever I upload the audio file to Google for transcription, I get an empty response. But when i upload another .wav file (downloaded online, not the recording). I get the transcription of that audio. const startRecording = async () => { try { console.log("Requesting permissions.."); const { status } = await Audio.requestPermissionsAsync(); if (status !== "granted") { alert("Sorry, we need audio recording permissions to make this work!"); return; } console.log("Starting recording.."); await Audio.setAudioModeAsync({ allowsRecordingIOS: true, playsInSilentModeIOS: true, }); const { recording } = await Audio.Recording.createAsync({ android: { extension: ".wav", outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT, audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, }, ios: { extension: ".wav", audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, linearPCMBitDepth: 16, linearPCMIsBigEndian: false, linearPCMIsFloat: false, }, }); setRecording(recording); } catch (err) { console.error("Failed to start recording", err); } }; const stopRecording = async () => { console.log("Stopping recording.."); if (recording) { await recording.stopAndUnloadAsync(); const uri = recording.getURI(); setRecording(null); uploadAudio(uri); } }; function getOtherUser(data, username) { if (data.receiver.username !== username) { return data.receiver; } if (data.sender.username !== username) { return data.sender; } return null; } … -
ModuleNotFoundError: No module named 'walk.myadmin'
I am trying to import my myadmin models into shoppingapp when I am getting error from walk.myadmin.models import Order I am trying this code and getting error when also I tried this one from myadmin.models import Order but same error I am expecting to import my models from one app to another in the same project. -
Django Template Not Displaying Vendor Contact and Description Fields
I'm working on a Django project where I have a Vendor model. The goal is to display the vendor's profile, including their contact information and description, on a profile page. However, the contact and description fields are not displaying in the template. Here is my Vendor model definition: class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") cover_image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=RichTextUploadingField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title Here is the view function that retrieves the vendor profile: def shop_page(request): products = Vendor.objects.all() revenue = CartOrder.objects.aggregate(price=Sum("price"))["price"] total_sales = CartOrderItems.objects.filter(order__paid_status=True).aggregate(qty=Sum("qty"))["qty"] context = { "products": products, "revenue": revenue, "total_sales": total_sales, } return render(request, "useradmin/shop_page.html", context) Here is the template shop_page.html: {% load static %} {% block content %} <style> body, html { height: 100%; margin: 0; } .container-fluid { height: 100vh; display: flex; justify-content: center; align-items: center; } .profile-card { border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #ffffff; overflow: hidden; } .card-header { background-color: #007bff; color: #fff; padding: 20px; border-bottom: none; } .card-title { font-size: 2rem; font-weight: 700; margin: 0; } .card-body { padding: 30px; } .profile-image { max-width: 200px; height: … -
Frustrating Cors problem between django and react js
So hello everyone, I am working on a project which have django as the api and react js as the frontend, but i am getting this annoying cors error no matter what i do to fix it. I have tried everything and every solution i've found maybe i am doing smtg wrong but one think i can addon is that get works perfectly like expected but not post your help is much appreciated . thanks Access to fetch at 'http://localhost:8000/Chercheur/Add' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. Django side Settings.py : """ Django settings for API project. Generated by 'django-admin startproject' using Django 5.0.6. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-i*mo_5h-6v5fi_$pxy3%-acy22u4_c9vm9+a@84j^(nl&hw@ae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Django OperationalError: MySQL Connection not available
I am encountering an issue while trying to connect my Django project to a MySQL database hosted on cPanel using "mysql-connector-python". Despite configuring the settings correctly, I consistently receive an OperationalError: MySQL Connection not available when attempting to run my Django application. Database Settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'the name', 'USER': 'the user', 'PASSWORD': 'the pass', 'HOST': 'localhost', 'PORT': '3306', } } I am using mysql-connector-python version 8.4.0 to connect to the MySQL database. Verified database credentials and ensured they match those configured in cPanel. Checked MySQL server status and confirmed it is running without issues. Error Message: django.db.utils.OperationalError: (-1, 'MySQL Connection not available.', None) The Django application and MySQL database are hosted on separate servers, with cPanel managing the MySQL instance. The MySQL user has been granted all privileges (ALL PRIVILEGES) for the specified database. -
Serving media files in Django using whitenoise for simple blog application
I am building a simple blog application where only I would be uploading the images and text of the blog from admin dashboard. I used whitenoise in production, with static files like css js and logo images etc. were loading correectly, but the media files of the blog were not being served. I explore the web and got to know that due to security considerations, static files and media files are separated with media files being loaded from storage services like S3 bucket etc. But in my case, only me, not any external user would be uploading the images for the blog from admin dashboard, so the security risk doesn't seem to apply here. (correct me if I am wrong here). So, to serve the media files from whitenoise what I did was to make static root and media root as same location, and used {% static %} to serve the blog images instead of media url. Now the application is working as it should, but I am concerned whether this approach is suitable in the long run or not. Please advise if there is any downside of using this approach for simple application like blogging websites. -
Admin page not found (404) in Django project?
I'm using a shared hosting with cPanel but without Terminal access. It was hard to find tutorial for this situation. After struggling to make it work. The website shows the home page at : https://mywebsite.com but not found (404) for the url: https://mywebsite.com/admin or https://mywebsite.com/admin/ I didn't touch anything in urls.py. The homepage is showing the famous green rocket and the message "The install worked successfully! Congratulations!" What I did is to run manage.py migrate and collectstatic and set STATIC_ROOT = 'home/mywebsite/dj/static/' in setting.py. But all of the above haven't improve the situation. Feel free to edit or improve the title of my question. -
Is it possible to change the url in view (Django) after a certain operation?
Let's say there is a page of a separate blog article with this url (aviary-ensemble is the slug of the article): http://127.0.0.1:8002/articles/article/aviary-ensemble/ Now I'm making a comment system and the form for writing a comment is on the same page. The view for creating a new comment I have formalized as follows: if there is no submitted data, then load the page, if there is - then based on this data create a comment and load the page. def details(request, slug, author=None): article = models.Article.objects.get(slug=slug) print(author) if request.method == 'POST': if author is not None: user = User.objects.get(username=author) print(user.username, type(user)) comment_author = UserProfile.objects.get(user=user) comment = request.POST['comment_area'] if comment[0] == '@': receiver = comment[1:].split(', ')[0] comment_text = comment[1:].split(', ')[1] models.Comment.objects.create(article=article, author=comment_author, receiver=receiver, text=comment_text) else: models.Comment.objects.create(article=article, author=comment_author, text=comment) article_comments = models.Comment.objects.filter(article=article) context = { 'article': article, 'article_comments': article_comments } return render(request, 'articles/article.html', context=context) else: article.views = article.views + 1 article_comments = models.Comment.objects.filter(article=article) context = { 'article': article, 'article_comments': article_comments } return render(request, 'articles/article.html', context=context) I set the url itself as follows: urlpatterns = [ path('', views.index, name='articles_catalog'), path('article/<slug:slug>/<str:author>/', views.details, name='comment_creation'), path('article/<slug:slug>/', views.details, name='details'), ] The nuance is that after submitting the form the url changes to http://127.0.0.1:8002/articles/article/aviary-ensemble/admin/ (admin is the username of … -
Why can I not drill down a model to get to a field?
I have this contestant model: class Contestant(models.Model): GENDERS = [ ("male", "Male"), ("female", "Female") ] EYE_COLORS = [ ("brown", "Brown"), ("blue", "Blue"), ("green", "Green"), ("hazel", "Hazel"), ("amber", "Amber"), ("gray", "Gray") ] HAIR_COLORS = [ ("black", "Black"), ("brown", "Brown"), ("blonde", "Blonde"), ("red", "Red"), ("gray", "Gray"), ("white", "White"), ("pink", "Pink"), ("purple", "Purple"), ("green", "Green"), ("orange", "Orange") ] main_photo = models.FileField(upload_to='main_image/') first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender = models.CharField(max_length=8, choices=GENDERS) height = models.IntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(120)]) weight = models.IntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(1500)]) eye_color = models.CharField(max_length=20, choices=EYE_COLORS) hair_color = models.CharField(max_length=20, choices=HAIR_COLORS) city = models.OneToOneField(City, on_delete=models.DO_NOTHING, related_name="contestant") user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="contestant_profile") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "contestant" verbose_name_plural = "contestants" db_table = "contestants" def __str__(self): return f"contestant {self.user}" and I want people to vote on the contestant. Here is the votes model: class ContestantVote(models.Model): contestant = models.ForeignKey(Contestant, on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="votes") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = (("contestant", "user"),) verbose_name = "vote" verbose_name_plural = "votes" db_table = "votes" def save(self, *args, **kwargs): if ContestantVote.objects.filter(contestant=self.contestant, user=self.user).exists(): raise ValidationError(f'User {self.user} has already voted for contestant {self.contestant}.') if … -
Password field in Signup/Login form not appearing properly | Django | HTML | Bootstrap
I am trying to create a custom signup form using HTML, CSS, Bootstrap as front end, and Django as backend, when I create the form, firstname, lastname, and email are appearing as required, but the password and confirm_password fields are not appearing as required, from forms.py, the widget's placeholder and class=form-control is also not being applied to it. I asked ChatGPT, it is asking to clear Cache, switching to incognito or a different browser, I tried all things, and still it is appearing the same. I am providing all the files associated with the signup form I created. models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name=None, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set.') if not first_name: raise ValueError('The First Name field must be set.') if not password: raise ValueError('Password cannot be left blank.') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.email forms.py from django import forms from django.contrib.auth.forms import …