Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement the mouseover product zoom functionality like amazon in slick sync slider? Not working jquery zoom plugins with this slider.possible?
I have done with the default slick sync slider. But cannot implement the jquery zoom plugins inside this slick slider. I want product zoom functionality like amazon..with this slick slider.please anyone tell me, what would be the best option for this.? -
How to restrict Media Folder using Django ? Is it a way?
I tried several tutorials using "FileResponse" to restrict the access to the MediaFolder only on authenticated User... But it does'nt run well online. It ran on localhost, but definitly not online. Is it a way or an App which can restrict the Media folder ? -
The QuerySet value for an exact lookup must be limited to one result using slicing in django
I was trying to do a system that will delete an item from our cart .so I made a url and I pass the slug of the item into it to delete it from the Cart . bit there is a problem . can you help please? views.py def remove_cart(request , slug): url = request.META.get('HTTP_REFERER') ca = product.objects.filter(slug = slug) Cart.objects.filter(produ = ca).delete() return redirect(url) urls.py app_name = 'cart' urlpatterns = [ path('' , views.cart_detail , name='cart_deatil'), re_path(r'^add/(?P<slug>[\w-]+)/$' , views.add_cart , name='add_cart'), re_path(r'^remove/(?P<slug>[\w-]+)/$' , views.remove_cart , name='remove_cart') ] models.py class Cart(models.Model): produ = models.ForeignKey(product , on_delete=models.CASCADE) user = models.ForeignKey(User , on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class CartForm(ModelForm): class Meta: model = Cart fields = ['quantity'] -
Restrict user from accessing form
Good day everyone! I'm a python Django web app developer and I ran into a problem recently which is to restrict a user from accessing a form twice untill after a given time. I've tried using Django sessions.accessed but I don't get what I want. I would appreciate if anyone could help me out with this. -
why getting Complex aggregates require an alias error?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but the problem is that if I have data in Orders table related to some gig and I retrieve the gig then it worked perfectly but if I tries to retrieve a gig with no orders yet ( in orders table there is no record/field containing that item/gig) then it gives me following error Complex aggregates require an alias Models.py class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) isCompleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) Views.py class … -
Django add to cart form
i have a product model : class Product(models.Model): thumbnail =models.ImageField(upload_to=upload_image_path,null=True,blank=True) title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) discount = models.DecimalField(decimal_places=2, max_digits=20, default=00.00) slug = models.SlugField(blank=True, unique=True) and I want to add make an add to cart form so the user can add products to his cart, the problem is that the add to cart form is diffèrent for each product example: for product A: available colors: blue and yellow, available size: S, M for product B: available colors: black and white, available size: L, XL what I did is create another model: class Color(models.Model): Color = models.CharField(max_length=120) def __str__(self): return self.Color and then add a ManyToMany relation to the product model: class Product(models.Model): thumbnail =models.ImageField(upload_to=upload_image_path,null=True,blank=True) title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) discount = models.DecimalField(decimal_places=2, max_digits=20, default=00.00) slug = models.SlugField(blank=True, unique=True) Color = models.ManyToManyField(Color) so now when i am creating a product i can chose the avaible colors, but for the add to cart form I have to hard code it in html in the products.html template products.html : {% for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{product.thumbnail.url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{product}}</h5> <p class="card-text">{{product.description}}</p> <form … -
Create a dynamic launch URL for Power BI with tabular data
I have a WEB app where there is a table with data (the data is filtered using Python (Django), the database is Azure SQL Database) and I want to send this table using a link to the Power BI program, I mean after clicking a certain button so that it opens Power BI with the same data. For example, I can cite the work of the Teams program when we open the link in the browser, it wants to redirect us to the program itself, or open it in the browser itself Maybe someone will have ideas on how to implement this? -
POST request resulting logout in django
POST request resulting logout in django views.py @login_required def employerprofile(request): submitted=False if request.method == 'POST': form=EmployerProfileForm(request.POST,request.FILE) if form.is_valid(): form.save() return HttpResponseRedirect('/employerprofile?submitted=True') else: form=EmployerProfileForm if 'submitted' in request.GET: submitted=True return render(request,'employer/employer-profile.html', {'form':form,'submitted':submitted}) ------------------------------------------------------------------------ -
Is there a way to pass certain info, that is specific to a user, to the fields of a (new) django form?
I have the following "problem": I have automated a "prediction-game" where users can win points when they predict the correct winners in a sports event over multiple weeks (for example: Tour de France). They are allowed to choose 5 athletes of which they think that will win in the races. At the end of every week, the users are allowed to make some changes in their prediction for the next week. Until a certain date (start of the event or week), the users can choose athletes for their prediction. The users can fill in the form and if they change their minds before the start, they are still able to change/update their prediction. But after the start, they can't change it anymore and their input will be used to calculate their score. After the first week (in which their scores are calculate with the input they made in the "PredictionWeek1" model), they will have a change to make a new prediction for the next week ("PredictionWeek2" model) for which they also have the change to update it as much as they want before a certain date. In reality, the input for the second week, will be very similar to the … -
Django - How to make UNIQUE constraint not apply across inherited models?
There's a PlainModel that has attributes like name, color - and a slug, which has to be unique. I want to make my own version of it, an ExtendedModel that also has size. So, I made the model inherit from PlainModel: class ExtendedModel(PlainModel): size = models.IntegerField(...) However, I ran into an issue - because of the way Django model inheritance works, ExtendedModel's database table only has two columns - one for size, and one for a pointer to the original PlainModel table. This means that the unique constraint on slug applies for both models, and there can't be an ExtendedModel with the same slug as an already existing PlainModel. I don't want this behavior, the slugs are only going to ever appear in the context of each model separately (e.g. /products/{slug} and /products/extended/{extended_slug}), so there's no reason to ensure uniqueness across them both. Is it possible to make the constraint apply only for each model respectively? An obvious way would be to have the tables be completely separate, which Django does not seem to support, however. PlainModel would have to be an "Abstract Model", which I can't control. (PlainModel is defined in an external library.) Another way would be to … -
Event management system django booking model and booking function?
How to create a Booking model for event management sys and conform booking msg display to a user with booking id and the user also cancel booking using Django? -
response returning no data django-rest
i don't know whats wrong with this code, previously i was getting assertion error and now this class OrganisationSerializer(ModelSerializer): products = ProductSerializer(many=True) #manytomany field pictures = PicturesSerializer(source ='pictures_set',many=True) #foreign key field class Meta: modal = Organisation fields = ['name','address' ,'products','pictures'] @api_view(['GET']) def get_data(request): data = None query_set = Organisation.objects.all() serialized_data = OrganisationSerializer(data = query_set,many =True) if serialized_data.is_valid(): data = serialized_data.data print(data) return Response(data,status=status.HTTP_200_OK) problem returning no data -
Is a subquery of this kind possible in django?
In sql I could can do something like this - select a, b, c from ( select a, b, c from table_a ) where a = something Is this possible with django? I've only ever used subquery of the type where the primary key of the subquery for example maps to a column of a row in the parent query. I don't want this though on this occasion. Here is the context. I have a query which has annotated column which uses a Window frame. Such an expression cannot be included in a WHERE clause because sql evaluates the where clause first. So it is necessary to perform this query first as a subquery and then use the result like it is its own table. On this parent query I can then filter. -
I want to use the foreign key model in as forms in Django forms
i have two models in django farmer and tractor and i want to use both the models in single form on webpage so that with all the properties as there inputs like name, phone, email , id, price etc. my models.py class Farmer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone =models.CharField(max_length=10) address = models.TextField(max_length=200) email_address = models.EmailField() def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Post(models.Model): tractor_price = models.IntegerField(max_length=150) implimentaion = models.CharField(max_length=50) purchase_date = models.DateField(auto_now=False) slug = models.SlugField(unique=True, db_index=True, null=True,blank=True) tractor_company = models.CharField(max_length=50) tractor_model = models.CharField(max_length=50) description = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now=False) farmer = models.ForeignKey( Farmer, on_delete=models.SET_NULL, null=True, related_name="posts") forms.py from .models import Post,Farmer class TractorForm(ModelForm): class Meta: model = (Post,Farmer) fields = ("tractor_price","implimentaion","purchase_date","tractor_company","tractor_model","description") here I also want to use Farmer model so that i can take input from that also -
uploaded file wont save
Im trying to add a feature to my app that allows users to upload their cv file. I created a model like this: class ResumeDocument(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) cvfile = models.FileField(upload_to="documents", null=True) and created a model form like below: class DocumentForm(forms.ModelForm): class Meta: model = ResumeDocument fields = ['cvfile'] my views.py: def pdf_resume(request): if request.method == 'POST': form = DocumentForm(request.POST or None ,request.FILES or None , instance=request.user) if form.is_valid(): form.save() messages.success(request, f'Done!!!!') return redirect('pdf_resume') else: form = DocumentForm(instance=request.user) context = {'form':form} return render(request, 'reg/pdf_resume.html', context) and finally my HTML: {% if messages %} {% for m in messages %} {{m}} {% endfor %} {% endif %} <form method="POST" action="{% url 'pdf_resume' %}" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ form }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit ">Update</button> </div> </form> when I click Update, it redirects to the page and messages me with success and no error. but the file doesn't get saved in media. however, when I upload the file from admin page it gets uploaded and saved. what am I doing wrong? please help me -
How do I add an extra button next to a specific field in django admin?
I added a button to django admin, but I don't know how to place this button next to the field. admin.py class ProductAdmin(admin.ModelAdmin): readonly_fields = ('created_date', 'updated_date') list_display = ('code', 'category', 'manufacturer', 'quantity', 'price', 'created_date', 'updated_date') list_filter = ('created_date', 'updated_date') change_form_template = "admin/quantity_change_form.html" def response_change(self, request, obj): if '_add-ten' in request.POST: obj.quantity += 10 obj.save() self.message_user(request, 'Добавлено 10 единиц') return HttpResponseRedirect(".") return super().response_change(request, obj) quantity_change_form.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Добавить 10 единиц" name="_add-ten"> </div> {% endblock %} Please, tell me how can I do this? -
How to make embedded document in mongodb using django models?
I have connected mongodb database to django using djongo. I have created 2 apps 'Artist' and 'Album' which have a one to many relation. I want to make embedded document in below structure: { ArtistName : "Ariana", Albums : [ { SerialNo : 1, AlbumName : "Positions" }, { SerialNo : 2, AlbumName : "thank u, next" } ] } How do I write django model in order to get document in the above structure? -
Django RedirectView.as_view always return parameter as lower case
I am using RedirectView.as_view to redirect my local url to external website The external url is case sensitive, however whenever I pass the 'Upper' case parameter to url , seems like RedirectView transfer it to 'lower case' Here is my code: re_path('externlink/(?P<platform>\w+)/(?P<uuid>\w+)/$', RedirectView.as_view(url='https://externlink/%(platform)s/%(uuid)s'), name='firebase') When I pass platform as 'Android' , the '%(platform)s' in RedirectView returned 'android' , it is not what I want, how can I prevent it from auto transfer ? -
Why is print(bid > highest_bid) returning true, when bid = 3 and highest_bid =2000?
I'm making a simple form in Django without using the in-built Django forms. To process the form I'm just using HTML/Django template and Python in the views.py file. I don't understand why print(bid > highest_bid) is returning True when: Highest bid = 2000.6 bid = 3 listing_detail.html <form method="POST" action="{% url 'listing-detail' object.id %}"> {% csrf_token %} <input type="hidden" name="highest_bid" value="{{ highest_bid }}"> <input type="number" step=".01" min="" placeholder="0.00" name="bid"> <button type="submit">Place bid</button> </form> views.py # place bid highest_bid = request.POST.get("highest_bid", "") #2000.6 print(f'Highest = {highest_bid}') bid = request.POST.get("bid", "") #3 print(f'bid = {bid}') print(bid > highest_bid) # returns True if 'bid' in request.POST and bid > highest_bid: #bid = float(request.POST['bid']) new_bid = Bids(bid_value=bid, bidder=self.request.user, item=item) new_bid.save() return redirect(reverse("listing-detail", args=listing_id)) This means that the bid is being saved to the database. Even though I am trying to only save the highest bid with the line if 'bid' in request.POST and bid > highest_bid: -
how to iterate over captured images and add to an input tag - js
i'm trying to capture multiple images and then save into the database here is the js code const player = document.getElementById('player') const canvas = document.getElementById('canvas') const form = document.getElementById('form') const docs = document.getElementById('documents') const captureButton = document.getElementById('capture') const context = canvas.getContext('2d') captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height) e.preventDefault(); let new_image = document.createElement('img') new_image.src = canvas.toDataURL() console.log(new_image) docs.value = canvas.toDataURL() form.insertAdjacentElement('beforeend',new_image) e.preventDefault(); }); navigator.mediaDevices.getUserMedia({video: true}) .then((stream) => { player.srcObject = stream;}) <form id="form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <video id="player" controls autoplay></video> <button type="button" id="capture">Capture</button> <button>save</button> <canvas id="canvas" width=320 height=240></canvas> <input type="text" name="documents" hidden id="documents"> </form> and here is my views.py to get multiple base64 data and split it by using its data attribute , here is my code @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = request.POST.get('documents') data,imgdata = images.split('data') for img in imgdata: print(img) format, imgstr = img.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj}) but it raise this error : not enough values to unpack (expected 2, got 1) and the print(img) returns only : ! and … -
TypeError: save() got an unexpected keyword argument 'force_insert'
I'm trying to implement a signal that creates a Profile upon the save of a User instance. Trying to test this out with my form to register users gives me the following stacktrace: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/auth/register/ Django Version: 3.2.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'webpack_loader', 'home', 'personal_list', 'utils', 'authentication'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/noxlock/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/noxlock/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/noxlock/my-anime-openings-list/MAOL/authentication/views.py", line 12, in register form.save() File "/home/noxlock/.local/lib/python3.8/site-packages/django/contrib/auth/forms.py", line 131, in save user.save() File "/home/noxlock/.local/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 67, in save super().save(*args, **kwargs) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/base.py", line 774, in save_base post_save.send( File "/home/noxlock/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/noxlock/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 181, in &lt;listcomp&gt; (receiver, receiver(signal=self, sender=sender, **named)) File "/home/noxlock/my-anime-openings-list/MAOL/personal_list/models.py", line 45, in create_profile Profile.objects.create(user=instance) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create obj.save(force_insert=True, using=self.db) Exception Type: TypeError at /auth/register/ Exception Value: save() got an unexpected keyword argument 'force_insert' Typically this is usually due to missing **kwargs in the definition … -
I want to save as null in database but not allowed (Django)
I have a model like this: class Maca(models.Model): maca_number = models.PositiveIntegerField( db_column='Maca Number' ) and a form like this: class MacaForm(forms.ModelForm): maca_number = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Maca Number'})) so I want if the user not fill this field to send empty in database. I got this error ValueError: Field 'maca_number' expected a number but got '' Thank you in advance -
Is somebody tried to build a 3D CAD wep app running on Browser?
I found an App which are able to use on Browser. I gonna build a similar one using python. Is possible by python? If someone experienced this, please help me. Thanks in advance! -
How do I fix this Getting no reverse match error in django
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My singlepost.html html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] View.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect ,get_object_or_404 from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context) def add_post(request): pass def post_detail(request,slug): indentified_post = get_object_or_404(Post,slug=slug) return render(request,"blog/post-detail.html",{'post':indentified_post}) i am iterating through posts and using the post-detail.html page all-post.html. {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <br> <h1 style="text-align:center;">All Tractors</h1> <ul> {% for post in posts %} <br> {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %} -
Deploying Django and Vue app to Elastic Beanstalk in the same instance
I want to deploy my Django/Vue app to Elastic Beanstalk. I have different endpoints for BE and FE through ports 8082 and 8080 respectively. I want to use Elastic Beanstalk's multicontainer deploy feature and deploy my BE and FE apps to the same instance. I initialized and configured my EB app and environment as a Python app. I can now deploy my BE to EB and access the api through the provided url. Is it possible to configure my EB app to deploy FE on the same instance as well. Or do I need to deploy my Vue app to another instance? It is described how to deploy multicontainer apps to eb here : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_v2config.html. But it only describes a php app running on nginx and it's not useful to me. Thanks.