Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to route to test pages using Wagtail Factories and Factory Boy
I'm trying to implement factory boy and wagtail factories to generate tests for the blog section of my site, at /blog/, which uses Wagtail CMS. However, I'm getting a 404 error when doing self.assertPageIsRoutable on the BlogIndexPage and CategoryIndexPage. I'm creating a Site. The root of the site is set to BlogIndexPage, then CategoryIndexPage is created as a child of BlogIndexPage. To my knowledge, wagtail_factories.PageFactory handles the creation of nodes and parents. Factory class BlogIndexPageFactory(wagtail_factories.PageFactory): title = "Blog Index" intro = "Welcome to the Blog" slug = "blog" class Meta: model = models.BlogIndexPage class CategoryIndexPageFactory(wagtail_factories.PageFactory): title = factory.sequence(lambda n: f"Category {n}") intro = factory.sequence(lambda n: f"Welcome to Category {n}") class Meta: model = models.CategoryIndexPage class BlogPageFactory(wagtail_factories.PageFactory): class Meta: model = models.BlogPage class SiteFactoryDefault(wagtail_factories.SiteFactory): is_default_site = True root_page = factory.SubFactory(BlogIndexPageFactory) Test class TestBlogIndex(WagtailPageTestCase): @classmethod def setUpTestData(cls): cls.site = SiteFactoryDefault.create() cls.index = cls.site.root_page cls.categories = CategoryIndexPageFactory.create_batch(4, parent=cls.index) def test_can_create_child(self): assert CategoryIndexPage.can_create_at(self.index) def test_category_route(self): for category in self.categories: self.assertPageIsRoutable(category) Trace FAIL: test_category_route (blog.tests.TestBlogIndex) ---------------------------------------------------------------------- Traceback (most recent call last): File "\venv\lib\site-packages\wagtail\models\__init__.py", line 1664, in route subpage = self.get_children().get(slug=child_slug) File "\venv\lib\site-packages\django\db\models\query.py", line 650, in get raise self.model.DoesNotExist( wagtail.models.Page.DoesNotExist: Page matching query does not exist. During handling of the above exception, another exception occurred: Traceback … -
How to troubleshoot AWS Elastic Beanstalk Django Deployment getting 504 Gateway Timeout
I have created a Django site on AWS and the main page will work and the Admin page will work. Any attempt to link to anything else results in a Gateway Timeout 504 error. I think it is similar to this unanswered post: Elastic Beanstalk 504 Gateway Timeout Error - Django The site was created using a PostGres DB following the W3 Schools tutorial - https://www.w3schools.com/django/django_deploy_provider.php Everything works great locally. I can even read from the AWS RDS locally. I have the requirements.txt file and a django.config file in the .ebextensions folder. It seems like the app cannot get data from the DB but I have no knowledge of how to troubleshoot what is happening. If someone can point me to a log or an idea to check I would appreciate it. -
How to change the font in CSS upon changing the language selection in Django's i18n?
I built a webpage using Django and set up the changing of languages with the internationalization that was built for Django called i18n. I have no problem with the language or translation locale between English (en) and Traditional Chinese (zh-hant). But I am confused as to where I can change the font-family and font-size in CSS in the event the language is switched. base.html {% load static %} <!DOCTYPE html> <html lang="zxx"> ... <link rel="stylesheet" href="{% static 'css/style.css' %}"> ... </html> style.css @import url('https://fonts.googleapis.com/css2?family=Quantico:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap'); :root { --heading-font: "Quantico", "Microsoft YaHei New", "Microsoft YaHei";; --body-font: "Inter", sans-serif; --body-font-size: 16px; } :lang(zh-hant) { font-family: "Microsoft YaHei New", "Microsoft YaHei"; font-size: 120%; } Putting the YaHei font (or other Chinese character fonts) in :root {...} or in :lang(zh-hant) {...} both do not work in changing the font upon changing the language to zh-hant. I realize that the language for each tag is defined in the beginning of the base.html where "lang=zxx" and this does not change upon i18n changing of URLs to 127.0.0.1:8000/zh-hant/ from 127.0.0.1:8000/en/ which is why :lang(zh-hant) {...} does not work. Please advise. Thank you. -
Django app on Heroku: TemplateDoesNotExist error despite successful local deployment
I have encountered an issue with my Django app and despite looking at similar posts on this topic, I haven't been able to find a solution that works for me. I'm currently working on my first Django app, a project called "Learning log" based on the "Python Crash Course" book. I followed the instructions in the book, but when I try to access my app on Heroku, I receive a TemplateDoesNotExists error. However, everything seems to work fine when I run the app locally. Error message: TemplateDoesNotExist at /users/register/ registration/register.html Request Method: GET Request URL: https://guarded-citadel-16510.herokuapp.com/users/register/ Django Version: 4.1.7 Exception Type: TemplateDoesNotExist Exception Value: registration/register.html Exception Location: /app/.heroku/python/lib/python3.11/site-packages/django/template/loader.py, line 19, in get_template Raised during: users.views.register Python Executable: /app/.heroku/python/bin/python Python Version: 3.11.2 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python311.zip', '/app/.heroku/python/lib/python3.11', '/app/.heroku/python/lib/python3.11/lib-dynload', '/app/.heroku/python/lib/python3.11/site-packages'] Server time: Fri, 31 Mar 2023 17:37:57 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /app/learning_logs/templates/registration/register.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/registration/register.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.11/site-packages/bootstrap4/templates/registration/register.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.11/site-packages/django/contrib/admin/templates/registration/register.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.11/site-packages/django/contrib/auth/templates/registration/register.html (Source does not exist) Even though I have stored my template in the path "/app/users/templates/registration/register.html" and Django attempted to access it from that location, … -
Django cannot unpack non-iterable NoneType object
I was trying to substitute a custom user model. I did it based on Django's documentation. I don't know what I did wrong though. Everything seems to work fine. I can use createsuperuser and see Users page. But when I go to ADD USER in Django's admin panel, I get this error: TypeError at /admin/accounts/user/add/ cannot unpack non-iterable NoneType object models.py: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email address", max_length=255, unique=True) phone_number = models.CharField(max_length=11, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "phone_number" REQUIRED_FIELDS = ["email",] objects = UserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin forms.py: class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput) class Meta: model = User fields = ("email",) def clean_password2(self): # ... def save(self, commit=True): # ... class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = User fields = (#...) admin.py: class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = (# ...) list_filter = (# ...) fieldsets = ( (None, {"fields": (# ...)}), ("Permissions", {"fields": (# ...)}), ) add_fieldsets = ( None, {"fields": ("phone_number", "email", "password1", "password2")}, ) search_fields = ("email", "phone_number") ordering = ("email",) filter_horizontal = () admin.site.register(User, UserAdmin) admin.site.unregister(Group) -
redirecting the website to =/ page somehow
I am building a crm app for learning purposes of django. I do not how the page redirects to /=/ page when I insert random username and pass that does not exist Using the URLconf defined in djangoCRM.urls, Django tried these URL patterns, in this order: admin/ [name='home'] The current path, =/, didn’t match any of these. this is my views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages def home(request): # Check to see if logging in if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] # Authenticate user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, "You Have Been Logged In!") return redirect('home') else: messages.success(request, "There Was An Error Logging In, Please Try Again...") return redirect('home') else: return render(request, 'home.html') def logout_user(request): pass and my base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django CRM</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous"> </head> <body> {% include 'navbar.html' %} <div class="container"> <br/> {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} {% … -
Standalone Django REST API and React webapp structure and data persistency
I want to make a small webapp - where you can upload (and save to AWS) images with some connected properties (like name, date, etc) and an image gallery where you can view the images - and I was wondering how to structure the components best. Here's what I had in mind: Backend: A standalone Django REST API which handles: Image upload Saving images to AWS Retrieving images from AWS Frontend: Here I'm not sure what the best structure is, but a React based frontend which handles: General UI stuff Getting latest images from Backend Showing image gallery I also want to create docker images from both the front-, and backend so they can be deployed separately. Questions How is a standalone React frontend built? The examples I saw regarding Django+React they always were one project and Django handled most of the logic/data and rendered templates that React could show. In my case, for a standalone frondend should I follow that patter, to have a very simple Django part that communicates with the backend and populates data which the React can use for the actual GUI? Or is it supposed to be "pure" React project? (BTW, I'm more familiar with … -
Django change path of image uploads in CKEeditor field
I am using django-ckeditor_5 and currently the richtext field using CKEeditor is uploading images to the media folder. Since this won't work in production with Whitenoise handling static files, I am attempting to change the upload path to the static folder. So far I have not been able to figure out how to get this to work. My relevant settings.py file settings are: STATIC_ROOT = BASE_DIR / "static" STATIC_URL = '/static/' STATICfILES_DIRs = [str(BASE_DIR.joinpath('static'))] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'uploads/' Changing the CKEDITOR_UPLOAD_PATH does not seem to have an effect on where images are uploaded. -
django model object inside container remove wrapping
How can I remove the wrap aroud each objects model ? I want only a big div box container ? I dont want the "grey space" beetween them. I tried moving the tag {% for listing in listings %} but it didnt work html <div class="col-lg-9"> <div class="row"> {% for listing in listings %} <div class="col-md-6"> <div class="right-container"> <div class="property-grid-1 property-block bg-white transation-this hover-shadow"> <div class="overflow-hidden position-relative transation thumbnail-img bg-secondary hover-img-zoom"> <div class="cata position-absolute"> <span class="featured bg-primary text-white">Disponible</span> </div> <a href="/proprietes/{{listing.listing_address_url}}"><img src="{{listing.listing_first_image}}" alt="Image Not Found!" style="max-width: 416px; max-height: 300px; width: 416px; height: 300px"></a> </div> <div class="property_text p-4"> <div class="property_text_inner"> <span class="listing-price">{{listing.listing_price_str}}<small></small></span> <h5 class="listing-title" style="margin-left: -15px"><a href="/proprietes/{{listing.listing_address_url}}">{{listing.listing_type}}</a> </h5> <span class="listing-location"><i class="fas fa-map-marker-alt"></i> {{listing.listing_address}}</span> </div> <ul class="d-flex quantity font-fifteen"> <li title="Beds"><span><i class="fa-solid fa-bed"></i></span>{{listing.listing_chambre}} </li> <li title="Baths"><span><i class="fa-solid fa-shower"></i></span>{{listing.listing_nb_salle_de_bain}} </li> <li title="Area"><span><i class="fa-solid fa-vector-square"></i></span>{{listing.listing_superficie_terrain_value}} </li> </ul> </div> </div> </div> </div> {% endfor %} </div> </div> -
Django - NGINX and uwsgi not working with static files
it's been 2 days I've been looking for an answer to my problem but none of the answers worked for me. I'm trying to deploy a POC Django web app, and until I had DEBUG=True everything was great. Then I decided to get ready for deployment and I added a proxy NGINX to serve the static content and uwsgi as server. I have been following different guides and I thought I understood what was happening, but no static content is being served and my admin panel is HTML only. Can someone please have a look at this and explain what I'm doing wrong? This is my project Dockerfile: FROM python:3.11-slim-bullseye ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apt-get update && \ apt-get install -y build-essential libmariadb-dev gcc && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ my-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R my-user:my-user /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER my-user CMD … -
How to navigate to a different page for a simple django application in Shopify App iFrame
Hello I am trying to create a Shopify Django application. I have created a page which list sets of Magic: the Gathering. I want to be able to click a set to be taken to a page that displays more details of that set. The set page is has the following URL: https://admin.shopify.com/store/{store name}/apps/{app name}/magic/sets/ This page loads as expected and I am able to use the functionality on this page such as searching for a set. However when I click on a set it doesn't navigate to set details page. The html code for this in <a class="" href="{{ set_code }}/">...</a> which should add the set code to the end of the URL. If I type the URL manually it works as expected and the set details page loads. I am using ngrok to create the tunnel between Shopify and my dev environment so I can view the application in the Shopify Admin UI, but I don't know why is not navigating properly when using the link in the iframe. Is there a specific way navigation should be done in the iframe -
Handling mail verification using dj-rest-auth
I am able to get a verification email to the newly signed up email account. I also can verify the new email but not directly from the link sent in the email. The reason that is the confirmation link should be called with a post method, as mentioned in the documentation. My urlpatterns list in url.py file has the two elements below: urlpatterns = [ ..., ..., path('registration/', RegisterView.as_view(), name='account_signup'), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent') ] For information I am using Django as backend with a frontend framework. What I want is for the email verification to redirect to a page in the Frontend and from there send the post request. Is there a way to achieve this ? How to send custom email ? how to have a custom register and confirm email view ? -
ModuleNotFoundError in python 3 - django
I have below directory structure --sample-django <base directory> - scripts <sub directory> - run_scripts.py - utilities <sub directory> - __init__.py - methods.py ---------------------------------------------- run_scripts.py from utilities.methods import get_name def main(): print(get_name()) main() ----------------------------------------------- When I run the run_scripts.py, I get the below error from utilities.methods import get_name ModuleNotFoundError: No module named 'utilities' I tried to add sys.path and also PYTHONPATH but did not solve my problem. Please help me to resolve this issue. sys.path.append('/Users/projects/sample-django/utilities') -
Django datetime field prints out unsupported operand type error
I have a @property in my django model which prints out True or False based on datetime difference. Even though it works when I am unittesting it I get error TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' class MyModel(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) @property def is_expired(self): if datetime.now(tz=utc) - self.created_at > timedelta(hours=48): return True return False How do I fix this? Every answer I checked does not help me . -
How can I ensure that these radio buttons are treated as sepereate groups?
In this form, I'm looping through a number of forms generated to give feedback for an assignment, where each form is representing one criteria in a rubric style marking grid. In this case the crtieriaLevelID being fetched is represented as a radioSelect, allowing the user to select which level the student meets a criteria to, however I have run into the issue of all the generated radio buttons being treated as a single group. I know that radio buttons are grouped by the 'name' attribute in html and I've tried overriding the name using the attributes of the widget, but I don't seem to be able to change it like this at all, so I'm wondering if the issue is in the view code somewhere? class FeedbackForm(forms.ModelForm): #forms.py class Meta: model = Feedback fields = ['submissionID','criteriaLevelID', 'comment'] widgets = { 'submissionID' : forms.HiddenInput(), 'criteriaLevelID':forms.RadioSelect(attrs={'name':'test'}), #createFeedback.html <form method="post"> {% csrf_token %} <table> <thead> <tr> <th>Criteria</th> <th>Criteria Level</th> <th>Comment</th> </tr> </thead> <tbody> {% for feedbackForm in feedbackForms %} <tr> <td>{{ feedbackForm.description}}</td> <td>{{ feedbackForm.form.criteriaLevelID | as_crispy_field}}</td> <td>{{ feedbackForm.form.comment | as_crispy_field}}</td> </tr> {% endfor %} </tbody> </table> <button class= "btn btn-primary"type="submit">Save Feedback</button> </form> #views.py def feedbackCreateView(request, pk): submission = Submission.objects.get(id=pk) assignment = submission.assignmentID criteria … -
The Term 'Source' is not Recognized
**source newenv\ben\activate** source : The term 'source' 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 + source newenv\ben\activate + ~~~~~~ + CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Been trying to install Django python env via virtualenv newenv and tried to activate the environment with Source newenv\ben\activate and I get this error which I do not know how to fix. many thanks. -
child template is not getting displayed in a correct way in template in django
I have created two templates in django project named (index.html) and (first.html). I extended the parent template (index.html) in the child template (first.html) using {% extends %}. But , I am not able to display the content of child template in a correct way. Parent template is overriding the child template body contententer image description here index .html >> parent template <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}Contact book {% endblock %}Title</title> <link type="text/css" rel="stylesheet" href="{%static 'css/style.css' %}" /> <link type="text/css" rel="stylesheet" href="{%static 'css/bootstrap.min.css' %}" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400" rel="stylesheet"> <!--<img class="contact_book" src="{% static 'img/contact_book.jpg' %}" alt="first" /> --> </head> <body> <nav> <ul class="nav"> <li><a href="#">Home</a></li> <li><a href="#">About me</a></li> <li><a href="#">Contact</a></li> <li style="float:right"><a href="#">Login</a></li> <li style="float:right"><a class="active" href="#about">Sign up</a></li> </ul> </nav> <main> {% block content %} {% endblock %} </main> </body> </html> child template (first.html) The child template (first.html) code is below {% extends 'index.html' %} {% load static %} <main> {% block content %} <div class="container"> <div class="row"> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone … -
When i try to send post request I get error 403
When I try to add an image to the backend using the form with post request, I get a 403 error. I don't know where I made a mistake so I give a link to the github repository https://github.com/Cichyy22/imagur-like-site -
Error when using form.changed_data, "argument of type 'cached_property' is not iterable"
When trying to check if the "author" field has changed I keep getting the error "argument of type 'cached_property' is not iterable". form.py class BookForm(forms.ModelForm): class Meta: model = Product fields = '__all__' **def clean(self): if 'author' in BookForm.changed_data and Book.objects.filter(author=self.cleaned_data['author'], title=self.cleaned_data['title'], genre=self.cleaned_data['genre']).exists(): raise ValueError("Author, title and genre must not be repeated")** models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) admin.py class ItemInline(admin.StackedInline): model = ProductIndex extra = 0 @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'genre', 'price', 'quantity', 'is_available'] list_filter = ['genre', 'is_available'] search_fields = ['title'] exclude = ['popularity'] inlines = [ItemInline] form = BookForm Please point out the error or indicate another alternative to check if the field has changed -
Django Manager-Employee relation
I need some support for this problem i'm facing right now. I created a django app that allows a user(Manager) to register, the user(Manager) can then log in and create accounts for the Employees, they receive an email to set a password, and then can log in, having limited accesibility to the platform. So far I managed to have the manager be able to, edit, activate-deactivate the employee account and even delete it, but there is no relation between the users. If I log in with 2 manager accounts, they both can see all the employee accounts in my employee_list. how can I create a OneToOne relation between the manager and employee so that the manager who created his employee accounts can see them. class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField(default=True) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) manager = models.ForeignKey(User, related_name='employees', on_delete=models.CASCADE) is_employee = models.BooleanField(default=True) def __str__(self): return self.user.username so far this is what I came up with Any help will be so much appreciated. -
ImproperlyConfigured at /watchlist-detail/1 Could not resolve Url for hyperlinked relationship
from .models import WatchList,StreamPlatform from rest_framework import serializers class WatchListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=WatchList fields='__all__' class StreamPlatformSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=StreamPlatform fields='__all__' urls.py file from django.urls import path from . import views urlpatterns = [ path("",views.WatchListAV.as_view()), path("watchlist-detail/<int:pk>",views.WatchListDetailsAV.as_view()), ] views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from .models import WatchList,StreamPlatform from .serializers import WatchListSerializer,StreamPlatformSerializer from rest_framework import status # Create your views here. class WatchListAV(APIView): def get(self,request): # print(self) # print("1") movies=WatchList.objects.all() # print("1") serializer=WatchListSerializer(movies,many=True,context={'request': request}) print(request) # print(serializer.data) return Response(serializer.data) def post(self,request): serializer=WatchListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) class WatchListDetailsAV(APIView): def put(self,request,pk): try: movies=WatchList.objects.get(pk=pk) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer=WatchListSerializer(movies,data=request.data) print("1") if serializer.is_valid(): print("2") serializer.save() return Response(serializer.data) return Response({"error":"Data invalid format"},status=status.HTTP_400_BAD_REQUEST) def get(self,request,pk): try: movie=WatchList.objects.get(pk=pk) except WatchList.DoesNotExist: return Response({'error':"movie not found"},status=status.HTTP_404_NOT_FOUND) serializer=WatchListSerializer(movie,context={'request': request}) print(request) return Response(serializer.data) def delete(self,request,pk): movie=WatchList.objects.get(pk=pk) movie.delete() return Response(status=status.HTTP_404_NOT_FOUND) models.py from django.db import models # Create your models here. class WatchList(models.Model): title=models.CharField(max_length=50) storyline=models.CharField(max_length=200) active=models.BooleanField(default=True) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title i am beginner and i am unable to understand this error.i have searched for solution at different places but not found any solution. I am getting this error. "ImproperlyConfigured at / Could not resolve URL for hyperlinked relationship using … -
How to integrate React with Django api
I started a React project with npm run vite@latest for frontend and a django project for the backend. I created a simple notes app that works with each other. But they have different ports. How to integrate React with Django so when I go to localhost:8000 ReactJS shows up? -
Custom filter backend or Django-Filter?
I work on simple Django project that uses DRf and I have small problem. I want to add filtering and searching to my API endpoints, but I don't know which way is better: Make custom filter backend for filtering and searching logic. Use Django-Filter package for this task. Here is part of my code now: from django.db import models from rest_framework import viewsets, filters class MyModel(models.Model): title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer filter_backends = [filters.SearchFilter] search_fields = ['title', 'description'] I am just wondering, which method is better for performance, easy to maintain, and follows best practices? Can you tell me pros and cons for both methods and any problems I can have? For example, if I make custom filter backend, how to make it good? If I choose Django-Filter, are there problems or limits I should know? I am very thankful for any help and advice! -
Will i be able to host my django web app on heruko if i have a github student developer pack
So, I have a Django web app I need to host, and I want to host it for free. But Heroku's service is not free, but I have the Github student developer pack and saw Heroku's service on it. Will I be able to host my Django project on it now, and if yes, then how do I do it? My Django web app has data that goes to the Django console and Firebase real-time database. Or can I get a free alternative? -
What is a better way to use 'request' in a ModelChoiceField
Is there any way to use user=request.user inside ModelChoiceField when I use this method I got an error: NameError: name 'request' is not defined. class AlbumForm(forms.Form): album = ModelChoiceField(queryset=Album.objects.filter(user=request.user) The model: class Album(models.Model): name = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE)