Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change a form class into a serializer class in django
While reading the django_rest documentation I learned that the serializers in REST framework work very similarly to Django's Form and ModelForm classes. Then I was curious about how to change an existing form class into a serializer class. How do I achieve this. Here is the Form class class EmployeeForm(ExtraFieldFormMixin, forms.ModelForm): """Form to create a new Employee instance.""" first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput(), max_length=128) retype_password = forms.CharField(widget=forms.PasswordInput(), max_length=128) def __init__(self, company, *args, **kwargs): self.company = company if kwargs.get('instance'): instance = kwargs.get('instance') user = instance.user kwargs['initial'] = { 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, } super(EmployeeForm, self).__init__(*args, **kwargs) if self.instance.id: del self.fields['password'] del self.fields['retype_password'] if self.company and self.company.pk: del self.fields['company'] -
Use of django middleware
What is django middleware and why we are using the middleware in django. I want to know, how to use django middleware, and what they are used for? And what things I can't do without them. -
How to properly implement Ajax with DataTables using Django?
I have a database that I would like to manifest as a datatable within my Django app. However, I'm having some trouble trying to get the required model data parsed to my Ajax-enabled template. models.py from django.db import models class MyModel(models.Model): someAttr = models.CharField() def __unicode__(self): return self.someAttr views.py from django.shortcuts import render from django.core import serializers from .models import MyModel def myModel_asJson(request): object_list = MyModel.objects.all() json = serializers.serialize('json', object_list) return render(request, 'template.html', {'json': json}) urls.py from django.conf.urls import patterns, url urlpatterns = patterns('myapp.views', url(regex=r'^$', view='myModel_asJson', name='my_ajax_url'), ) template.html <table cellpadding="0" cellspacing="0" border="0" id="example"> <thead> <tr><th>My Attr Heading</th></tr> </thead> <tbody></tbody> </table> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').dataTable( { "processing": true, "ajax": { "processing": true, "url": "{% url 'my_ajax_url' %}", "dataSrc": "" }, "columns": [ { "data": "fields.someAttr" }, { "data": "pk" } ] } ); } ); </script> When I open the webpage, I am greeted with an error, stating that my json is not valid. I have verified that the json is in fact valid, but the data is still not showing on my datatable. I've no idea how to get around this error. Any help in the matter would be greatly appreciated, I would really like to … -
Problems with extended models in Django
I am currently working on a webapp for user authentication. The user should edit his attributes but when I try to extend the user model, it can not display the attributes. Here is my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User) salutation = models.CharField(max_length=100, default='') title = models.CharField(max_length=100, default='') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here my forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'salutation', 'title', ) my views.py @login_required @transaction.atomic def edit_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect(reverse('accounts:view_profile')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) args = {'user_form': user_form} args2 = {'profile_form': profile_form} return render(request, 'accounts/edit_profile.html', args, args2) And this is the template: <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} The profile_form.as_p does not show anything and when I try to save the changes it also does not do anything. Clearly I am missing something, but I … -
Do not redirect to the dynamic url
This's my view.py from django.shortcuts import render from .models import Demo def home(request): movie_list = Demo.objects.all() return render(request, 'home.html', { 'movie_list': movie_list, }) def movie_detail(request,title): detail = Demo.objects.get(title=title) return render(request, 'detail.html', { 'detail': detail }) urls.py from django.conf.urls import include, url from django.contrib import admin from netflix.views import home,movie_detail urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^movie', home), url(r'^movie/(?P<title>.*)/$', movie_detail, name='movie_detail') ] detail.html <div class="container-fluid"> <div class="row"> <div class="card mb-3"> <img class="card-img-top" src="{{detail.img_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{detail.title}}</h5> </div> </div> </div> </div> Demo is my model's name. I want to ask why I can't go to the dynamic url like http://127.0.0.1:8000/movie/xxx xxx is movie name thanks for help. -
Django form change value in database with jquery in template
I want to change the value of a form field to a certain string when a box is checked. The model field in my model.py is number = models.CharField(_('number'), max_length=50, blank=True). I wrote an event that reacts to checking the checkbox given by number_given = forms.BooleanField(): $("#id_number_given").change(function() { if(this.checked) { $("#id_number").attr("disabled", "disabled"); $('#id_number').val("not assigned") } else { $("#id_number").removeAttr("disabled"); } }); This seems to do what I want: if the checkbox is checked, the field gets greyed out and the value set to "not assigned". However, the value is not changed in the database. Is there no way to set the form field value with jquery and save it, too? Also, if the checkbox gets unchecked again, of course the value that is typed into the field should be used in the database when the form is saved. -
Original exception text was: 'QuerySet' object has no attribute 'profile'
from listing.models import Lead class NdtvFeedSerializer(serializers.ModelSerializer): make = serializers.CharField(source="profile.variant.model.make.display_name") model = serializers.CharField(source="profile.variant.model.display_name") variant = serializers.CharField(source="profile.variant.display_name") make_year = serializers.DateField(source="profile.make_year") registration_year = serializers.DateField(source="profile.registration_year") kilometer_driven = serializers.IntegerField(source="profile.mileage") fuel_type = serializers.CharField(source="profile.fuel_type") transmission = serializers.CharField(source="profile.transmission_type") city = serializers.CharField(source="city.display_name") price = serializers.IntegerField(source="listing_price.value") class Meta: model = Lead fields = [ "id", "make","model", "variant", "make_year", "registration_year", "kilometer_driven", "fuel_type", "transmission", "city", "price" ] Error- AttributeError: Got AttributeError when attempting to get a value for field model on serializer NdtvFeedSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'profile' I have checked, the source path is correct. Lead Model:- class Lead(models.Model, LeadProperties): city = models.ForeignKey(City, null=True) sell_request = models.ForeignKey(SellRequest, null=True) assigned_to = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="assigned_leads") created_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="created_leads") sales_executive = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="sales_leads") status = models.ForeignKey(Status) is_valid = models.BooleanField(default=False) is_saved = models.BooleanField(default=False) 'Entry fields' image_set_primary = models.ForeignKey(FileSet, null=True) primary_pdf_report = models.ForeignKey(FileUpload, null=True) inspection = models.ForeignKey(FieldTask, null=True) dent_map = models.ForeignKey(DentMap, null=True) extra_photos = models.ForeignKey( FileSet, null=True, related_name='leads_extra_photos') documents_photos = models.ForeignKey( FileSet, null=True, related_name='leads_document_photos') profile = models.ForeignKey( LeadProfile, null=True, related_name="profile_lead") report_sheet = models.ForeignKey(ReportSheet, null=True) accessories_report = models.ForeignKey(AccessoriesReport, null=True) tyre_condition = models.ForeignKey('TyreCondition', null=True) verdict = models.ForeignKey(FinalVerdict, null=True) car_sold_info … -
Cannot Send Email using SMTP server from DigitalOcean Server
We have hosted a django website in Digital Ocean droplet. I'm sending email using django's msg = mail.EmailMultiAlternatives(mail_obj.subject,mail_obj.content,settings.FROM_EMAIL,[mail_obj.to_email],connection=connection) msg.attach_alternative(mail_obj.content, "text/html") result=msg.send(fail_silently=False) The email settings in settings.py is all correct and everything is working fine in local machine. But the EmailMessage.send (or EmailMultiAlternatives.send) method is blocking indefinitely. This happens only is server. When run on local machine, mail is delivered successfully. Any clue? Thanks in advance. -
JSONDecodeError: Expecting value: line 1 column 1 (char 0) error
I am facing this error while making request to fetch json from api. I can get json data using the "/v1/articles' path. conn = http.client.HTTPSConnection("api.xxxx.com.tr") headers = { 'accept': "application/json", 'apikey': "cd6b6c96799847698d87dec9f9a731d6" } filter = "daily" conn.request("GET", "/v1/articles", headers=headers) reader = codecs.getreader("utf-8") res = conn.getresponse() data = json.load(reader(res)) json.dumps(data) return data But i am having JSONDecodeError if i set filter. Code: conn = http.client.HTTPSConnection("api.xxxx.com.tr") headers = { 'accept': "application/json", 'apikey': "cd6b6c96799847698d87dec9f9a731d6" } conn.request("GET", "/v1/articles?$filter=Path eq '/daily/'", headers=headers) reader = codecs.getreader("utf-8") res = conn.getresponse() data = json.load(reader(res)) json.dumps(data) return data I tried same filter using Postman with no error and i can get Json data. Returned Json data from Postman: [ { "Id": "40778196", "ContentType": "Article", "CreatedDate": "2018-03-20T08:28:05.385Z", "Description": "İspanya'da 2016 yılında çalınan lüks otomobil, şasi numarası değiştirilerek Bulgaristan üzerinden getirildiği Türkiye'de bulundu.", "Files": [ { "FileUrl": "http://i.xxxx.com/i/xxxx/98/620x0/5ab0c6a9c9de3d18a866eb54.jpg", "Metadata": { "Title": "", "Description": "" } } ], "ModifiedDate": "2018-03-20T08:32:12.001Z", "Path": "/gundem/", "StartDate": "2018-03-20T08:32:12.001Z", "Tags": [ "ispanya", "Araç", "Hırsız", "Dolandırıcı" ], "Title": "İspanya'da çalınan lüks araç Türkiye'de bulundu!", "Url": "http://www.xxxx.com.tr/gundem/ispanyada-calinan-luks-arac-turkiyede-bulundu-40778196" } ] I can not figure out the problem. It would be great if anyone help me about this issue. Thank you. -
How do I redirect to another form after submitting a form in django.
SO I have the following form which is working.: <body> <form method="POST" class = "incubatorBox" novalidate enctype="multipart/form-data"> {% csrf_token %} <h2 class = "register-text"> Add Incubator</h2> {{ form.as_p }} <br> <input class = "register-button" type="submit" name="" value="Register"> </form> </body> </html> I have the following models.py class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs = {'incubator_id': self.pk}) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner class Details(models.Model): incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE, related_name='banana_pudding') inc_name = models.CharField(max_length = 30) inc_img = models.FileField() inc_contact = models.CharField(max_length = 600, default = "Enter all available means of contacting") inc_details = models.TextField(max_length= 2500) inc_address = models.TextField(max_length = 600, default = "Address") inc_doc = models.FileField() inc_policy = models.FileField() def __str__(self): return self.inc_name So Basically whats happening here is that the first form is adding data in the Incubator database and after submission it has to redirect the user to form which enter the data in Details database in the models.py. My first form is working fine and … -
custom manager is returning all the objects django.11 postgres
class CustomManager(models.Manager): def get_query_set(self): queryset = super(CustomManager, self).get_query_set() return queryset.filter( models.Q(expiration_date__gte=datetime.date.today()) | models.Q( expiration_date__gte=datetime.date.today() - datetime.timedelta(days=40), is_invoice_emailed=True ) ) class Subscription(models.Model): .... objects = CustomManager() default = models.Manager() when I access Subscription.objects.all() it's returning all the records in db without filtering. but, If I use below query queryset = Subscription.objects.all() queryset.filter( models.Q(expiration_date__gte=datetime.date.today()) | models.Q( expiration_date__gte=datetime.date.today() - datetime.timedelta(days=40), is_invoice_emailed=True ) ) It is returning filtered results. Why? I'm using django==1.11.11, python2.7 and db Postgresql Please help. Thanks. -
Django/Graphene mutations doesn't apply
I am currently creating a GraphQL interface for my Django app, using Python-Graphene. While queries works great, mutations - not quite. Here's the schema code (full code here: https://ctrlv.it/id/107369/1044410281): class IngredientType(DjangoObjectType): class Meta: model = Ingredient ... class CreateIngredient(Mutation): class Arguments: name = String() ok = Boolean() ingredient = Field(IngredientType) def mutate(self, info, name): ingredient = IngredientType(name=name) ok = True return CreateIngredient(ingredient=ingredient, ok=ok) class MyMutations(ObjectType): create_ingredient = CreateIngredient.Field() schema = Schema(query=Query, mutation=MyMutations) and my mutation: mutation { createIngredient(name:"Test") { ingredient { name } ok } } Running it returns proper object and ok is True, but no data is pushed to the database. What should I do? What did I miss? -
What happens to the Django admin site during production?
Django offers an admin interface at /admin. Is it not safe to keep this URL during production? Or should I change the URL to /d0oai32492384h24ui234nij23n4k2jnkjnkjn or something? -
How to process data passed in success function in jQuery Ajax
I need to process two lists in Ajax success function. The below simple code works well for a single list but doesn't work with 2 lists. How can we process 2 lists separately in a success function. jQuery Ajax success: function(data) { $.each(data, function() { $.each(this, function(k, v) { //do something with v }); }); } views.py lst1 = [1, 2, 3, 4, 5] lst2 = ['a', 'b', 'c', 'd', 'e'] context = { 'labels' : lst1, 'sk_labels': lst2 } return HttpResponse(json.dumps(context), content_type='application/json') -
Set loading limits by file extension in nginx
I am using the following command to limit file upload in nginx; client_max_body_size 100m; But I want to do it based on file extensions. For example, 5 mb for png, 10 mb for jpg. Is something like this possible? -
Using StackedInline for CustomUser to make it inline but for password it not taking encryption
I am using Django admin for some users as UI and making custom admin interface so used StackedInline for User module but it saving without encryption Version: Django 1.11 class CustomUserAdmin(admin.StackedInline): model = CustomUser fieldsets = ((None, {'fields': ('username', 'password', 'first_name', 'last_name','phone', 'email','is_active', 'date_joined')} ),) max_num = 1 class BuilderAdmin(admin.ModelAdmin): model = Builder form = BuilderAdminForm inlines = [CustomUserAdmin] -
django search using sqlite
i want search data from database. where i create 4 radio buttons for invetory data and want to serach data fron particular table following is the code i follow please suggest where i need to change the code my view def searchq(request): #option = "q" #get value from form #option = "o" #get value from form if request.POST('q_id'): if txtsrc in request.GET: txtsrc = request.GET['txtsrc'] quatation = QuatationOrder.objects.filter(id__icontains= txtsrc) return render(request, 'template/searchq.html', {'res': results, 'query': txtsrc}) elif value in request.GET('o_id'): if 'btnsearch' in request.POST: results = order.objects.filter(pk=id) elif opt == "i_id" in request.GET: if 'btnsearch' in request.POST: results = Invoices.objects.filter(id=1) else: if 'btnsearch' in request.POST: results = Bills.objects.filter(id=1) print(results) return render(request, 'template/searchq.html', {'res':results}) -
Django datetime field with string inside
I have a model which works fine. I just don't know what is the purpose of the string (date published) inside the datetime field - match_date declaraction. Of course, I found this model as I was trying out a few tutorials. class Team(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) match_date = models.DateTimeField('date published') I've gone through the documentation but couldn't find this one. Thanks -
We are doing development using python and Django on Linux server. How could I use MKS to configure a sandbox that can replicate my dev server
We are doing development using python and Django on Linux server. How could I use MKS to configure a sandbox that can replicate my dev. server -
Django template - use 2 models to filter results
apologies if my question is not that clear. I'm new to Django and it's my first time to ask questions here as I can't seem to find solutions to my problem. I've done research on how to use multiple models in Django template and succeeded to do so, however, one of my requirement is that each trucker in the list should show corresponding number of registered truck units but I can't seem to do this. The output should be like this: Haulers List Registered Hauler Number of units Trucker #1 10 Trucker #2 5 ... Trucker #n 3 Should you have suggestions I highly appreciate it. Im using Django version 2.0.1 and Python 3.6 on Windows if that's relevant. Here is my code: models.py class Trucker(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class TruckUnit(models.Model): plate_number = models.CharField(max_length=7) trucker = models.ForeignKey(Trucker, related_name='truckunits', on_delete=models.CASCADE) def __str__(self): return self.plate_number views.py class TruckerList(generic.ListView): model = Trucker context_object_name = 'trucker_list' queryset = Trucker.objects.all().order_by('name') template_name = 'trip_monitor/trucker_list.html' def get_context_data(self. **kwargs): context = super(TruckerList, self).get_context_data(**kwargs) context['units'] = TruckUnit.objects.all() context['truckers'] = self.queryset return context urls.py from django.urls import path from . import views urlpatterns = [ path('truckers/', views.TruckerList.as_view(), name='trucker_list'), ] trucker_list.html {% extends 'base.html' %} {% block … -
django handling basic http auth
Currently I have the following code to handle an incoming GET request: #view.py def handle_request(request): if request.method == 'GET': <do something> return response this code can handle a simple GET request the form: curl http://some_url/ But now I want to add basic http authentication: curl --user username:password http://some_url/ I want to modify my views.py code to look like: def handle_request(request): if request.method == 'GET': if username == some_hard_coded_approved_username and password == corresponding_password: <do something> return response else: response = HttpResponse("") response.status_code = 401 return response How do I implement this line to parse username and password from http request: if username == some_hard_coded_approved_username and password == corresponding_password: -
Graph not getting displayed on html template django
So I am using bokeh.pydata to plot graph on the page. Yet it shows four dots (' .... ') where it is supposed to plot the graph. Below is my python file which is supposed to plot the graph. from django.shortcuts import render , render_to_response from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm from django.urls import reverse from bokeh.plotting import figure, output_file, show from bokeh.embed import components def index(request): ### graph plotting stuff ### x= [1,3,5,7,9,11,13] y= [1,2,3,4,5,6,7] title = 'y = f(x)' plot = figure(title= title , x_axis_label= 'X-Axis', y_axis_label= 'Y-Axis', plot_width =400, plot_height =400) plot.line(x, y, legend= 'f(x)', line_width = 2) #Store components script, div = components(plot) print("@#$!@") print(script) print("@#$!@") print(div) # return render(request, 'visit/index.html', context=None) return render(request, 'visit/index.html', {'script' : script , 'div' : div}) def profile(request): return HttpResponseRedirect(reverse("main:home")) def registration(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): formObj = form.cleaned_data username = formObj["username"] name = formObj["name"] email = formObj["email"] password = formObj["password"] if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username=username, name=name, password=password) login(request, user) return HttpResponseRedirect('/') else: form = UserRegistrationForm() return render(request, 'visit/registration/register.html', {'form': form}) Below is my … -
django python dynamic input values multiple zero return error message
def advancement(request): value1=request.POST.get('amount') intvalue=int(value1) if intvalue == 0 or intvalue==00 or intvalue==000:#like more zeros message.error(request,'please enter a proper value') return render(request,'page.html') html code: <html> <head> <title></title> </head> <body> <label>amount<input type='text' name='amount'></label> <input type='submit' name='validate' value='pay-advance-amount'> </body </html> In text box give zeros like(0000000). This more Zeros not allow to register into Database so before give the Error Message. -
Setup several django project in the same domain and port with apache2
Expect result: example.com/project1 => project1 example.com/project2 => project2 Occurred Questions: project1 works fine,but project2 was not found on this server. My configure is as following: /etc/apache2/sites-available/project.conf <VirtualHost *:80> ServerName example.com WSGIScriptAlias /project1 .../ENV_project1/project1/project1/wsgi.py WSGIDaemonProcess project1 python-home=.../ENV_project1/project1 WSGIProcessGroup project1 <Directory .../ENV_project1/project1/project1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /project2 .../ENV_project2/project2/project2/wsgi.py WSGIDaemonProcess project2 python-home=.../ENV_project2/project2 #WSGIProcessGroup project2 <Directory .../ENV_project2/project2/project2> <Files wsgi.py> Require all granted </Files> </Directory> wsgi.py import os from os.path import join,dirname,abspath PROJECT_DIR = dirname(dirname(abspath(__file__))) import sys sys.path.insert(0,PROJECT_DIR) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project1.settings")#another is project2.settings application = get_wsgi_application() Error log Target WSGI script '.../project1/wsgi.py' cannot be loaded as Python module. ImportError: No module named project2.settings -
Mysqlclient instollation Error
Python 3.4 and Django installed successfully .but when i want to install mysqlclient using This command (pip install mysqlclient ) it shows "error: Microsoft Visual C++ 10.0 is required. But i have installed Microsoft Visual C++ 10 and 14. and visual Studio community too.So, Can anybody help me to get out of this problem?