Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run function on loading DetailView in Django
I would like to execute a function immediately upon loading a DetailView. Specifically, I have a Market model, and when users land on a DetailView using that model, I want the current_price on the relevant market to be saved in the most_recent_price feature of the relevant user. Here's what I have right now, which isn't doing anything - I don't get any error message or anything, it simply doesn't get executed: class MarketDetailView(LoginRequiredMixin, DetailView): model = Market template_name = 'question.html' login_url = 'login' def set_current_price_for_user(self, **kwargs): pk = self.kwargs['pk'] market = Market.objects.get(pk=pk) user = request.user user.most_recent_price = market.current_price I feel like I'm missing something basic here. What am I doing wrong? -
How to close all html popup window when I click logout button in django backend
I tried to close all the html popup window when I clicked on logout button. But when I tried with Httpresponse and javascript It's not working. So I have attached my code for better understanding. I can't understand what's happening. I tried to render with Httpresponse in views.py with the help of Javascript, But It's failed. Thanks in advance... Success.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <!-- Interaction Script Here --> <script type="text/javascript"> function win() { var secondWindow= window.open("{% url 'choice' %}","choice","height=700,width=700,scrollbars=no"); if(window.close()){ secondWindow.close(); } } function win1(){ var thirdWindow= window.open("authordetails.html","AUTHOR DETAILS","height=800,width=700,scrollbars=no"); if(window.close()){ thirdWindow.close(); } } function win2(){ var fourthWindow= window.open("maxsales.html","MAX. SALES","height=800,width=700,scrollbars=no"); if(window.close()){ fourthWindow.close(); } } function win3(){ var fifthWindow= window.open("updatePrice.html","CHANGE PRICE","height=800,width=700,scrollbars=no"); if(window.close()){ fifthWindow.close(); } } function win4(){ var sixthWindow= window.open("report.html","REPORT","height=800,width=700,scrollbars=no"); if(window.close()){ sixthWindow.close(); } } window.onload=function(){ window.resizeTo(700,700); window.open("{% url 'success' %}","success","width=700,height=700,scrollbars=no"); }; </script> </head> <body> <nav class="fixed-top"> <input type="checkbox" id="check" /> <label for="check" class="checkbtn"> <i class="fas fa-bars"></i> </label> <label class="logo">Book Managment</label> <ul> <li><p style="font-size:17px;color:white;">Welcome {{user.username}}</p></li> <li><a href="{% url 'logout' %}">Logout</a></li> </ul> </nav> <!-- Interaction Code Here--> <div class="suc"> <h1>Your Interaction</h1> <form action="{% url 'success' %}" method="POST"> <fieldset class = "insertion"> <div> <label for="insert">Insert Values</label> <button type="button" id="insert" onclick="win()">SELECT</button> </div> <div> <label for="details">View Author Details</label> <button type="button" id="details" … -
How to generate coverage reports programmatically using Coverage.py?
At present, I am generating coverage reports via coverage.py, by giving the coverage command which would thus generate an HTML report. Now I want to automate this whole process such that in my Django project I should have a URL and a corresponding view that should generate the coverage report for the whole project and render it as HTML file..! -
Django Serve Special files like favicon and manifest
How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), path('favicon.ico', favicon, name='favicon'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) favicon = never_cache(TemplateView.as_view(template_name='myproject/favicon.ico')) The index works, but favicon doesn't. So what about the other files that need to be served? How can I define those files (anywhere from 4-20 files) to be served by uwsgi? -
Passing data from html to python
It is necessary to obtain information from the selected cell from the html file and then work with it in views.py. Is it possible and how to do it? Thank you in advance! <tbody> {% for element in qz %} <tr> <td class="counterCell"></td> <td style="display: none">{{ element.0 }}</td> <!-- information is needed for this cell when it is selected --> <td>{{ element.1 }}</td> <td>{{ element.2 }}</td> <td><span class="glyphicon glyphicon-trash"></span></td> </tr> {% endfor %} </tbody> -
'QuerySet' object has no attribute 'favourite'
Can any one please fix the problem. Here in this view I am getting the error . Actually I am adding the favourite list to the product and tried to write the view . listings/views.py from django.shortcuts import get_object_or_404, render from .choices import price_choices, bedroom_choices, state_choices from django.core.paginator import EmptyPage, PageNotAnInteger,Paginator fetch the data from .models import Listing, Comment from realtors.models import Realtor from sellers.models import Seller Create your views here. def index(request): #varname = modelname.objects.all() # listings = Listing.objects.all()//displaying in any order # now displaying the list in the latest date(descending) listings = Listing.objects.order_by('-list_date').filter(is_published = True) if listings.favourite.filter(pk = request.user.id): is_favourite = True #creating the pagination paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) is_favourite = False context = { 'listings' : paged_listings, 'is_favourite':is_favourite } return render(request, 'listings/listings.html', context) def listing(request, listing_id): if request.method == "POST": name = request.POST['name'] message = request.POST['message'] proid = listing_id query = Comment(message = message, name = name ) # stars = stars query.proid_id = proid # query.stars = stars query.save() listing = get_object_or_404(Listing, pk = listing_id) seller = Seller.objects.all().filter(pk = listing_id) comment = Comment.objects.all().filter(proid = listing_id) context = { 'listing' : listing, 'comments':comment, 'seller':seller } return render(request,'listings/listing.html',context) def search(request): queryset_list = … -
Django: How to show second form on submit of first form without refreshing the page?
Hi all I am trying to display a second form without refreshing the page when I click on submit button of first form. Is there any solution for this? Thanks in advance. -
Deploying a Django Application (Apache, Passenger, Virtualenv)
Im stuck in deploying my working Django Application on a production PLESK server. The project can be started as a development server successfully by typing: httpdocs# cd mysite httpdocs/mysite# source myvenv/bin/activate httpdocs/mysite# export LD_LIBRARY_PATH="/usr/local/lib" httpdocs/mysite# python manage.py runserver <freyt.de>:8000 Then, if I point the browser to freyt.de:8000 I can see my app. Fine. Right now, I'm trying to call my app by Passenger from Apache. When checking with "passenger-config restart-app" it seems to run, but when curl freyt.de it shows me html with 403 Forbidden. So, I assume my Django app is not started successfully. This is my current folder structure: https://i.stack.imgur.com/8xNMG.png I already adjusted some topics in PLESK as follows: Apache Webserver: wsgi is activated I created a Service Plan and subscribed it with my domain freyt.de In the Service Plan under tab "Webserver" I added additional directives for HTTP as follows. PassengerEnabled On PassengerAppType wsgi PassengerStartupFile passenger_wsgi.py In the Service Plan under "Hosting Parameters" I enabled SSH access to the server shell: /bin/bash For the "Domain" I set the Document root to "..httpdocs/public". Also I added in "Apache & nginx Settings" the same directives. (I also tried without, but dont seem to have an effect.) Some details at … -
DRF when generating cookie sessionid
I am creating /auth/ page on my Django Rest Framework site. And I can not save session id. Have i create this cookie or its creating automatically? My auth view: class AuthView(APIView): permission_classes = (permissions.AllowAny,) renderer_classes = [TemplateHTMLRenderer] @csrf_exempt def get(self, request): return render(request, 'login.html', {}) @csrf_exempt def post(self, request): serializer = AuthFormSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.data username = data.get('username') password = data.get('password') if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST, template_name='login.html') user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND, template_name='login.html') self.token, _ = Token.objects.get_or_create(user=user) user_token = Token.objects.get(user_id = user.pk) if (datetime.now() - user_token.created.replace(tzinfo=None)).days > 10: Token.objects.update(user_id=user.pk, key=Token.generate_key(user.pk), created = datetime.now()) context = {'token': self.token.key} # return Response(, status=HTTP_201_CREATED, template_name='') return HttpResponse(json.dumps(context), content_type="application/json") -
How to extend field in UserCreationForm in django?
I have been trying to add a phone number field in UserCreationForm so that on registration a user gives its phone number but unfortunately phone number is not storing. it accepts the Phone number on the registration page but it doesn't show the phone number on the webpage. I think it is not storing. forms.py class myCreateForm(UserCreationForm): ph= forms.CharField(max_length=400, required=True, label='Phone') class Meta: model = User fields = ['first_name', 'last_name' ,'username', 'email', 'password1', 'password2','ph'] def save(self, commit=True): user = super(myCreateForm, self).save(commit=False) user.ph = self.cleaned_data["ph"] if commit: user.save() return user views.py def register(request): form = myCreateForm() if request.method == "POST": form = myCreateForm(request.POST) if form.is_valid(): form.save() return redirect('loginPage') return render(request , 'register.html', {'form' : form}) template {%for i in user%} Hi {{i.first_name}}<br> Username : {{i.username}}<br> E-Mail : {{i.email}}<br> Phone : {{i.ph}}<br> {%endfor%} but on my webpage, it shows everything except phone number. Please Help Me Out -
How to keep Celery running in Django (drf) + Redis + WSGI (EC2)
I don't think its a very new question. I just could not find the right answer. I am trying to use Celery for background tasks while implementing a backend with the Django Rest Framework. I have a Redis server. Celery is working as expected with celery worker -A my_project --loglevel=info However, it does not work if I sop this command. How do I keep that running? I have found a blog with supervisor. I just want to know what is the standard (as well as easier) to do this. -
Formset not applying required=True
I use a formset, made of several forms, where each form contains a ModelChoiceField. However, while I wrote required=True for this field, I am able to post data although I do not select anything in it (when looking at the HTML source code, I can indeed check that required is not included in the select tag). Moreover, formset.is_valid() returns True contrary to what I expected. So far, I have managed to solve this by adding 'required' : 'required' in attrs (see below), but I guess it is not the usual way to achieve this. Here are my forms.py: class InitialForm(forms.Form): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True, label="Poule", widget=forms.Select(attrs={'class': 'select'})) nb_rounds = forms.IntegerField(min_value=1, max_value=5, required=True, label="Nombre de manches", initial=1, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) nb_teams = forms.IntegerField(min_value=2, max_value=5, required=True, label="Nombre d'équipes", initial=2, widget=forms.NumberInput(attrs={'class': 'input', 'style': 'width:5ch'})) class FinalForm(forms.Form): def __init__(self, *args, **kwargs): group = kwargs.pop('group') nb_rounds = kwargs.pop('nb_rounds') super(FinalForm, self).__init__(*args, **kwargs) self.fields['teams'] = forms.ModelChoiceField(queryset=Team.objects.filter(group=group), required=True, label="Equipe", widget=forms.Select(attrs={'class': 'select', 'required': 'required'})) for i in range(nb_rounds): self.fields['score_%i' % i] = forms.IntegerField(min_value=0, max_value=50, required=True, label="Score", initial=0, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) and views.py def initial_new_game(request): # GET request if request.method == 'GET': form = InitialForm() return render(request, 'initial_form.html', {'form': form}) # POST request else: form = InitialForm(request.POST) if form.is_valid(): request.session['group_id'] … -
Django: How do I upload an image to a folder named after the article slug
I defined two models Article, Article_photos. Photos present in each article is stored in the relevant Article_photos model. I intend to store multiple photos per article in this way. I want each photo to be uploaded to a folder by naming the folder in this manner: {slug}_images. This is Article model: class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Author') article_title = models.TextField() article_content = models.TextField() slug = models.SlugField(max_length=30, blank=True) ... def save(self, *args, **kwargs): self.slug = slugify(self.article_title) super(Article, self).save(*args, **kwargs) And the Article_photos model to store one or more photos: class Article_photo(models.Model): article = models.ForeignKey('Article', on_delete=models.CASCADE) photo = models.ImageField(upload_to='{}_images'.format(article.slug)) Now, when i'm running makemigrations, it's returning this error: AttributeError: 'ForeignKey' object has no attribute 'slug'. How do rename the folder in the pattern I want? -
Use mongoDB with django 3.0
As I said in the title I want to integrate mongoDB next to my Postgres Database in a Django3.0 project. I used to use djongo* but it seems it's not compatible with the latest version of Django. What do you think is the best connector to use mongoDB in a Django project ? *https://github.com/nesdis/djongo -
Django Serve Other Files and Default Route
If I should split this up into 2 questions I will but I have 2 major questions here. First Question How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) So what about the other files that need to be served? Am I supposed to be defining them all manually, or is there a way to do it properly? Second Question How can I get django to redirect all unknown urls to / Since the react part of the project uses react-router, it changes the url in the SPA. So if I go to /options in the app, it works, but if I were to … -
how to remove these usercreation forms instruction in django
class Driver_SignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = ("username", "email", "password1", "password2") model = User help_texts = { 'username': None, 'email': None, 'password1': None, 'password2': None, } this is the code i already use the help text none but not working properly here is image of that -
POST request return 405 on auth (nginx angular)
i'm using django and angular with nginx. I get 405 not allowed when i try to post to /auth/. my nginx conf: server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /home/dev/projet-name/frontend/my-app/dist/tryangular; include /etc/nginx/default.d/*.conf; location / { try_files $uri $uri/ /index.html; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } location ~ ^/(api|admin)/ { include uwsgi_params; uwsgi_pass SERV_IP:3031; } } Djnago is on the same server. I don't even know where i messed up -
Disable CSRF validation on Wagtail Page
I'm trying to do a curl POST request on a wagtail page. Unfortunately I hit the CSRF protection. I tried to disabled CSRF on this specific type of page using the @csrf_exempt decorator, without success. Here is my pseudo code (one of many attemps): @method_decorator(csrf_exempt, name='serve') class NewsletterPage(MedorPage): class Meta: verbose_name = _("newsletter page") Seems like the csrf verifition is done even before the serve method is called. Any idea? thanks -
Counting the many-to-many value in filter
I am trying to do like this my class is here class TweetJson(models.Model): authors = models.ManyToManyField(Station) and filter MyText.objects.filter(Q(authors__count__gte=1)) However it returns. Related Field got invalid lookup: count is there any way to count the number of many-to-many objects? -
The value in __init__ doesn't returns correct value?
I have a model in django: class Game(models.Model): gaming = models.BooleanField(default=False) def __init__(self, *args, **kwargs): super(Game, self).__init__(*args, **kwargs) self.old_gaming = self.gaming Now, when I print the value of self.old_gaming it comes out to be True instead of False while working from an application. Whereas, while I work on django-admin it shows False. Why is it showing two different values? -
Django - How to get the object attribute before updating in Update class based view?
I'm learning Django and I'm struggling with the Class Based View of Django. I would like to access the object attributes before the update in order to show the user what was the previous attributes. Here my class view : class GroupUpdateView(LoginRequiredMixin, UpdateView): model = GroupName fields = ['name', 'description'] template_name = 'dashboard/groups/group_update_form.html' group_name_before_editing ="" #I wanted to write model.name here #Overrive def form_valid(self, form): return super().form_valid(form) def get_success_url(self): messages.success(self.request, "The group %s was updated successfully" % ( self.group_name_before_editing)) return reverse_lazy('dashboard:group-update', args=(self.object.pk,)) In get_success_url(), I would like to show the user the previous name of the group that has been updated. I tried also with the get_context_data() but was not able to obtain the result. Could you help please ? How to get the current model attributes ? -
Django search : query multiple table, join them then return the queryset
I'm building a search for my product price tracking app and there're 2 models products and scans class products(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=100) product_link = models.CharField(max_length=255) image_link = models.CharField(max_length=100) store_name = models.CharField(max_length=100) class Meta: verbose_name_plural = "products" def __str__(self): return str(self.product_name) class scans(models.Model): scan_id = models.IntegerField(primary_key=True) prod_id = models.IntegerField(models.ForeignKey("scrape.Model", on_delete=models.CASCADE)) price = models.IntegerField() scanned_time = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = "scans" def __repr__(self): return str(self.prod_id) the search is supposed to take a name(string) input and query for a store name in the same table and query for price which is in another table and return the query set with the product_name, store_name and price. I've tried this class searchResults(ListView): model = 'products', 'scans' template_name = 'result.html' # let query = GET request from form (in home.html) def get_queryset(self): queryset = [] rawquery = self.request.GET.get('q') queries = rawquery.split(" ") for q in queries: prodresults = products.objects.filter( Q(product_name__icontains=q) ).distinct() for prodresult in prodresults: prod_id = products.objects.get(product_name=prodresult).product_id prod_price = scans.objects.get(prod_id=prod_id).price for result in prodresults: #joins results toegther queryset.append(result) queryset.append(prod_price) return list(set(queryset)) The code broke at prod_price = scans.objects.get(prod_id=prod_id).price with scans matching query does not exist. -
django-autocomplete-light add parameter to query url (in version 3.3)
I'm using django-autocomplete-light in a django admin change_form.html page, however I need to change dynamically the GET parameters of the URL depending on another field. I have already tried to replicate this answer django-autocomplete-light add parameter to query url, but failed since I am using version 3 Tried this way: $("#id_city").change(function(){ url = '{% url "custom-pop-autocomplete" %}'; $('#id_p').attr('data-autocomplete-light-url', url + `?city=${$(this).val()}`); $('#id_p').trigger('autocompleteLightInitialize'); }); This way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { $(this).initialize }); and this way: $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { window.__dal__initialize(this); }); None of them working to reinitialize django-autocomplete-light. I just need to change the URL. -
Django DeprecationWarning Use of .. or absolute path
I am getting a lot of these warnings in production but not on devstack which is making me curious to know about this warning and how to get rid of this. Apparently there is no information which imports is causing the issue. I am looking for any tools, documentation that explains this Deprecation warning when this will raise an exception in the future and steps to get rid of this warning. thank you! [__init__.py:1566] - /edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages/pkg_resources/__init__.py:1158: DeprecationWarning: Use of .. or absolute path in a resource path is not allowed and will raise exceptions in a future release. -
Insert Data From HTML to Django Template
I want to save data from HTML template into database Model. I want to override this toplaner_name, toplaner_avatar, toplaner_price everytime I submit the Form. The img and span tags are dynamically changing by JS template <form method='POST'> {% csrf_token %} <div class="player-on-map toplaner"> <img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map"> <span class="nickname">Szygenda</span> <span>Price: 1500</span> </div> <button type='submit'>SAVE TEAM</button> </form> models.py class Team(models.Model): toplaner_name = models.CharField(max_length=30, default='Ibo') toplaner_avatar = models.ImageField(default='avatar.png') toplaner_price = models.IntegerField() JS toplaners.forEach(toplaner => toplaner.querySelector('.btn').addEventListener('click', function(){ toplaner_on_map.innerHTML = toplaner.innerHTML; toplaner_on_map.querySelectorAll('.btn, .position, .player-price').forEach(item => item.classList.add('hide')) }))