Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vagrant provision fatal in: TASK [Start yarn]
I'm trying to set up Vagrant and while trying vagrant provision I get the error below: TASK [Start yarn] ************************************************************** fatal: [default]: FAILED! => {"changed": false, "msg": "Unable to start service yarn: Job for yarn.service failed because the control process exited with error code.\nSee \"systemctl status yarn.service\" and \"journalctl -xe\" for details.\n"} PLAY RECAP ********************************************************************* default : ok=25 changed=3 unreachable=0 failed=1 skipped=2 rescued=0 ignored=0 Ansible failed to complete successfully. Any error output should be visible above. Please fix these errors and try again. systemctl status yarn.service says Unit yarn.service could not be found, but the TASK [Deploy yarn install] during Vagrant provision has status ok: [default]. How can I solve the problem? -
Using signals in django, trying to generate code for SMS verification but generated code is not visible in admin. what am i missing?
folder structure enter image description here models.py from face_detect from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) mobile = models.CharField(max_length=10,null=True) add = models.CharField(max_length=10,null=True) image = models.FileField(null=True) def __str__(self): return self.user.username models.py from otp from django.db import models from django.contrib.auth.models import User from face_detect.models import Profile import random # Create your models here. class Code(models.Model): number = models.CharField(max_length=5, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return str(self.number) #otp verification def save(self, *args, **kwargs): number_list = [x for x in range(10)] code_items = [] for i in range(5): num = random.choice(number_list) code_items.append(num) code_string = "".join(str(item) for item in code_items) self.mobile = code_string super().save(*args,**kwargs) signals.py from otp from face_detect.models import Profile from django.contrib.auth.models import User from .models import Code from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def post_save_generate_code(sender, instance, created, *args, **kwargs): if created: Code.objects.create(user=instance) apps.py from otp from django.apps import AppConfig class OtpConfig(AppConfig): name = 'otp' def ready(self): import otp.signals init.py from otp default_app_config = 'otp.apps.OtpConfig' admin.py from otp from django.contrib import admin from .models import Code # Register your models here. admin.site.register(Code) code seen in http://127.0.0.1:8000/admin/otp/code/ enter image description here code is not visible. how can i make … -
keep users logged in using Knox Token Authentication django
I am having a hard time trying to figure this out. I am trying to use the django rest api knox token authentication and React. This is what my code looks like in Authenticate.js export function LoginComponent (props) { const [state, setState] = useState({credentials : {username: '',password: '',}}) const [hasLoggedIn, setHasLoggedIn] = useState(false) const Login = (event) => { event.preventDefault() fetch("http://127.0.0.1:8000/users/accounts/api/auth/login",{ method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(state.credentials) }) .then( data => data.json()).then( data => { console.log(data.token) props.userLogin(data.token) } ) .then( console.log(hasLoggedIn), setHasLoggedIn(true), props.LoggedIn(hasLoggedIn)) .catch(error => console.error()) } const Register = (event) => { fetch("http://127.0.0.1:8000/users/accounts/api/auth/register",{ method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(state.credentials) }).then( data => data.json()).then( data => { console.log(data.token) } ).catch(error => console.error()) } const inputChanged = (event) =>{ const cred = state.credentials; cred[event.target.name] = event.target.value setState({credentials: cred}) } return ( <div> <label> Username: <input type='text' name='username' value={state.credentials.username} onChange={inputChanged} /> </label> <br/> <label> Password: <input type='password' name='password' value={state.credentials.password} onChange={inputChanged} /> </label> <br/> <button onClick={Login}>Login</button> <button onClick={Register}>Register</button> </div> ) } This is a code I made from a youtube video The problem comes while trying to keep the users authenticated, if you refresh on this current code, you will end up losing the Token, which means you have to login … -
Why does upload_to in ImageField not working at all when i try to save uploaded image from user in views
I am trying to make a simple mail service with very simple architecture project. At this moment my backend part of development is almost done, but i have stoped already fro two days because of i have no idea why does images saving not working. Obviously, i expect that user upload his profile avatar and it's saving to path i've set in upload_to. Path to image must looks like profiles/UserName/his_profile_img.jpeg For last two days i have spent more than 12 hours by trying to solve it. This is my model where is my trouble ImageField: from django.db import models from datetime import datetime, timedelta from django.contrib.auth.models import User def username(user, file): string_username = str(user).split()[0] return f"profiles/{string_username}/{file}" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="Profile") ##### This is here avatar = models.ImageField(default="/profiles/profile.png", upload_to=username) name = models.CharField(max_length=30, blank=True) surname = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=64, blank=True) bio = models.CharField(max_length=1024, blank=True) def username(self): return self.user.username @property def joined(self): joined = self.user.date_joined.strftime("%d %B %Y") is_today = joined == datetime.today().strftime("%d %B %Y") if is_today: return "today" is_yesterday = joined == datetime.date(datetime.today() - timedelta(days=1)).strftime("%d %B %Y") if is_yesterday: return "yesterday" return f"{joined}" def __str__(self): return f"{self.user} profile" This is a view function, which doesn't save image: def … -
How to duplicate part of html code in django using jinja2?
I need to duplicate a certain part of the code through the Django admin panel. But I do not know how this can be implemented. My teacher suggested that this can be done through jinja2, but I don't really understand how to use jinja2 for my purposes. I would be very grateful to anyone who can help either find information or show you how to implement it. this is the html code that needs to be duplicated <td class ="sale"> {% if good.image %} <img src="{{ MEDIA_URL }}{{ good.image_sale }}"> {% endif %} {% for good in goods %} <h1 class="description">{{ good.description_text }}</h1> {% endfor %} <a class="buy" href="#openModal" > <span >Купить</span></a> {% for good in goods %} <h1 class="price" >{{ good.price_text }}</h1> {% endfor %} </td> I do not know what else to add, if you need something else, write, I will add -
Upload a file in Django Admin, but not as a model's FileField
I'm working with Django 3 and I need to upload a (zip) file via the Django Admin. All the information that I've found online refers to uploading files as a models' FielField. But in my case, I don't want to associate the uploaded file to any model. I just want to upload it and run a certain management command based on its content, and delete it afterwards. If needed, I can use JQuery in the Django Admin pages to help accomplish this goal. Any pointers on how to do this? -
how to remove a null value from session cart dictionary in django
here is my views.py logic to add product in session cart def index(request): categoryID= request.GET.get('category') product= request.POST.get('product') cart=request.session.get('cart') if cart: quantity=cart.get(product) if quantity: cart[product]=quantity+1 else: cart[product]=1 cart['product']=1 else: cart['product']= 1 request.session['cart']=cart print(cart) print(product) category=Category.get_all_categories() if categoryID: products = Product.get_all_products_by_id(categoryID) else: products=Product.get_all_products() prddata={ 'product' : products, 'cat': category, } return render(request,'index.html',prddata) I have added two product in cart but when I print cart in terminal {'product': 1, '1': 1, '2': 4, 'null': 1} 2 [06/Nov/2021 01:10:25] "POST / HTTP/1.1" 200 13104 this null is being added I don't know how. How to prevent this or remove it from cart? please help. -
Query data using filter Django/python
I'm pretty new to the Django backend framework. I have been able to easily query data, but now I'm trying to filter that data. When I run the application it will load the landing page and other pages, but when I try to naviagate to the FRReports page I get "Error during template rendering In template C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html, error at line 16 'webdart' is not a registered namespace" Any ideas or guidance? urls.py from django.urls import path, include from . import views from webdart.views import AboutView from django.contrib import admin admin.autodiscover() # Use '' to default to the home page urlpatterns = [ path('', views.landing, name='webdart-landing'), path('admin/', admin.site.urls), path('home/', views.home, name='webdart-home'), path('data/', views.data, name='webdart-data'), path('data/stationData/', views.data_stationData, name='webdart-data_stationData'), path('data/obscura/', views.data_obscura, name='webdart-data_obscura'), path('data/tiz/', views.data_tiz, name='webdart-data_tiz'), path('data/mcv/', views.data_mcv, name='webdart-data_mcv'), path('data/viewer/', views.data_viewer, name='webdart-data_viewer'), path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'), path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'), path('FRReports/', views.DocRepositoryListView.as_view(), name='list'), path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'), #path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'), path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'), . . . views.py from django.core.paginator import Paginator from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView, ListView, DetailView from webdart.models import Person, DocRepository from webdart.filters import DocRepositoryFilter class DocRepositoryListView(ListView): model = DocRepository template_name = 'webdart/FRReports.html' def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset()) return context class documents_FRReports(DetailView): … -
Django + gUnicorn timing out with POST requests with large sizes
Sending a 'large' POST request to gUnicorn will cause it to freeze and eventually timeout. This is both on my production server and development server (both running Ubuntu 20.04). It just freezes before returning [CRITICAL] WORKER TIMEOUT (pid:10000) Django's default dev server works without issues. My WSGI file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings') application = get_wsgi_application() -
How can I make a twitter like homepage with django?
I am right now new to the Django web framework. I want to make a twitter-like/facebook-like homepage where a user can post a status or update and also view other ures' posts but I can't do that because when a user is logged in, he posts an update but can't view it is his home. He can view all the posts when he logs out. Here is my views function for this. views.py def index(request): posts = NewPost.objects.all().order_by("-timestamp") if request.user.is_authenticated: if request.method == "POST": post = NewPostForm(request.POST) user = request.user timestamp = datetime.now() if post.is_valid: post = post.save(commit=False) postdata = NewPost(post=post,user=user,timestamp=timestamp) postdata.save() return render(request,"network/index.html",{ "post" : post, "user" : user, "timestamp" : timestamp }) else: post = NewPostForm() return render(request,"network/index.html",{ "post" : post }) return render(request,"network/index.html",{ "posts" : posts }) urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), ] templates {% extends "network/layout.html" %} {% block body %} <div style="margin: 10px 10px 10px 10px;"> <h1>All Posts</h1> {% if user.is_authenticated %} <div class="border border-success" style="margin: 10px 10px 10px 10px;"> <div style="margin: 10px 10px 10px 10px;"> <h3>New Post</h3> <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <div class="form-group"> <!-- <textarea name="post" class="form-control" cols="30" … -
My form doesn't appear with another some problems with the bid system Django issues
I want to apply this requirement: the user should be able to bid on the item. that bid must be largest than the bid and if not show error message my problem is when I runserver the bid form disappearing and I cannot see anything except this pargraph <p class="text-muted">Start the first Bid!</p> I try to do that thing that what I have urls.py urlpatterns = [ path('Post/<int:id>', views.viewList, name='viewList'), # bids path("Post/<int:id>/bid", views.take_bid, name="take_bid"), # Close Bid path('Post/<int:id>/close', views.closeListing, name="closeListing"), ] views.py def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'Bidform': BidForm(), 'is_watched': is_watched } return render(request, 'auctions/item.html', context) @login_required def take_bid(request, id): listing = Post.objects.get(id=id) bid = float(request.POST['bid']) if is_valid(bid, listing): listing.currentBid = bid form = BidForm(request.POST, request.FILES) newBid = form.save(commit=False) newBid.auction = listing newBid.user = request.user newBid.save() listing.save() return HttpResponseRedirect(reverse("viewList", args=[id])) else: return render(request, "auctions/item.html", { "listing": listing, "Bidform": BidForm(), "error_min_value": True }) def is_valid(bid, listing): if bid >= listing.price and (listing.currentBid is None or bid > listing.currentBid): return True else: return False models.py class Post(models.Model): # data fields title = models.CharField(max_length=64) textarea = models.TextField() # … -
Custom template tags in Django
I want to use Django Template Tags to return some html values but it happens that the value is returned once and then reused by the browser when refreshed even if I do a hard refresh. It only changes when I reload my development server. Is there anything that can be done to return the dynamic html files from the template tags each time the browser is refreshed -
How to serialize first photo in album? Django
How to serialize first photo in album if photo connected by using FK with model Gallery. I need first photo for gallery cover in galley list. My models: class Gallery(models.Model): title = models.CharField() class GalleryImage(models.Model): gallery_id = models.ForeignKey(Gallery, related_name='photos') photo = models.ImageField() Anyone have any ideas? May be I need suchlike request Gallery.objects.get(id=id).photos.first() but i not sure is it correct. -
Python Django ImportError: cannot import name 'Required' from 'typing_extensions'
Django version is 3.2.9. Python version is 3.10.0. And typing_extensions 3.10.0.2 I'm new to coding, python, etc., and can't figure out what is the problem. Following django tutorial I created an app and ran the server successfully, but a day later, when I tried to do that again I faced this problem: File "C:\Users\fused\Desktop\code\py\myproject\myapp\views.py", line 1, in <module> from typing_extensions import Required ImportError: cannot import name 'Required' from 'typing_extensions' (C:\Users\fused\AppData\Local\Programs\Python\Python310\lib\site-packages\typing_extensions.py) After trying to run a server with 'python manage.py runserver' this problem appeared, tried reinstalling typing_extensions, checked versions of everything, but nothing solved the problem. If any additional information is needed, I'll reply with it. Thanks in advance -
Getting CSRF token missing error on a django rest framework (with TokenAuthentication) public APIView
I'm having issue with Django Rest Framework and CSRF configurations. I know there are plenty of similar posts on the subject (like this one Django Rest Framework remove csrf) but most of them do not apply (I'm not using SessionAuthentication, nor Django templates), and the way DRF handles CSRF is still unclear to me. Here is the situation : I have a DRF application acting as a backend API with several routes, with Token Authentication (JWT) I also have a separate frontend communicating with my API. Both are on the same domain (say https://example.com and https://example.com/backend) I have a simple APIView on DRF side for registration on which I need to send POST requests. This view doesn't require authentication. When I send the POST request, I get a 403 Forbidden error with the following message : detail "CSRF Failed: CSRF token missing or incorrect." Here is my view: class RecaptchaVerifyView(APIView): permission_classes = [] serializer_class = ReCaptchaSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): return Response({'success': True}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I've read that DRF disables CSRF except for SessionAuthentication which I do not use. I also read that empty permission_classes should solve most of the problems. So … -
Updating model field by adding old value to new Django
I'm trying to keep track of the total hours being put into a work order. I'd like to add the new number being entered to the number existing in the DB and return the total. Thank you in advance for any help. The Model: class WorkOrder(models.Model): client = models.ForeignKey(Contact, on_delete=models.CASCADE) hours_worked = models.IntegerField() The View: class UpdateWorkOrder(LoginRequiredMixin, generic.UpdateView): model = WorkOrder template_name = 'client/update_workorder.html' success_url = reverse_lazy('dashboard') -
Django-neomodels driver error while running python manage.py install_labels
I am running the paradise papers neo4j project tutorial, I have created all my models but I get the error below while generating database indexes.That is when I run command: python manage.py install_labels My requirements.txt: asgiref==3.4.1 certifi==2021.10.8 Django==3.2.8 django-neomodel==0.0.7 djangorestframework==3.11.2 gunicorn==20.0.4 neo4j-driver==4.3.1 neomodel==4.0.4 pytz==2021.1 Shapely==1.7.1 six==1.16.0 sqlparse==0.4.2 white-noise==3.3.1 and added the following in the settings.py: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL','bolt://neo4j:1234@127.0.0.1:7687'). Error: File "/Users/harmankibue/Desktop/Data/Projects/Django-Projects/papers_search/manage.py", line 21, in <module> main() File "/Users/harmankibue/Desktop/Data/Projects/Django-Projects/papers_search/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/django_neomodel/management/commands/install_labels.py", line 12, in handle install_all_labels(stdout=self.stdout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/core.py", line 153, in install_all_labels install_labels(cls, quiet=False, stdout=stdout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/core.py", line 110, in install_labels db.cypher_query("CREATE INDEX on :{0}({1}); ".format( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/util.py", line 35, in wrapper return func(self, *args, **kwargs) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neomodel/util.py", line 230, in cypher_query response = session.run(query, params) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/work/simple.py", line 221, in run self._connect(self._config.default_access_mode, database=self._config.database) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/work/simple.py", line 118, in _connect self._connection = self._pool.acquire( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 805, in acquire return self._acquire(self.address, timeout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 660, in _acquire connection = self.opener(address, timeout) File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 787, in opener return Bolt.open( File "/Users/harmankibue/opt/anaconda3/envs/papers_env/lib/python3.9/site-packages/neo4j/io/__init__.py", line 337, … -
'AnonymousUser' object has no attribute '_meta' | Django Authentication
Same authentication system on three different places in project i.e Authenticating user at login, registration, and password reset. At password reset it works fine all the time. At registrations sometime works and sometime doesn't and at login works on rare occasions. Also the error is same all the time. ERROR AttributeError at /userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ 'AnonymousUser' object has no attribute '_meta' Request Method: POST Request URL: http://127.0.0.1:8000/userauth/user-activate/NA/avnpw3-de3afda5cfeae9690598ace91235106a/smqia40453665072/pW1QdEFRkm42txOZ Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute '_meta' Exception Location: C:\Users\smqia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py, line 247, in inner Python Executable: C:\Users\smqia\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\smqia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 05 Nov 2021 16:35:02 +0000 CODE settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) views.py username = smqia404 password = *************** user = authenticate(request, username=username, password=password, backend='django.contrib.auth.backends.ModelBackend') login(request, user, backend='django.contrib.auth.backends.ModelBackend') -
GeoDjango with Docker error: 'DatabaseOperations' object has no attribute 'geo_db_type'
This appears to be a common error, and I have checked all the solutions I could find (there are only about 4 and almost all of them involve misconfigurations). I am NOT using heroku, but I AM using docker. I am using the docker images python:3.9.7 and postgis/postgis:10-3.1-alpine. My Dockerfile contains the following line: ARG BUILD_ENV=production # ... FROM python:3.9.7 as apiserver #... RUN apt-get update && \ apt-get install --no-install-recommends -y apt-utils build-essential sudo git wget curl ca-certificates nginx openssl libpq-dev expect libmagic-dev graphviz python3-gdal python3-pandas postgis binutils libproj-dev gdal-bin python3-djangorestframework-gis # ... RUN pip install --upgrade pip && pip install -r requirements/${BUILD_ENV}.txt # ... This should make sure all the dependencies I need to build the postgis libs for django are present, so when I run pip install, it will have everything it needs. It is more verbose than it needs to be because the GeoDjango docs say to install postgis binutils libproj-dev gdal-bin, and the drf-gis one has all the GeoDjango libs as dependencies. I plan on using the drf-gis package, but am not currently using it. requirements/production.txt django-cors-headers==3.5.0 django-extensions==3.0.9 django-filter==2.4.0 # ... Django==3.1.13 # ... djangorestframework==3.12.4 djangorestframework-gis==0.17 # ... I have enabled the correct app in … -
Saving a comment under an article returns 404 page not found
I have been trying to add comments to a blog page that I am creating. I have a comment model which has a post id as foreign key, and user as well, because I want to allow only users to comment. class Comment(models.Model): post = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments') name = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_NULL) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] However on save, it returns a 404 error. Not Found: /articles/this-is-first-article/ [05/Nov/2021 16:51:05] "POST /articles/this-is-first-article/ HTTP/1.1" 404 2912 This is my urls: app_name = 'articles' urlpatterns = [ path('', article_search_view, name='search'), path('create/', article_create_view, name='create'), path('<slug:slug>/', article_detail_view, name='detail'), ] And this is my view: def article_detail_view(request, slug=None): article_obj = None new_comment = None comments = None comment_form = None if slug is not None: try: article_obj = Article.objects.get(slug=slug) comments = article_obj.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article_obj new_comment.save() return redirect(article_obj.get_absolute_url()) else: comment_form = CommentForm() except Article.DoesNotExist: raise Http404 except Article.MultipleObjectsReturned: article_obj = Article.objects.filter(slug=slug).first() except: raise Http404 context = { "object": article_obj, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form } return render(request, "articles/detail.html", context=context) I know this is a trivial problem, … -
Custom confirm screen when saving an object in my Django project?
I am looking to create a custom confirm screen in django when saving an object. (Add/update) I have been able to achieve this using the Media class in admin class by specifying custom JavaScript that would use window.confirm(), however this looks quite unprofessional. class Media: js = ('confirmation_popup.js',) I have been trying to create a similar screen to the delete confirm that django offers. I have created a html template to use for the screen. I have overridden the response_change admin method to redirect to this template on post. But the problem is that the model saves before it gets to the response change so no matter what the outcome of the confirm the model has already saved. So my question at hand is it possible to redirect a model admin page before a save, then redirect back after the confirm? If not, how can I go about creating a confirm screen for saving a model? I am using Django v3.1.* so I cannot use https://pypi.org/project/django-admin-confirm/ . I have tried before and the admin-confirm screen does not work. -
Django ORM better way to manipulate django ORM query
Below are the models: class Seat(models.Model): hall = models.ForeignKey(Hall,on_delete=CASCADE) type = models.TextField(verbose_name="Seat Type") class Show(models.Model): show_time = models.TimeField(verbose_name='Show Time') movie = models.ForeignKey(Movie,on_delete=CASCADE) hall = models.ForeignKey(Hall,on_delete=CASCADE) cinema = models.ForeignKey(Cinema,on_delete=CASCADE) class Booking(models.Model): seat = models.ForeignKey(Seat,on_delete=CASCADE) show = models.ForeignKey(Show,on_delete=CASCADE) movie = models.ForeignKey(Movie,on_delete=CASCADE) hall = models.ForeignKey(Hall,on_delete=CASCADE) cinema = models.ForeignKey(Cinema,on_delete=CASCADE) user = models.ForeignKey(User, verbose_name="Username", on_delete=DO_NOTHING) # donothing Explanation of the models: Multiple Seats in a Hall Each Hall hosts multiple Shows Each Booking is basically a ticket for a show with a specific seat and a specific show. Requirement is to get a queryset that has all seats not present in the bookings table for a specific show. Basically, get the list of available seats for a show by checking they are not present in the Bookings table The SQL query would look like this: SELECT * FROM Seat as S join Show as Sh on S.hall = Sh.hall join Bookings as B on B.show = Sh.id where Sh.id = 1 AND B.seat IS NULL how to convert this to Django ORM: able to do it like this (is there a better way rather than creating the seat_id_list?): qs = Seat.objects.filter(hall=hid) #---------------------------------- show_bookings = Booking.objects.filter(show=spk) seat_id_list = [] for each_booking in show_bookings: print(each_booking.seat.id) seat_id_list.append(each_booking.seat.id) qss … -
Is there an elegant way to flatten nested JSON with a django serializer?
I receive nested JSON from an API (I can't influence the structure). I want to flatten the nested fields while deserializing an object, using a django rest framework serializer. How do I do this elegantly? Here is my current approach, which works by using nested serializers and doing the flattening in the .create(): from dataclasses import dataclass from rest_framework import serializers input_data = { "objectName": "Johnny", "geoInfo": { "latitude": 1.2, "longitude": 3.4, }, } flattened_output = { "name": "Johnny", "lat": 1.2, "lon": 3.4, } @dataclass class Thing: name: str lat: float lon: float class TheFlattener(serializers.Serializer): class GeoInfoSerializer(serializers.Serializer): latitude = serializers.FloatField() longitude = serializers.FloatField() objectName = serializers.CharField(max_length=50, source="name") geoInfo = GeoInfoSerializer() def create(self, validated_data): geo_info = validated_data.pop("geoInfo") validated_data["lat"] = geo_info["latitude"] validated_data["lon"] = geo_info["longitude"] return Thing(**validated_data) serializer = TheFlattener(data=input_data) serializer.is_valid(raise_exception=True) assert serializer.save() == Thing(**flattened_output) I know that when serializing objects to JSON, you can reference nested/related objects in the source parameter e.g. first_name = CharField(source="user.first_name") which is really nice, but I haven't been able to find something similar for deserialization. -
Django test: Residence() got an unexpected keyword argument 'hotel_id'
class Hotel (models.Model): name = models.CharField() country = models.CharField() city = models.CharField() street = models.CharField() class Residence(models.Model): hotel_id = models.ForeignKey(Hotel, on_delete=models.DO_NOTHING, related_name='hotel') house_number = models.CharField() I want to join two models (Hotel and Residence) and then post it. I wrote the folowing code: serializers.py class HotelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hotel fields = ['name', 'country', 'city', 'street'] class ResidenceSerializer(serializers.HyperlinkedModelSerializer): hotel_id = HotelSerializer() class Meta: model = Residence fields = ['house_number', 'hotel_id'] def create(self, validated_data): return Residence.objects.create(**validated_data) views.py class ResidenceViewSet(viewsets.ModelViewSet): serializer_class = ResidenceSerializer queryset = Residence.objects.all() When I try to post data in my api I got the following error: Residence() got an unexpected keyword argument 'hotel_id'. Can someone help me? -
How to import bootstrap in django?
I have set up my python environment for coding, but I can't find the pip command to install Django in my virtual environment. I have tried to install it with pip install python3-django, as in the video I watched, but it simply doesn't work