Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django media audio currentTime reseting to 0
I'm trying to make a audiobook website with django(3.2.13). But when I try to go back and forth. The currentTime of the audio goes back to 0. I have tryed it in side of console too. It's weird because when the audio file is small it work's!(When I refesh) But if the file is Big It doesn't work. All of the audios are work's good if I don't change the currentTime of the audio. What could be the problem? #djangotemplate <audio class="playing-audio" src="{{ audio.audios.url }}"></audio> #views.py class AudioDetailView(DetailView): model = Audio template_name = "audios/audio_detail.html" pk_url_kwarg = "audio_id" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) audio_id = self.kwargs.get("audio_id") audio = Audio.objects.get(id=audio_id) context["img_url"] = f"/static/img/{audio.category.title}.png" return context -
How can I redirect in the quick_view page after deleting feedback?
My motive is that I want to redirect quick_view.html after deleting particular feedback on a particular product. How can I do it? views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) context = { "quick_view":quick_view, } return render(request, 'quickVIEW_item.html', context) def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK'), ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) After deleting the particular feedback, I want to redirect to the quick_view page of that particular product. Now shows below error: def DeleteFeedback(request,id,quick_view_id): ProductREVIEWS.objects.get(pk=id).delete() messages.success(request,"Successfully your feedback deleted.") return redirect('quick_view', quick_view_id) urls.py: path('quick_view/<int:quick_view_id>/', views.quick_view, name="quick_view"), path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), path("DeleteFeedback/<int:id>/", views.DeleteFeedback, name="DeleteFeedback") error: TypeError at /DeleteFeedback/22/ DeleteFeedback() missing 1 required positional argument: 'quick_view_id' Request Method: GET Request URL: http://127.0.0.1:8000/DeleteFeedback/22/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: DeleteFeedback() missing 1 required positional argument: 'quick_view_id' Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce ' 'site\\env\\lib\\site-packages'] Server time: Sat, 16 Jul 2022 05:49:50 +0000 -
Ajax success event not working in Django templates
Hello I am using Ajax to POST method inside Django template on modal submit $submitButton.click(function(event) { event.preventDefault(); $submitButton.addClass('disabled').prop('disabled', true); $error.prop('hidden', true); if (!$reasonField.val()) { handle_error(`{% trans "Entering a reason is mandatory!" %}`); return; } const reason = $reasonField.val(); $.ajax({ type: 'POST', url: `/staffing/midterm_contract/${reservation_id}/ignore/`, dataType: 'text', data: { comment: reason, }, headers: { 'X-CSRFToken': "{{ csrf_token }}", }, success: function(data) { console.log("Test") if (data) { console.log("Success") close() } else { handle_error(data.message) } }, error: function(jqXHR, textStatus, errorThrown) { handle_error(errorThrown); }, }); }); views.py class IgnoreMidtermContract(SupportUserRequiredMixin, UserPassesAllTestsMixin, View): user_tests = (UserTests.is_support_reservation, ) def dispatch(self, request, *args, **kwargs): self.reservation = get_object_or_404(Reservation, pk=kwargs['pk']) self.ignore_midterm_contract_reason = request.POST.get('comment', None) return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.reservation.ignore_midterm_contract_reason = self.ignore_midterm_contract_reason self.reservation.midterm_contract_ignored_at = timezone.now() self.reservation.midterm_contract_ignored_by = self.request.user self.reservation.midterm_contract_is_ignored = True self.reservation.save() return JsonResponse({'success': True}) success event inside Ajax POST method not working and not showing any error I tries with many was that was suggested other this kind of questions but still not working I tried to remove dataType: 'text', still not working Is there anything wrong or something add or remove? -
how to count the top_topics based on number of groups created on that topic in django?
I have such models where topic is related with room as shown in code. How can i count the top_topics as i have counted in top_groups. I want to count top_topics based on number of group created on that topic. I hope you get what i mean. Models.py class Topic(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Room(models.Model): admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg') name = models.CharField(unique=True, max_length=100) description = models.TextField(null=True, blank=True) members = models.ManyToManyField(User, related_name='members', blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.name Views.py def home(request): q = request.GET.get('q') if request.GET.get('q') != None else '' groups = Room.objects.filter(Q(topic__name__icontains=q)| Q(name__icontains=q) | Q(description__icontains=q) ) top_groups = Room.objects.alias( num_members = Count('members') ).order_by('-num_members')[:5] group_count = groups.count() topics = Topic.objects.all()[:5] context = {'groups':groups, 'group_count':group_count, 'topics':topics, 'top_groups':top_groups} return render(request, 'base/home.html', context) I am basically confused in relationship. what can be the way i can access Room from Topic? Please help !!!! -
How to add comma separated values in Django Admin
I have these two models, Category, and Subcategory. They look like this: class Category(models.Model): name = models.CharField(max_length=100) class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100) So far, this all works great! I'm creating all the starter categories and subcategories for my projects and only have about 15 categories, but each category may wind up having tens of subcategories under them... What I need is a way to be able to copy and paste a ton of subcategory values into the admin form via a comma separated list, and create multiple new objects all at once, all with the same category as their foreign key. This will save me hundreds of clicks. How can this be accomplished? -
two (2) django applications on same vps server
I have two django applications deployed on the same server. I wanted to know if the two applications can coexist together without causing problems when the server handles requests with nginx and gunicorn . -
How to limit results with annotate and prefetch_related in django?
I'm have a django query with annotate and prefetch_related. all_questions = Question.objects.all().annotate(is_complete=Case( When( pk__in=completed_questions.values('pk'), then=Value(True) ), default=Value(False), output_field=BooleanField()), votes_difference=Count('like')-Count('unlike'), ).order_by('votes_difference').prefetch_related('tags') I want to limit the result to, let's say 100 objects. I tried this query, all_questions = Question.objects.all().annotate(is_complete=Case( When( pk__in=completed_questions.values('pk'), then=Value(True) ), default=Value(False), output_field=BooleanField()), votes_difference=Count('like')-Count('unlike'), ).order_by('votes_difference')[100].prefetch_related('tags') I got this error message 'Question' object has no attribute 'prefetch_related' I checked the official documentation but can't seem to find any example related to it. Is it possible to do so? -
How to send the value of select while onchange in django?
<main> <section class="topbar"> <select name="category" id="category" onchange="location.href='{% url 'searchbycategory' this.value %}'"> <option value="none">All category</option> <option value="book">Books</option> <option value="notes">Notes</option> <option value="fur">Furniture</option> <option value="draw">Drawing tools</option> <option value="others">Others</option> </select> </section> is there something like this.value to send the current selected value this is my path in url.py: path('searchbycategory/str:category',views.searchbycategory,name="searchbycategory") -
Google cloud and wagtail getting database error on deployed website
I'm deploying django wagtail website on google cloud successfully, but I'm getting: "settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details." error. I even tried hardcoding database values in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'url to sql stuff', 'USER': 'user I register', 'PASSWORD': "my password", 'PORT': '8080', 'HOST': "127.0.0.1" } } I can confirm values are correct and database exists on cloud. Still getting the same error. What should I do? -
How can I implement update and delete in django view?
I am creating a movie review website. In it, I want to be able to allow a User to make one comment on one movie and then Update or Delete that comment. But I am only able to implement POST right now. How do I change the view, html or model? Questions to ask How do I go from here to keep my comments visible so that if one user comments on one movie, I can't comment on it? How can I keep the comments posted by a user at the top of the comment list so that they can be updated and deleted? An example of what we would like to implement is Rotten Tomatoes. class Comment_movie(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'movie') indexes = [ models.Index(fields=['user', 'movie']), ] def view_movie_detail(request, movie_id): if not(Movie.objects.filter(id=movie_id)): Movie(id = movie_id).save() movie = Movie.objects.get(id=movie_id) if request.method == "POST": form = Comment_movie_CreateForm(request.POST) if form.is_valid(): Comment_movie( comment = form.cleaned_data['comment'], user = request.user, stars = form.cleaned_data['stars'], movie = movie ).save() return redirect('view_movie_detail', movie_id=movie_id) else: form = Comment_movie_CreateForm() data = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") … -
Django & AJAX to show DB objects upon user's input submission
I'm pretty new in the Web development world, have been using Django so far. I've been trying to figure out how to render data back to page after clicking on a submit button, so I see I'll need to use AJAX for that purpose. I've created a very simple app just to understand the basics of AJAX. However, googling, I couldn't really find a basic straight-forward implementation so I kinda got lost... What I'm trying to achieve: I have a model called Country: class Country(models.Model): name = models.CharField(primary_key=True, max_length=35) continent = models.CharField(max_length=10) capital = models.CharField(max_length=35) currency = models.CharField(max_length=10) And a super simple main page that asks the user to insert some country name. The idea is to bring to the page all the info from the DB. So it would look like this: main page snapshot Main page HTML body: <body> <h2><em>Please type a country name:</em></h2><br><br> <div class="container"> <form id="get_info" method="post"> {{ form }} {% csrf_token %} <input id="submit_button" type="submit" name="submit" value="Get info"> </form> </div> </body> views.py: from django.shortcuts import render from country_trivia import forms def main_page(request): get_info_form = forms.GetInfo() return render(request, 'country_trivia/index.html', {'form': get_info_form}) forms.py: from django import forms class GetInfo(forms.Form): country_name = forms.CharField(label="") I've seen some examples using … -
django-cqrs No model with such CQRS_ID: X
i'm trying to use CQRS design on django using the library "django-cqrs", something is not right, cause i've followed the documentation very closely, but it throws me this error No model with such CQRS_ID: categoria. ('CQRS is failed: pk = 6 (categoria), correlation_id = None, retries = 0.',) No model with such CQRS_ID: categoria. Model for cqrs_id categoria is not found. my models of both the master and the replica, are with the CQRS_ID completely the same, I have copied the entire line of the master model to place it in the replica model, and still throws me the error Here are the models code Master: from dj_cqrs.mixins import MasterMixin from django.db import models class Categoria(MasterMixin, models.Model): CQRS_ID = 'categoria' nombre = models.CharField(null=False, max_length=200) Replica: from dj_cqrs.mixins import ReplicaMixin from django.db import models class CategoriaRef(ReplicaMixin, models.Model): CQRS_ID = 'categoria' id = models.IntegerField(primary_key=True) nombre = models.CharField(null=False, max_length=200) So it's kind of curious, i don't know where the error is -
django allauth login callback going to server behind firewall
My django instance is behind a firewall and there is a front facing proxy that exposes it. Whenever a login request (to google) comes from a user using the proxy website, the callback uri is to the server behind the firewall, and since that server isn't exposed, the login fails. This happens regardless of what servers I have enabled in the google oauth portal. -
Testing redirects to parameterized URLs when creating object
I have a view for creating blog posts which redirects the user to a form to fill the blog post content like this: from django.views import View from app.models import BlogPost class CreateBlogPost(View): def post(): new_post = BlogPost.objects.create() return redirect(reverse('post_edit'), args=[new_post.id]) class EditBlogPost(View): ... And my urls are the following: from django.urls import path from app.views import CreateBlogPost urlpatterns = [ path('post', CreateBlogPost.as_view(), name='post_create'), path('post/<int:pk>/edit', EditBlogPost.as_view(), name='post_edit') ] I would like to: test the CreateBlogPost by asserting that it redirects to post/<some_id>/edit. I've tried: using the method assertRedirects from django's SimpleTestCase, but couldn't find a way to make this work. I'm also using pytest-django, in case that's relevant. -
DRF - Prevent users from referencing objects that do not belong to them
I have two models like so with a parent child relation: models.py class Bank(...): user = models.ForeignKey('User', ...) class Account(...) bank = models.ForeignKey('Bank', ...) user = models.ForeignKey('User', ...) I am using DRF and want to provide API access to these models. I want to ensure that Users can only access their own data. On the viewsets I can retrict the querysets to just the objects the user "owns" like so: views.py class BankViewSet(...): def get_queryset(self): return self.queryset.filter( user = request.user ) And I can do the same for Accounts. However, how can I stop a user from creating an Account via POST request with a Bank that they do not own? I want to ensure that users can only create Accounts that belong to a Bank that they own. How can I enforce/check that the Bank in the Account POST request contains the same user as the requestor? -
Updating parent form with a select2 field when closing another modal form django
I am trying to add this functionality to my django app. I have a select2 field as a ForeignKey data type field in my main form. Now, I also got an "add" button right next to it that when clicked, opens a modal with another form. That form creates another instance for the select2 to look for, another entry, so that's good and settled. But, I want it to, when submitting the form in the modal, instead of the main form page being refreshed and having to refill all other fields again, it automatically selects the instance it has just created on the select2 field. I am fairly new to the front-end aspect of it all so it would be great to have some guidance. -
Django - populate data in update form with Bootstrap Modal
I'm creating a simple app with 2 models. Unit & Note. In Note model, there is a field with Foreign Key (Unit). Now I'm trying to edit each note inside Unit's detail view (not Note detail view) with Bootstrap Modal. I don't know how to get note_id so that I can use it for Note's form instance. Right now, I only get empty form and if I save it, it overwrite the original data with empty data. Here is a code. I'd really appreciate your help since I've been stuck with this for quite long time. models.py class Unit(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) number = models.CharField(max_length=10) def __str__(self): return self.number class Meta: ordering = ('number',) def get_absolute_url(self): return reverse("unit-detail", args=[str(self.id)]) class Note(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name="notes") title = models.CharField(max_length=30) note = models.TextField() created_date = models.DateField() def __str__(self): return self.title views.py def unit_detail(request, pk): unit = Unit.objects.prefetch_related('notes').get(id=pk) # How do I pass instance for note_form ??? note_form = NoteModelForm(instance=???) context = { "unit":unit, "note_form":note_form, } return render(request, "units/unit_detail.html", context) # Update note class NoteUpdateView(generic.UpdateView): template_name = "units/note_update.html" form_class = NoteModelForm def get_queryset(self): queryset = Note.objects.all() return queryset def get_success_url(self): unit_id = self.object.unit.id return reverse("unit-detail", … -
hello I am a beginner Django developer I am facing issue in Payment integration with stripe
I'm creating an ecommerce web app in django everything is working fine without payment integration (stripe) Now when i integrated stripe the only thing I'm facing is that i cannot pass the total amount in cart to my charge.py function which will simply charge the card the amount in cart views.py from locale import currency from django.urls import reverse import stripe import datetime from django.shortcuts import redirect, render from django.http import JsonResponse from .models import * import json from .utils import cookieCart,cartData,guestOrder stripe.api_key = "sk_test_51LGVvZLOhjoxBBs0eMasEkak6VRuemLVz7KEHubNhiFwiGwMPO20RNLiDXJEkQwiCU7eGIuBawvSjpSKX8ImI7S600soefS68W" # Create your views here. def home(request): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.all()[:3] context = {'products': products, 'cartItems': cartItems} return render(request, 'Home.html',context) def aboutUs(request): return render(request, 'aboutUs.html') def contactUs(request): return render(request, 'contactUs.html') def terms(request): return render(request, 'Terms.html') def store(request): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store.html', context) def productDetails(request,id): data=cartData(request) cartItems=data['cartItems'] products = Product.objects.get(id=id) context = {'products': products, 'cartItems': cartItems} print(products) return render(request, 'productDetails.html', context) def cart(request): data=cartData(request) cartItems=data['cartItems'] order=data['order'] items=data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'cart.html', context) def checkout(request): data=cartData(request) cartItems=data['cartItems'] order=data['order'] items=data['items'] print(order.get_cart_total) context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'checkout.html', context) def update_item(request): data = json.loads(request.body) productId = … -
Django generic.UpdateView NOT updating values upon successful POST
Below I am trying to update a specific form (OrganizationForm): Template is Rendering with the form fields and existing values in the fields. Upon Submission of the form the POST request is successful. ISSUE: The changes are not being saved to the DB. # Views.py class OrganizationDetails(LoginRequiredMixin, UpdateView): login_url = '/user/login/' redirect_field_name = 'redirect_to' model = Organization form_class = OrganizationForm template_name = 'organization/org_details.html' success_url = reverse_lazy("organization") def get_object(self): queryset = super().get_queryset() return queryset.get(pk=self.request.user.organization.pk) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) curr_org = self.request.user.organization heading = TermsHeading.objects.filter(organization=curr_org) content = TermsContent.objects.filter(heading__organization=curr_org) context['headings'] = heading data = dict() for item in heading: x = [] for desc in content: if desc.heading == item: x.append(desc) data[item] = x context['data'] = data return context What I have tried: I have overrided the 'POST' method in the class with the following: # def post(self, request): # print(request.POST) # form = OrganizationForm(request.POST) # if form.is_valid(): # form.save() # print("Valid and Saved") # else: # print(form.errors) # return super(OrganizationDetails, self).post(request) Terminal Output: [16/Jul/2022 02:44:15] "GET /user/myorganization/ HTTP/1.1" 200 29699 Not Found: /favicon.ico [16/Jul/2022 02:44:15] "GET /favicon.ico HTTP/1.1" 404 5037 [16/Jul/2022 02:44:25] "POST /user/myorganization/ HTTP/1.1" 302 0 [16/Jul/2022 02:44:25] "GET /user/myorganization/ HTTP/1.1" 200 29699 Not Found: /user/myorganization/Roboto-Regular.ttf [16/Jul/2022 02:44:25] "GET … -
Django Evaluate Queryset of ManyToMany relationship early to use in async function
I'm using a Django-Channels consumer for websocket async communication. I have something like this below class Command(UUIDModel): owner = models.ForeignKey(AUTH_USER_MODEL, default=None, on_delete=models.SET_DEFAULT, null=True, blank=True, related_name='commands') name = models.CharField('Name', default='New Command', max_length=128, blank=True, null=True) class Secret(UUIDModel): owner = models.ForeignKey(AUTH_USER_MODEL, default=None, on_delete=models.SET_DEFAULT, null=True, blank=True, related_name='secrets') command = models.ManyToManyField(Command, blank=True, related_name='secrets') @sync_to_async def get_command(pk): command = Command.objects.get(id=pk) return command class CommandConsumer(AsyncWebsocketConsumer): @log_exceptions async def command(self, event): log.debug(event) command = await get_command(event.get('command').get('id')) log.debug(command) log.debug(command.secrets) log.debug(command.secrets.all()) # Fails here return I get a SynchronousOnlyOperation error when running this, right when it evaluates the queryset for Secrets in the ManyToMany field. Is there a way to force the queryset to evaluate ahead of time in the synchronous get_command function, instead of in the async websocket? That way I can easily access the secrets via command.secrets. -
React-django on cpanel - MIME type ('text/html') is not a supported stylesheet
I am developing a react-django application. My application runs locally. When I install it on a server running on cpanel, it just shows a blank page. My provider checked it and made the following statements: The python application is installed correctly on cpanel The cause of the error should be found on the developer side. I made the simplest possible application: Simpletest Local mode: "Simple Test" text appears in the title and under the react logo (see attached image) enter image description here cpanel: Python application: the text "Simple Test" appears only in the title and sends the following error message enter image description here Does anyone have any idea where I can look for the error? The application can be cloned from github: enter link description here I would like to ask someone to try and install it on a server running cpanel. Does it have an application running? Many thanks from Tipti. -
Can I build a full-stack site using only django
New into web dev Wondering if you can build a full-stack site with only django no html no css only django -
Django; getattr(): attribute name must be string while saving django model
Whenever i submit this form, i get this error and the form does not submit successfully. what is possible the error and how do i go about fixing this? class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to=user_directory_path, default='default-product.jpg') title = models.CharField(max_length=1000) status = models.CharField(max_length=100, choices=PRODUCT_PUBLISH_STATUS, default="in_review") content = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=1000000000, decimal_places=2) file = models.FileField(upload_to=user_directory_path, blank=True, null=True) views = models.IntegerField(default=0) slug = models.SlugField(unique_for_date=True) def __str__(self): return self.title -
Flask Error Use 'FLASK_APP=pushup:name' to specify one
I am trying to build my first flask application and I keep getting the error when I typed '''flask run''' My folder is called pushup and it is on my desktop Error: Failed to find Flask application or factory in module 'pushup'. Use 'FLASK_APP=pushup:name' to specify one. -
How to display model attributes in django on web app
I am creating a portfolio site with djnago. Now suppose i have a blog and i want to show the blog title,small summary and the link. I've created a model as below: class Blog(models.Model): blog_title=models.CharField(max_length=50) summary=models.TextField(blank=False) blogLink=models.URLField() def __str__(self): return self.blog_title def get_summary(self): return self.summary def get_link(self): return self.blogLink I can fill these values in the admin page but how can i show it in the web app so that other people can access the links. I also have a context processor to user details like first name etc. Should i have different context processors for different classes that I create. Just a beginner and trying out projects to skill myself I