Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth override default template with custom template
I'm currently trying to override a Django allauth template. So far, I followed all the recommendations on similar questions to mine: overriding default templates of django-allauth How to override template in django-allauth? However, my goal is just change the default Django allauth without making new views or forms. (In previous projects I used to override the default forms constructor classes with the helper of Django Crispy Forms which is not possible in this particular case.) I believe there is a way to ignore the {{form}} variable and just define a working form from scratch. Currently, I have my template being successfully being displayed when I navigate to 'account_login'. However, when I press Sign In nothing happens. Here is my myapp/templates/account/login.html file: {% extends 'base.html' %} {% load staticfiles %} {% block title %} Sign In to {{ SITE_NAME }} {% endblock %} {% block body %} <div class="centered"> <img class="logo" src={% static 'imgs/logo.png' %} alt="" width="100" height="100"> <form id="login_form" class="form-signin" method="post" action="{% url 'account_login'%}"> {% csrf_token %} <label for="inputLogin" class="sr-only">Email address or Username</label> <input type="text" id="login" class="form-control" placeholder="Email or Username" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="password" class="form-control" placeholder="Password" required> <div class="note mb-3"> <label> <input type="checkbox" value="remember" id="remember"> Remember … -
ProgrammingError at /registration/post_report/ values_list on EmptyQuerySet used in a queryset filter returns full set
I want to show all the record list from the table on the basis of option selected and if i didn't select any option i want to show all the data of every year on the basis of land area ,number of storey , plinth area and so on. I'm able to show data on the basis of option selected but unable to show data if i didn't select any option from the select box or if I select All from the select boxes , I want to show all the data related to option list of question select box of every year of every ward number . Please, help me. views.py def post(request, template_name='report.html'): if request.method == 'POST': context={} all_ward = NewRegistrationModel.objects.values_list('ward_no', flat=True) data = request.POST.get('question') print data ward_no = request.POST.get('ward_no') if ward_no=="": allward=all_ward startdate = request.POST.get('start_date') enddate = request.POST.get('end_date') if startdate == "" : start_date='2073-01-31' if startdate == '' : start_date='2073-01-31' elif startdate != "": start_date = startdate if enddate == "": end_date='2077-12-30' if enddate == "": end_date='2077-12-30' elif enddate != "": end_date = enddate if startdate and enddate: date = NewRegistrationModel.objects.filter(registration_date__gte=start_date, registration_date__lte=end_date) context['date'] = date if ward_no > 0: ward = NewRegistrationModel.objects.filter(ward_no=ward_no).annotate(Count('ward_no')) if data == 'landinfo' : … -
Django dictionary not passed?
Trying to pass python dictionary to my django template. But it seems to not be passed while rendering. I have read documentation and few sites, but can't find solution. It must be simple... #views.py def home(request): context = {} links = getLinks() for link in links: splited = getRate(link).split() # print(splited) key = splited[1] context[key] = float(splited[0]) print(context) return render(request, 'home.html', context) home.html: {% for key, value in context.items %} <a href="{{key}}">{{value}}</a> {% endfor %} I print dictionary in my terminal, so it definitely exists and contains everything I need. But can't refer to it in my template. -
Access list data with index in jinja template
I am getting this error when I use any number with this also I have seen some solution on this site but I'm not able to solve or I am doing it in wrong way. A Help will be appreciated. THANKS django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]' from 'resend_lst[0]' {% for attendee_data in attendees_data %} <tr> <td>{{ attendee_data.attendee.name }}</td> <td>{{ attendee_data.attendee.email }}</td> <td>{{ attendee_data.attendee.mobile }}</td> <td>{{ attendee_data.attendee_response.date }}</td> </tr> **resend_lst is a list data type and I need to access this with its index in that loop ** {% if resend_lst[{{forloop.counter}}] == '0' %} <style> #response-{{forloop.counter}}{ display:none; } #cancel-{{forloop.counter}}{ display:none; } #loader-next-{{forloop.counter}}{ display:none; } #ajax-loader{ text-align: center; width:19px; height:19px; } </style> {% else %} <style> #response-{{forloop.counter}}{ display:none; } #cancel-{{forloop.counter}}{ display:none; } #loader-next-{{forloop.counter}}{ display:none; } #ajax-loader{ text-align: center; width:19px; height:19px; } </style> {% endif %} <-- some task --> {% endfor %} -
how to save data into database using Django-ajax-json?
I failed to save data into database using Django-ajax-json. following is my code: this is views.py: def new_stok(request, pk): supplier = get_object_or_404(Supplier, pk=pk) data = dict() if request.method == 'POST': form = NewStokForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True stoks = supplier.stoks.all() data['html_stok_list'] = render_to_string('stoks2.html',{'pk':supplier.pk,'stoks':stoks}) else: data['form_is_valid'] = False else: form = NewStokForm() context = {'supplier': supplier, 'form': form} data['html_form'] = render_to_string('includes/partial_stok_create.html', context, request=request, ) return JsonResponse(data) javascript file: stok.js $(function () { $(".js-create-book").click(function () { var data_id = $(this).attr("data-id"); $.ajax({ url: '/supplier/' + data_id + '/new/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); $("#modal-stok").on("submit", ".js-stok-create-form", function () { var form = $(this); var data_id = form.attr("data-id"); var url_action = '/supplier/' + data_id + '/new/'; $.ajax({ url: url_action, data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#stok-table tbody").html(data.html_stok_list); // <-- Replace the table body $("#modal-book").modal("hide"); } else { $("#modal-book .modal-content").html(data.html_form); } } }); return false; }); }); The function $("#modal-stok").on("submit", ".js-stok-create-form", function ()) got problem where I don't know how to pass the {{ supplier.pk }} back to stok_list.html upon saving. My stok_list.html file: {% extends 'base2.html' %} {% load static %} {% … -
How to access database from other app in Django in same project
I am new to Django, the way I understand the database migration structure is allotted per app. If I have several apps inside the project, how do I refer the models/data in database on another apps? Let's say I have these apps: Home Expense Income I have created User, Balance, Expense, Income models on Home app. How do I access these data on Expense and Income? Is there a better way to implement project structure as I am not quite sure that my current implementation is the right one. Is it correct to implement models that should be accessible from all apps within a certain app? -
If else statement not working in ajax template
title_posts.html {% extends "main/base.html" %} {% load static %} {% load humanize %} {% block styles %} <link rel="stylesheet" type="text/css" href="{% static 'main/css/title_posts.css' %}"> {% endblock styles %} {% block content %} <style> body { background-image: url("{{ game.cover_display.url }}"); background-repeat: no-repeat; background-size: 100% auto; background-color: #171717; background-attachment: fixed; background-position: 0 3.5rem; } </style> <div class="container black2 container-nav gamenav"> <ul class="quantico"> <li><a class="text-light nav-link" href="{% url 'title-posts' game.title %}">Updates</a></li> <li><a class="text-light nav-link" href="{% url 'title-bugs' game.title %}">Bugs</a></li> <li><a class="text-light nav-link" href="https://twitter.com/{{ game.twitter }}">Twitter</a></li> <li><a class="text-light nav-link" href="https://www.reddit.com/r/{{ game.reddit }}">Reddit</a></li> </ul> </div> <div class="container black container-position"> <div class="row justify-content-center"> <div class="col-md-3 text-center"> <img class="cover-image-height" src="{{ game.cover.url }}"> </div> <div class="col-md-9"> <p>{{ game.description| safe }}</p> <div class="btn-group"> <button type="button" id="platform" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select Platform </button> <div class="dropdown-menu" id="plat-form-options"> {% for platform in game.platform.all %} <option class="dropdown-item" value="{{ platform.id }}" onclick="platFormSelect('{% url 'title-posts-ajax' title=game.title platform_id=platform.id %}', '{{ platform }}')">{{ platform }}</option> {% endfor %} </div> </div> </div> </div> <hr> <div id="posts_data"> </div> {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info … -
How to ake my reply form receive input django?
Hey guys I was making a reply form from which users can reply to the comments,I use the comments form two times 1st for the comments itself , 2nd for the reply .BUT when i initialise the form for replies .It gives me the data of the model .It doesn,t appear as a form Here,s the models.py of comments and replies class CommentManager(models.Manager): def all(self): qs = super(CommentManager,self).filter(parent = None) return qs class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) pub_date = models.DateTimeField(auto_now_add = True) parent = models.ForeignKey('self',null = True,blank = True) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name def replies(self): return Reply.objects.filter(parent = self) @property def is_parent(self): if self.parent is not None: return False return True Here,s the views.py of comments and replies def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm( request.POST or None) subscribe = Subscribe() parent_obj = None if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() return redirect('index') try: parent_id = request.POST.get('parent_id') except: parent_id = None if parent_id: parent_qs = Comments.objects.filter(id = parent_id) if parent_qs.exits(): parent_obj = parent_qs.first() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return … -
I would like to know how to actually update an on object by a user who created it
I would like to know how to update an object that was create by a User(hunter). Here is the model of the product below class Product(models.Model): title = models.CharField(max_length=250) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') url = models.TextField() hunter = models.ForeignKey(User, on_delete=models.CASCADE) And here is the create method which is made for creating an object def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url = request.POST['url'] else: product.url = 'http://' + request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) Can you please help me create an update method so that only a user who created this product can delete it? Thank you very much -
Stripe charge not being generated
I implemented Stripe into a form I have. Two issues are currently occuring, the first is after the Stripe payment is accepted, the view is not rediecting. The second issue is even though the Stripe payment is being accepted, a charge is not being created on the test server, which I am viewing on the Stripe dashboard. I am unsure what is causing this problem and would appreciate any help with this. HTML <!-- Form --> <form action="{% url 'view:book_lesson' lesson.id %}" method="POST" autocomplete="off" id="book"> {% csrf_token %} <div class="hidden"> {% load tz %} {% timezone user.time_zone %} <p><span id="start">{{ lesson.lesson_datetime_start|time }}</span></p> <p><span id="end">{{ lesson.lesson_datetime_end|time }}</span></p> {% endtimezone %} </div> <div class="text-center"> <div class="form-group"> <div class="ins-left"> <p>{% render_field form.booked_instrument value=lesson.lesson_instrument %}</p> </div> <div class="date-right"> <p>{% render_field form.booked_date value=lesson.lesson_datetime_start|date %}</p> </div> </div> <br /> <br /> <br /> <div class="form-group"> <label>Length</label> {{ form.booked_length }} </div> <br /> <div class="form-group"> <label>Time</label> {{ form.booked_time }} </div> <div class="ins-left"> <p>Price: $<span id="price"></span></p> </div> <input type="hidden" id="stripeToken" name="stripeToken" /> <input type="hidden" id="stripeEmail" name="stripeEmail" /> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button" id="customButton">Book Now</button> </div> </div> <script src="https://checkout.stripe.com/checkout.js"></script> </form> <script src="{% static 'view/javascript/price.js' %}"></script> JS var handler = StripeCheckout.configure({ key: 'pk_test_R5oVIdGG0ELimZmnldXORhAK', //image: '/square-image.png', token: function(token) { … -
How to display JSON data in proper format on GET request
I have created small API in django and Python. I am reading data from URL(Remote API) and storing into database when I do the GET request. Everything looks good and I am displaying same data on my server's endpoint as well.But it display in non readable format. Please refer the below code view.py: from rest_framework import generics from customer.models import Customers from .serializers import CustomersSerializer, CustomersKeySerializer import json import urllib.request import pyodbc from django.http import HttpResponse, JsonResponse def customer_get(request): j = urllib.request.urlopen("https://web.njit.edu/~jsd38/json/customer.json") customer_data = json.load(j) cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=DAL1281;" "Database=Test;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute("SELECT CustomerId FROM dbo.Customers") CustomerIdRows = [x[0] for x in cursor.fetchall()] CustomerIds = Customers.objects.values_list('CustomerId', flat=True) for customer in customer_data: CustomerId = customer["@Id"] Name = customer["Name"] PhoneNumber = customer["PhoneNumber"] EmailAddress = customer["EmailAddress"] StreetLine = customer["Address"]["StreetLine1"] City = customer["Address"]["City"] StateCode = customer["Address"]["StateCode"] PostalCode = customer["Address"]["PostalCode"] if int(CustomerId) not in CustomerIds: cus = Customers() cus.CustomerId = CustomerId cus.Name = Name cus.PhoneNumber = PhoneNumber cus.EmailAddress = EmailAddress cus.StreetLine = StreetLine cus.City = City cus.StateCode = StateCode cus.PostalCode = PostalCode cus.save() if int(CustomerId) not in CustomerIdRows: cursor.execute( "INSERT INTO dbo.Customers(CustomerId,Name,EmailAddress,StreetLine,City,StateCode,PostalCode) VALUES (?,?,?,?,?,?,?)", (CustomerId,Name,EmailAddress,StreetLine,City,StateCode,PostalCode)) cnxn.commit() queryset = Customers.objects.all() serializer_class = CustomersSerializer return HttpResponse(customer_data) -
Why my django form is not submitting while submitting via AJAX?
I am trying to upload an image via AJAX with a Django view. Here is my HTML form. <form class="BackgroundImageUplaoder" action="/uplaod" id="form2">{% csrf_token %} <input type="file" accept="/image*" name="image" multiple="false" /> <button type="submit">Uplaod</button> While the corresponding ajax is:- $(document).ready(function(){ $('#form2').submit(function(){ var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var formdata={ 'image':$('input[name=image]').val(), }; console.log("Formvalue is taken"); console.log(formdata.image); $.ajax({ type:'POST', url:'/Upload/Background/', data:formdata, dataType:'json', encode:true, headers:{ "X-CSRFToken": csrftoken }, processData:false, contentType:false, }) .done(function(data){ console.log(data); if(!data.success){//we will handle error if (data.password){ console.log(data.password); $('#password_error').text(data.password); } return false; } else{ window.location='/'; } }); event.preventDefault(); }); }); and django view is:- def uploadbackground(request): if request.method=="POST": form=BackgroundImageUplaod(request.POST,request.FILES) if form.is_valid(): instance=form.save(commit=False) myobject=HomeScreen.objects.get(profile__user=request.user) if myobject: myobject.image=instance myobject.save() return JsonResponse({'success':True}) else: sample=HomeScreen(profile__user=request.user,image=instance) sample.save() return JsonResponse({'success':True}) else: form=BackgroundImageUplaod() return JsonResponse({'image':'An error is encountered while uplaoding','errors': [(k, v[0]) for k, v in form.errors.items()]}) The console is showing following error According to my view, The form is not validating.After validating my forming. I am checking that whether the instance correponding to current logged in user exist or not.If yes i am updating that instance otherwise creating new object -
How to redirect 2 pages backwards in django
There's a project I'm working on and I'm not particularly sure if what I'm trying to do is possible with django. Please direct me if it is. Here it goes: In the registration and login functionalities of my app, I designed the registration to do the job of both registration and login (i.e When a user fills in the registration form and the data is not conflicting with other user's data, especially the username, the new user is automatically registered logged in). Here is what I have so far. views.py: def register(request): """This view takes care of registering the user and logging in the user at the same time""" if request.method == 'POST': form = UserNameFormRegistration(request.POST, request.FILES) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] the_email = form.cleaned_data['email'] the_first_name = form.cleaned_data['first_name'] the_last_name = form.cleaned_data['last_name'] profile_picture = form.cleaned_data['profile_picture'] user = authenticate(username=username, password=password) user.email = the_email user.first_name = the_first_name user.last_name = the_last_name login(request, user) return redirect(request.META.get('HTTP_REFERER')) else: form = UserCreationForm() context = { 'form': form, } return render(request, 'registration/register.html', context) registration form (register.html): <!-- form --> <div class="limiter"> <div class="container-login100"> <div class="wrap-login100"> <form class="login100-form validate-form" action="{% url 'register' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <span class="login100-form-title p-b-34"> <b><font style = "font-family:Open … -
gunicorn.socket: Failed with result 'service-start-limit-hit'
I was deploying a django app and it failed because for some reason the gunicorn.socket file was not created even though before adding nginx it worked perfectly fine so I searched the internet and found this answer where the guy says that the reason for this is the virtual environment but I'm sure there must be a way around it using venv right? the log I get from nginx: connect() to unix:/run/gunicorn.sock failed (11 1: Connection refused) while connecting to upstream, error from gunicorn: gunicorn.socket: Failed with result 'service-start-limit-hit'. I'm 100% sure the problem is with gunicorn not with the setup of nginx becuase I did check for the gunicorn file and it did not exist. -
Django Autcomplete light for making searchable dropdowns
I want to make a Django form with one choicefield that can autocomplete itself from a set of values defined. Basically, I have a database table called the player and it has an attribute playername in it. I want to make a form with choicefield that contains data from that player table with search availability, Here is my try: Views.py from django.shortcuts import render,redirect from django import forms from pages.models import Team ,Player,Match from decimal import * from django.contrib.admin.widgets import FilteredSelectMultiple from dal import autocomplete class PlayerAutocomplete(autocomplete.Select2ListView): def get_list(self): x=[] y=Player.objects.values('PlayerName') for i in range(0,len(y)): x.append(y[i]['PlayerName']) return x class PlayingForm(forms.Form): def get_choice_list(): x=[] y=Player.objects.values('PlayerName') for i in range(0,len(y)): x.append(y[i]['PlayerName']) return x player = autocomplete.Select2ListChoiceField(choice_list=get_choice_list,widget=autocomplete.ListSelect2(url='player-autocomplete')) urls.py from django.urls import path from django.conf.urls import url from pages import views from pages.views import PlayerAutocomplete urlpatterns = [ path('',views.home,name='home'), path('about/',views.about,name='about'), path('administrator/',views.administrator,name='administrator'), path('add_team/',views.add_team,name="add_team"), path('add_player/',views.add_player,name="add_player"), path('add_match/',views.add_match,name="add_match"), path('add_playing/',views.add_playing,name="add_playing"), path('add_playing_teams/',views.add_playing_teams,name="add_playing_teams"), url( r'^player-autocomplete/$', PlayerAutocomplete.as_view(), name='player-autocomplete', ), ] add_playing_teams.html {% extends 'admin_base.html' %} {% block content %} <center> <div class="container" style="margin-top: 100px;"> <h1>Add Playing teams</h1> <div style="width:30%"> <form role="form" method="post"> {% csrf_token %} {% for error in form.non_field_errors %} <div class="form-group has-errors text-danger small"style="margin-left:100px;"> {{error}} </div> {% endfor %} {% for field in form %} <div class="form-group has-errors text-danger small"style="margin-left:100px;"> … -
html in email from Django
I'd like to know whether or not I can include anchor tags in the 'txt_message' that I send from django. Will they be displayed as hyperlinks within the email that the user sees? My understanding is that the txt_message is only rendered when the email server won't accept the html_message. I want to ensure that the user sees and can click on the hyperlink that I send them (regardless of whether I they are seeing the txt_message or the html_message. send_mail(subject, txt_message, from_email, to_email, html_message=html_message, fail_silently=False) Thanks for the help! -
How to validate string values in django?
in PHP there's a function called filter_var() which validate String values and filter it , Is there any function do the same in django -
How to make dynamic markers in Java using google map api
The idea is to make an interactive map (using googlemap API) I have successfully imported a map. Next I want to make dynamic markers. So lets say i have some customers. In the database (each customer has a location). I am using Ajax to collect location information from a function in view.py this will query database and get a dictionary containing the customers location information and return it to html. So far I have been able to get this Jason Response. my view.py def requestAjax(request): customerList = Customer.objects.all().values('id', 'customer_number','postcode','latitude','longitude') data = list(customerList) return JsonResponse(data, safe=False) I have a Ajax call setInterval(ajaxCall, 3000); //300000 MS == 5 minutes function ajaxCall() { $.ajax({ url: '/maps/my_ajax_request/', datatype: 'json', type: 'GET', success: function (data) { alert("Data OK"); }, failure: function(data) { alert("Got an error dude"); } }); } and my html <div id="googleMap" style="width:100%;height:800px;"></div> <script> function myMap() { var mapProp= { center:new google.maps.LatLng(52.190680,5.959044), zoom:8, }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); } Now the question is how can I process the Ajax response and use the customer data to make dynamic markers!!!!! Thanks -
Django channels: pass form data to consumer
I'm learning Django and I'm working in a webpage where I need to offer the user the possibility to log in to an external service. I can't simply use the traditional Django views system because otherwise, I would lose the connection with a simple refresh. For that reason, I thought about using Django Channels. My problem now is how do I send the data to the consumer class? Using the consumers.py given in the tutorial, I would like to send data from a form submission to the connect function and then make the connection if the login to the external service is ok. Then, in that scenario, I could use the clientinstance and the methods from these external services. So, in short, is it possible to send form data the consumer? And would this be ok, with respect to security in case of sensitive data? from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): ###### ## login to external service ###### #get login data from form submited when the websockted is initiated username = ... pass = ... self.client = Client(cd['username'], cd['password']) if client: await self.accept() # Receive message from room group async def chat_message(self, event): message = … -
Populating UserProfile at User registration
I'm trying to populate a User profile field at user registration (I've read that this is not recommended however is required for my app) model.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) twitter = models.CharField(max_length=50) def create(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create, sender=User) form.py class RegForm(UserCreationForm): email = forms.EmailField(required=True) username = forms.CharField(max_length=50, required=True) twitter = forms.CharField(max_length=50, required=True) class Meta: model = User fields = ( 'username', 'twitter', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.userprofile.twitter = self.cleaned_data['twitter'] if commit: user.save() return user Currently, I'm getting the error "User has no userprofile" (first time using Django, sorry if this is a silly question, I couldn't find anything that helped online) -
Django and the form_valid method
I'm following a Django Course about user authentication and authorisation. But the point is that I don't really understand the form_valid() method here : class ArticleCreateView(CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'body') # new def form_valid(self, form): # new form.instance.author = self.request.user return super().form_valid(form) I cannnot figure what this method returns. Thanks -
Media files not showing up after deployment
So I just finished deploying a django app to the internet and for some reason media files won't show up. here's the link I followed everything works perfectly fine but medias and the weird thing is the media does exist at the exact path it should come from but it won't show up. -
test for post API receiving status code 200 instead of 201
My test for my post method API receive status code 200 but should 201 I tried to find where is problem but i couldn't. It would be easier if i would get error status 4xx but i have no idea why post method could receive code 200. My API view works fine so this must be problem with test code but I really don't have idea what may cause this problem. Maybe I'm wrong and status code 200 is ok, but I think that post method should receive status 201. test_api.py def test_post_logged_in(self): product = Product.objects.get(id=1) self.client.login(username='test', password='test123') data = { 'nick': self.user.id, 'rate': '1/5', 'content': 'here is comment', 'product': product.id } response = self.client.post(reverse('add_comments', kwargs={'id': product.id}), data, format='json') self.assertEqual(response.status_code, 201, f'expected Response code 201, instead get {response.status_code}') views.py class CreateComment(APIView): def get_object(self, id): try: return Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 def get(self,request, id): product = self.get_object(id) serializer = ProductSerializer(product) return Response(serializer.data) def post(self, request,id): serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save(nick=request.user, product=self.get_object(id)) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to filter quaryset from django forms
I'm trying to get a dropdown menu that shows current users List objects Models.py class List(models.Model): name = models.CharField(max_length=100, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') def __str__(self): return self.name class Meta: unique_together = ['name', 'user'] I tought I could do something like this in forms: class data_form(forms.Form): def get_user(self, request): user = request.user.pk selection = forms.ModelChoiceField(queryset=List.objects.filter(user=user).all()) num = forms.IntegerField() but first of all it doesnt work and second multiple sources told that you are not supposed to have requests at model's and requests should always be on views level. So I changed the queryset to this: class data_form(forms.Form): selection = forms.ModelChoiceField(queryset=List.objects.all()) num = forms.IntegerField() this basicly works but problem is it shows all objects, even the ones that are created by other users and I cant have that. Can I filter that somehow in views or something? views.py: @login_required def app(request): form = list_form form2 = data_form user = request.user.pk user_lists = List.objects.filter(user=user) context = {'user_lists': user_lists, 'form': form, 'form2': form2} return render(request, 'app/app.html', context) In views I already render buttons filtered with query set with these objects and it works with user and user_lists but how do I do it for "form2"? -
Django - how to pass temporary data from one view to another in order to return information from api
Hello, so I would like to pass the 'name' variable in the form_valid function that is located within my SearchView class (FormView) to the PlayerList class (TemplateView,SearchView). I want to do this because I want to access the name variable from SearchView, and on the PlayerList view use it to search an API database and display information. Must I save it to a database before I continue? Or is there a way efficiently solve this problem?