Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelChoiceField on a Foreign Key not working
I have a foreign key inside a model and I want to customize the way it appears in my form. By default a select appears with option values as id. I want to change the option values to be another field. Can't get it to work.Please help. Models.py: class PriceDetails(models.Model): id = models.AutoField(primary_key=True) size = models.ForeignKey(SizeOd, blank=True, null=True, on_delete=models.DO_NOTHING) def __str__(self): return str(self.id) class SizeOd(models.Model): size = models.DecimalField(unique=True, decimal_places=1, max_digits=5) multiplier = models.DecimalField(decimal_places=3, max_digits=8) def __str__(self): return str(self.size) Forms.py: class PriceDetailsForm(forms.ModelForm): size = forms.ModelChoiceField(queryset=SizeOd.objects.order_by('size'), to_field_name="multiplier", required=False) class Meta: model = PriceDetails exclude = ('id',) Views.py: class PriceDetailsInline(InlineFormSetFactory): model = models.PriceDetails form = forms.PriceDetailsForm fields = '__all__' factory_kwargs = {'extra': 1, 'can_delete': False} Default: <select> <option value='id1'>size1</option> <option value='id2'>size2</option> </select> Expected: <select> <option value='*multiplier1*'>size1</option> <option value='multiplier2'>size2</option> </select> -
How do I pass instance in models within signals?
I have the following model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) education = models.CharField(blank=True, null=True, max_length=255) country = models.CharField(blank=True, null=True, max_length=255) facebook = models.CharField(blank=True, null=True, max_length=255) whatsapp = models.CharField(blank=True, null=True, max_length=255) description = models.TextField(blank=True) I am creating a signal that after saving user, it creates a profile associated to that, the code below is my signal. I don't know how to pass instance in Profile.objects.create. I muse that passing instance like instance.education, instance.country ... is wrong or there are other errors in this signal because I am getting this error User has no profile. Please help me fix it, thank you signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print("INSTANCE BELOW:") print(instance) if created: Profile.objects.create(user=instance, education=instance.education, country=instance.country, facebook=instance.facebook, whatsapp=instance.whatsapp, description=instance.description) -
django: create submodel for a model
How to create a model like the image where I can add as many players as I want from admin-panel -
SerializerMethodField always returns the same value and excludes fields
I have an API that sends some sample data. I am trying to change the representation of the output, using Django's SerializerMethodField(). But it doesn't work as expected since I am always getting back the same data and the fields are not shown in my output. I have three models that look like this: 2 Models which are related through foreign keys: class Machine(models.Model): machine_name = models.CharField(max_length=120) def __str__(self): return self.machine_name class Project(models.Model): project_name = models.CharField(max_length=120) def __str__(self): return self.project_name And one model like this: class Simulation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) machine = models.ForeignKey(Machine, on_delete=models.CASCADE, default=1) project = models.ForeignKey(Project, on_delete=models.CASCADE, default=1) I create data like this: test_api_local(method="post", data={"machine":2, "project":1 }) What I'd like to achieve is that when I send data with machine:2, it should write the name of this machine2 into the result. Like 'machine' : 'machinenametwo'. I tried this using SerializerMethodField. I know it is ReadOnly, but since I do not actually change the data only manipulate it I thought something like this might work: class SimulationSerializer(serializers.ModelSerializer): machine = serializers.SerializerMethodField() project = serializers.SerializerMethodField() class Meta: model = Simulation fields = ('project', 'machine', ) def get_machine(self, obj): print(obj.machine) project_name = obj.project.project_name return str(project_name) This does not work, since … -
How to show updated date after an ajax call in Django
I'm trying to implement review section in my Django app. The below is my source code for posting and listing reviews of a store. I've already done creating a review with Ajax, but I can't figure out how to show the newly created review after the Ajax call. Like how like button works in social media, I can easily update the like button based on the response of Ajax call by changing attr() or html(). But, this doesn't apply to this review case since it shows a store's reviews with for looping. So I feel like I gotta figure out how to let the for loop run again after the Ajax call. Have anyone dones this before? HTML <div class="review-new"> <div class="my-rating" name="rating"></div> <textarea class="form-control" rows="5" id="ratingTextarea"></textarea> <input class="global-btn" stlye="float:right" type="button" value="Submit" id="review-submit" data-url="{% url 'boutique:post-review-api' store.domainKey %}" data-store-id="{{ store.id }}"> </div> ... {% for i in store.review_set.all %} ... {% endfor %} views.py class ReviewPost(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, store_domainKey=None, format=None): rating = request.data['rating'] content = request.data['content'] store_id = request.data['storeId'] store = Store.objects.get(id=store_id) new_review = Review() new_review.store = store new_review.review_score = rating new_review.content = content new_review.created_by = request.user new_review.save() reviews = store.review_set.all() data = { 'reviews': reviews … -
Can't access post data in update view for comparisons
I am trying to access certain fields in my post data to do logic checks, if those test fail I want to display an error message. The logic works fine upon initial form creation but it doesn't seem to work in update view. It seems like none of the if statements are able to access the value in the post data. here's my function in my updateview class: def post(self, request, **kwargs): if trips.objects.filter(van_used=request.POST['van_used']).exists(): for next in trips.objects.exclude(first_name=request.POST['first_name']): if datetime.datetime.strptime(request.POST.get('trip_start'), "%Y-%m-%d").date() <= next.trip_start: if request.POST.get('van_used') == next.van_used: messages.warning(request, request.POST.get('van_used') + ' is in use during that time period. Pick another vehicle or change trip dates.') return render(request, self.template_name, {'form': self.form_class}) -
where am gonna wrong with search?
views.py def userlogout(request): logout(request) return HttpResponseRedirect(reverse('userlogin')) def Search(request): if request.method == 'POST': search=request.GET['srch'] if search: match=Blog.objects.filter(Q( blog_title_icontains=search)| Q( blog_description_icontains=search)| Q(blogcategories_icontains=search) ) if match: return render (request,"search.html",{"sr":match}) else: messages.error(request,"no results found") else: return HttpResponseRedirect('/search/') return render (request,'index.html') # index.html {% csrf_token %} blog/urls.py path('search/', views.Search, name='search'), *****it gives me error: Exception Type: MultiValueDictKeyError Exception Value: 'srch' please help me how can i search in my blog by using existing template. -
how can I get Djando-ajax popup button to work?
I am trying to create a popup form for a New Task in my calendar, but I have never get it to work. I am using Ajax for this purpose. Here is my code. The Ajax is located in the static folder under the name "plugin.js" base.py {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bookstore</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/plugin.js' %}"></script> {% block javascript %} {% endblock %} </body> </html> calendar.html {% extends 'cal/base.html' %} {% block title %} Quality Assurance Calendar {% endblock %} {% block content %} <div class="clearfix"> <a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a> <a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a> {% if user.is_authenticated %} <button type="button" class="btn btn-primary show-form"> <span class="glyphicon glyphicon-plus"></span> New Task </button> {% endif %} </div> {{ calendar }} <div class="modal-fad" id="modal-task"> <div class="modal-dialog"> <div class="modal-content"></div> </div> </div> {% endblock %} part of the view.py def task_create(request, task_id=None): # if not request.user.is_authenticated: … -
Adding new Django app - Getting 404 page not found
I have created a directory called vsdk which includes service_development (a voice application) and my newly created application called dashboard. Unfortunately I can’t seem to get the main page of dashboard to work. I get a 404 error when trying to access 127.0.0.1:8000/dashboard/, while doing everything similar to what I’ve done with service_development. Would someone be able to help me? Vsdk\settings.py INSTALLED_APPS = [ 'vsdk.service_development.apps.ServiceDevelopmentConfig', 'vsdk.dashboard.apps.DashboardConfig', 'storages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Vsdk\dashboard\apps.py from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class DashboardConfig(AppConfig): name = 'vsdk.dashboard' verbose_name = _("Dashboards") Vsdk\urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.urls import include, path admin.site.site_header = _("Petrichor Rain Service") urlpatterns = [ url(r'^', admin.site.urls), url(r'^vxml/', include('vsdk.service_development.urls')), url(r'^vxml/', include('vsdk.dashboard.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Vsdk\dashboard\urls.py from django.shortcuts import render from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] -
Key error while accesing a dataframe column in django
I am doing a Django project. I am converting my models into a dataframe for my convenience. I am stuck up in a step where I get a Keyerror of a column "Sales(L)". If I run the same script in shell or spyder it is not throwing any error. Have a look at my script below. smtv = MTD.pdobjects.all() se = Salesexecutive.pdobjects.all() smtv_df = smtv.to_dataframe().reset_index(drop=True) se_df = se.to_dataframe().reset_index(drop=True) se_df=se_df.rename(columns={'Customer_Account':'Customer_Code'}) smtv_df['Sales_Value']=smtv_df['Sales_Value'].astype(float) smtv_df['Sales_Value']=(smtv_df['Sales_Value']/100000).apply(lambda x: round(x, 2)) smtv_df=smtv_df[(smtv_df['Invoice_Date']>=month_st) & (smtv_df['Invoice_Date']<=tdt)] df = pandas.merge(smtv_df,se_df[['Customer_Code','Ecode','Sales_Executive']],on='Customer_Code', how='left') df[['Ecode', 'Sales_Executive']] = df[['Ecode','Sales_Executive']].fillna('Unknown') filt_df={} filt_df['RGN']=request.POST.get('RGN', None) filt_df['MKU']=request.POST.get('MKU', None) filt_df['Vertical']=request.POST.get('Vertical', None) filt_df['Channel']=request.POST.get('Channel', None) fikt={k: v for k, v in filt_df.items() if v!=''} for k,v in fikt.items(): df=df[df[k]==v] df1=pandas.pivot_table(df,index='MKU',values=['Sales_Value'],aggfunc='sum').replace(numpy.nan,0) df1=df1.rename(columns={'Sales_Value':'Sales(L)'}) df1['Sale Target(L)']=df1['Sales(L)']*1.25 Please suggest some ideas to fix this issue. Thanks -
How to send a request?
I need to send a request with the following data "order": { "server_callback_url": "http://site.id/callback", "currency": "UAH", "amount": "1400", "order_type": "settlement", "response_url": "http://site.id/test/responsepage/", "order_id": "test1234561467462099.19", "operation_id": "test1234561467462099.19", "order_desc": "test order", "merchant_id": 700001, "receiver": [ { "requisites": { "amount": 100, "merchant_id": 500001 }, "type": "merchant" },{ "requisites": { "amount": 200, "merchant_id": 600001 }, "type": "merchant" }, ] } I need to send them to https://api.fondy.eu/api/settlement But I never did that. I am not familiar with DRF at all. Tell me how to implement it, please. -
Is there a wrong way to name Class Based Views in Django?
this is a question about code style and best practices. In our Django project we have Class Based Views named like this: urls.py path('project/<int:pk>/clone/', CloneView.as_view(), name='clone'), path('project/<int:pk>/delete/', ProjectDelete.as_view(), name='project-delete'), path('project/<int:pk>/optimize/', ProjectOptimize.as_view(), name='project-optimize'), path('project/<int:pk>/report/', ReportView.as_view(), name='report'), as you can see, some of them we say MyClassView.as_view() and in others we just say MyClass.as_view(). But I also noticed that in the Documentation they always use the first form: https://docs.djangoproject.com/en/2.2/topics/class-based-views/ Something that also caught my attention is that we never use view in the name, for example: name=clone-name. My question is: is there any noticeable advantage of explicitly saying in the class name that this class is a view? Is it "wrong" not to use it? I would like to keep our code base consistent. Thank you all! -
Unable to set UploadedFile object size at run time in Django
Reference doc for UploadedFile. Trying to change the file size in the test case. from django.core.files.uploadedfile import UploadedFile @fixture def photo(self): file_obj = StringIO() image = Image.new("RGBA", size=(50, 50), color=(256, 0, 0)) image.save(file_obj, "png") file_obj.seek(0) return UploadedFile(file_obj, name="test.png", content_type="image/jpg", size=2000000) I tried to change the file size for a test case self.photo.size = 10000001 def test_invalid_photo_size(self): self.photo.size = 10000001 response = self.client.post(reverse("registration_register"), data=self.data) But when I fetch value for the photo in the form, I'm getting the default value i.e 2000000. self.cleaned_data.get('photo').size It should have returned the 10000001 as size in the form. I'm not clear why this is happening? Any alternative other than creating a new photo from scratch. -
Как исправить ошибку? Выбивает ошибку
Пытаюсь вывести локацию по id, но почему то номер id выводит а вот саму локацию не подтягивает. views: def one(request, location_id): locations = Location.objects.get(id=location_id) return render(request, 'one_lok.html', {'locations': locations}) HTML: {% block locations %} <h1> TEST CUST 2 </h1> {{ location.id}} {% for location in locations %} <h1> TEST CUST 1 </h1> {{ location.id}} {% endfor %} {% endblock locations %} -
Node fetch not returning response data on mobile but works on desktop
Really stuck with this one. Fetch gets Django REST API json data and works great on desktop. But it loads nothing on mobile devices and tablets, with one exception and that is for some odd reason it works on my phone on Chrome only. Other phones and tablets with Chrome do not work. Code is as follows: import React, { Component } from "react"; import cookie from "react-cookies"; import "whatwg-fetch"; import Food from "./Food"; import { Link } from "react-router-dom"; import logo from "../images/db_logo_must.webp"; import burger from "../images/burger.svg"; class Desserts extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { menu: [], elClass: false }; } loadPosts() { let endpoint = "/menu/food/"; const csrfToken = cookie.load("csrftoken"); let thisComp = this; if (csrfToken !== undefined) { let lookupOptions = { method: "GET", headers: { "Content-Type": "application/json" } }; fetch(endpoint, lookupOptions) .then(function(response) { return response.json(); }) .then(function(responseData) { console.log(responseData); thisComp.setState({ menu: responseData }); }) .catch(function(error) { console.log("error", error); }); } } componentDidMount() { this.setState({ menu: [] }); this.loadPosts(); } handleClick() { this.setState({ elClass: !this.state.elClass }); } render() { const { elClass } = this.state; const { menu } = this.state; return ( <div> <aside> <img className="logo" src={logo} alt="" /> <img … -
How I can check redirect in method > Django
I have two methods in my view and I try check redirect in first method, but don't know how do it. Two methods > order_create and order_success. In template order_success have values about user info and order info, also cart clear works. I want check my redirect. views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity'] ) cart.clear_session() return redirect('order:order_success') else: form = OrderCreateForm() return render(request, 'orders/order_create.html', {'cart':cart, 'form':form}) def order_success(request): if order_create_method_redirect: order = Order.objects.order_by('id').last() return render(request, 'orders/order_success.html', {'order':order}) else: return HttpResponse('Empty page') urls.py app_name = 'order' urlpatterns = [ url(r'^order$', views.order_create, name='order_create'), url(r'^order/success$', views.order_success, name='order_success'), ] -
How can we get top trending searched listing in django rest framework using elastic search?
I am using django 2.1, elastic search 6.1 and django-elasticsearch-dsl-drf 0.17.6. view.py class SchoolViewSet(DocumentViewSet): document = SchoolDocument serializer_class = SchoolDocumentSerializer permission_classes = (AllowAny,) lookup_field = 'id' filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend, FacetedSearchFilterBackend ] # Define ordering fields ordering_fields = { 'name': 'name', } # Specify default ordering ordering = ('name',) faceted_search_fields = { 'top_name_hit': { 'field': 'name', 'facet': TermsFacet, 'enabled': True, 'options': { 'size': 4, # Override default number of suggestions "order": {"_count": "desc"}, 'show_term_doc_count_error': True, }, }, } documents.py @INDEX.doc_type class InstituteDocument(DocType): id = fields.StringField(attr='id_str') name = fields.StringField( analyzer=html_strip, fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), 'edge_ngram_completion': fields.StringField( analyzer=edge_ngram_completion ), }, fielddata=True ) class Meta: model = School I want to get result of most top most searched school. How can i get list of top trending list ? -
rendering questions on template one by one without changing the page URL when a button is clicked, I have about 3000 questions in the DB?
I am creating an exam platform where I need to render questions one by one to the template from DB, without changing the page URL , I am using django Framework, I have tried rendering the question by saving all the questions in a python OBJECT, and I am getting all the questions at a time in the Template. I am expecting a single question to be generated at a time, and when a button is clicked it has to change to the next question. and the answers given need to be saved in the same DB. -
How to filter datetime field by date?
I have model: class Account(models.Model): contract_date = models.DateTimeField() Field contract_date stored in db in UTC timezone. I need select all accounts where contract_date__date == date. But date stored in MSK timezone (+3). For example: Account.objects.create(contract_date='2010-01-01 21:00:00') Account.objects.filter(contract_date__date=date(2010, 1, 2)).all() The query return a empty list. -
Auto populate field in form based on database calculation in django
Basically I need to achieve below thing: when user enters start date and end date , i should be able to auto populate no of days (excluding saturday, sunday and holidays) in one of the field in the form. At database level I have table and query ready for calculating this thing. how to incorporate the same in django? I have Leave application and three files: models.py,views.py,forms.py and leave.html file class Leaves(models.Model): leaveID = models.AutoField(primary_key=True) fromDate = models.DateField() toDate = models.DateField() leaveType=models.CharField(max_length=20) noofDays = models.IntegerField(blank=True,null=True) createdBy = models.CharField(max_length=30) createdAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) updatedAt = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) def leave(request): context = {'form': Leaves} if request.method=='POST': form = LeaveForm(request.POST) if form.is_valid(): leaveID=request.POST.get('leaveID') fromDate=request.POST.get('fromDates') toDate=request.POST.get('toDate') leaveType = request.POST.get('leaveType') createdBy = User.objects.get(username=request.user.username) noofDays = Dim_Date.objects.raw('select count(distinct calendarDate) from Dim_Date where isWeekday=1 and isHoliday<>1') form.save() return render(request,'leave/leaveconfirmation.html') else: return render(request,'leave/leave.html') else: return render(request,'leave/leave.html',context) I should be able to auto populate field based on from_date and to_date given in the form. (Backend logic is ready) Please let me know how to integrate the same in django. -
User sessions with React and Django REST
Let's imagine the following scenario: 1- I have a backend made in django rest which manages information of partners attached to a financial institution (accounts, loans, balances, etc). 2- We develop a frontend in React that communicates with this api and presents an interface to see all this information (only consultations). My first solution was to manage user sessions resolving requests in redux actions and storing my verification token in my local storage, in turn, each of the new requests I made to the api verified the truth of this token, if it has expired I close session and I inform this (it is a requirement that the user session be closed if this exceeds the inactivity time). The question is this: Taking into account the potentially sensitive information that we are working on, is this the correct way to solve this situation? What other alternatives do I have? Thank you very much for reading and expressing your opinion -
How can I access to an other user?
Hello I am trying to access to an account to an other user using django-hijack by the email of an user but I don't know how to do this ... Could you give me an example please ? Thank you very much ! -
Django:The QuerySet value for an exact lookup must be limited to one result using slicing
I am working on a project where admin can assign team to manager. But it is not working and i have no idea how it will work. Because it is raising an error saying "The QuerySet value for an exact lookup must be limited to one result using slicing." Here is my model.py class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) user = models.ForeignKey(User,on_delete=models.CASCADE) class Meta: permissions = [ ("edit_task", "can edit the task"), ] here is my views.py file for the teams of manager @login_required (login_url= 'have the url where it will go') @permission_required('have the permission that is assigned by me') def supervisor(request): return render(request, 'manager/index-3.html') def supervisor_team(request): print(request.user.email) email=request.user.email obj= Create_Team.objects.filter(status='Accept', managers=manager.objects.filter(user__email=email)) return render(request, "manager/accept_team.html", {"object": obj}) I have no idea where i am wrong. -
attrs aren't being applied to PasswordInput
I have created a custom registration form. The 'placeholder' attribute works good for the username and email. But it doesn't apply to password1 and password2, to which I mentioned 'forms.PasswordInput'. from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser exclude=() widgets = {'username': forms.TextInput(attrs={'placeholder':'Username','class':'inputData'}), 'email': forms.TextInput(attrs={'placeholder': 'Email', 'class': 'inputData'}), 'password1': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'inputData'}), 'password2': forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'inputData'})} -
Print list data in HTML (templates) with parameter from View
I am new to Django so forgive me to ask this question. I am trying to find it for few hours already but no luck and that is why I am asking here. I have view: def filmovi(request): data = {'filmovi':{'1': 'Osvetnici' , '2' : 'It Chapter Two', '3' : 'Kapetanica Marvel', '4' : 'Aladdin' }} #data = {'1': {'name': 'Osvetnici: Zavrsnica', 'zanr': ' Action', 'godina': '2019'} , '2' : {'name': 'It Chapter Two', 'zanr': ' Horror', 'godina': '2018'}, '3' : {'name': 'Kapetanica Marvel', 'zanr': ' Action', 'godina': '2019'}, '4' : {'name': 'Aladdin', 'zanr': ' Comedy', 'godina': '2019'} } return render(request, 'filmovi.html', data) def film(request, id): filmovi = {'1': {'name': 'Osvetnici: Zavrsnica', 'zanr': ' Action', 'godina': '2019'} , '2' : {'name': 'It Chapter Two', 'zanr': ' Horror', 'godina': '2018'}, '3' : {'name': 'Kapetanica Marvel', 'zanr': ' Action', 'godina': '2019'}, '4' : {'name': 'Aladdin', 'zanr': ' Comedy', 'godina': '2019'} } data = filmovi.get(id, {}) return render(request, 'film.html', data) What I need to do is show all movie names in my "filmovi.html" Movie names should be link that will send ID to "film" and show some specific details about that movie only. When I call my view from urls I am keep …