Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django change widget from select to check bock
New to Django here and i tried to look but couldn't find an answer. Is there a quick and easy way to change the default widget on forms for example i would like to change the select box on country to a check bock model.py class Publisher(models.Model): countryChoices = (('CA','Canada'),('US','United States'),('MX','Mexico')) name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(choices = countryChoices, max_length=30) website = models.URLField() views class PublisherCreate(CreateView): model = Publisher fields = [ 'name', 'address', 'city', 'state_province', 'country', 'website'] Sorry for the simple question thanks in advance -
Creating a variable field in model Django
I want to ask the user how many questions they want to ask; based on their response, I want to populate a model with those many fields. The way I am currently thinking about doing that is as follows: from __future__ import unicode_literals from django.db import models class Interview(models.Model): title = models.TextField() description = models.TextField() number_questions = models.IntegerField() question_one = models.ForeignKey('Question', related_name='question_one') question_two = models.ForeignKey('Question', related_name='question_two') question_three = models.ForeignKey('Question', related_name='question_three') question_four = models.ForeignKey('Question', related_name='question_four') question_five = models.ForeignKey('Question', related_name='question_five') class Question(models.Model): question_description = models.TextField() prep_time = models.IntegerField() response_time = models.IntegerField() I realize that this solution is inefficient because a) the user is limited to a preset number of questions and b) if the user specifies less than 5 questions, there are unnecessary question entries created. What is a better way to go about storing multiple questions? -
How to return primary key as a response when ever we make a post request using django rest framework?
I have django model and a view for it define as: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer what should i do to return a primary key as response ? Help Appreciated. -
Can't import serializer from other serializer in django rest-framework?
Problem I have 2 models, leads and notes. I want a lead to be able to have 1 or more notes. I have used a generic foreign key because I want to plan for the future and a note could be assigned to say a person or a meeting for example. Following the instructions for django rest framework and Rest Framework Generic Relations I am trying to import one serializer from the other to make a reverse relation possible. Error I can't import the serializers in both files(call one serializer from the other) because I get: File "/Users/james/Documents/UtilityCRM-Server/crm/leads/urls.py", line 2, in <module> from leads import views File "/Users/james/Documents/UtilityCRM-Server/crm/leads/views.py", line 11, in <module> from leads.serializers import LeadSerializer File "/Users/james/Documents/UtilityCRM-Server/crm/leads/serializers.py", line 4, in <module> from notes.serializers import NoteSerializer File "/Users/james/Documents/UtilityCRM-Server/crm/notes/serializers.py", line 6, in <module> from leads.serializers import LeadSerializer ImportError: cannot import name LeadSerializer Any help would be greatly appreciated! Code notes/models.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class Note(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=100) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) # Relations content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() note_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.title … -
Trouble with namespace. Two different Urls are rendering the same view
I am having trouble with my urls. I have one app called users that has two models, Salon and Stylist. The url /stylists and /salons is rendering the same view (stylist_results) however /salons should render salon_results and I cannot figure out why. I think there may be something wrong with the way I am using namespaces. users/urls.py from django.conf.urls import url #import views from the current directory from . import views urlpatterns=[ url(r'^$', views.stylist_results, name='stylist_results'), url(r'^(?P<pk>\d+)$', views.stylist_detail, name='stylist_detail'), url(r'^$', views.salon_results, name='salon_results'), url(r'^(?P<pk>\d+)$', views.salon_detail, name='salon_detail'), ] users/views.py from django.shortcuts import get_object_or_404, render from .models import Salon, Stylist # Create your views here. def salon_results(request): salons = Salon.objects.all() return render(request, 'salons/salon_results.html', {'salons': salons}) def salon_detail(request, pk): salon = get_object_or_404(Salon, pk=pk) return render(request, 'salons/salon_detail.html', {'salon': salon}) def stylist_results(request): stylists = Stylist.objects.all() return render(request, 'stylists/stylist_results.html', {'stylists': stylists}) def stylist_detail(request, pk): stylist = get_object_or_404(Stylist, pk=pk) return render(request, 'stylists/stylist_detail.html', {'stylist': stylist}) urls.py from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url(r'^salons/', include('users.urls', namespace='salons')), url(r'^stylists/', include('users.urls', namespace='stylists')), url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), ] urlpatterns += staticfiles_urlpatterns() views.py from django.shortcuts import render def home(request): return render(request, 'home.html') -
Read variables from template in Django or Jinja2
Looking for a solution to read the complete list of variables that can be passed into a context and displayed within a template, using either Django or Jinja2. For example, something like this in Django: from django.template import Template template = Template("<h1>{{title}}</h1>{%for v in values%}<p>{{v}}>/p>") for node in template.nodelist: #Get the variable name from the node This seems like a real pain. All I want is a list of the keys that a context object could pass to the template, in this example, "title" and "values" -
Django - validate forms (raise errors)
I can't deal with raising errors in my template. I wrote clean method for my form: def clean(self): cleaned_data = super().clean() subcategory = cleaned_data['subcategory'] subcategory1 = cleaned_data['subcategory1'] if subcategory1 and (subcategory == subcategory1): raise forms.ValidationError("ERROR") else: print('OKKKKKKKKKK') My view: if request.method == 'POST': form_extended = SiteAddFormFull(request.POST) if form_extended.is_valid(): form_extended.save() messages.add_message(request, messages.SUCCESS, 'Success!!') else: messages.add_message(request, messages.ERROR, 'Error!!') print(form_extended.errors) Why when I open my form view I get "OKKKKKKKKKK" (in terminal) from my clean(self) method and in my template view 'Error!!' appears...? I would like to show error from my clean method but I don't now how to do it.... -
Make output of a function available to other function
I want to make some user information available to two different functions in my view.py. But, I want to hit database only once, not twice. Is there a way I can do this? Here is the function that outputs some user info (userlocs): def get_user_info(profile_ins): fav_loc = list() lat = list() lon = list() for loc in UserLoc.objects.filter(profile=profile_ins): fav_loc.append(loc.name) lat.append(loc.location.geo_code_lat) lon.append(loc.location.geo_code_lon) userlocs = list(zip(fav_loc, lat, lon)) return userlocs This is the view function when user looks at his profile. This is where I first call get_user_info: def profile(request): profile_instance = Profile.objects.get(user=request.user) userlocs = get_user_info(profile_instance) context = {'locations': userlocs} return render(request, 'profile.html', context) Now, I want the userloc list to be available to the following function too. This function is supposed to compare user input to the existing userloc info. I know I can again call get_user_info function, but I think this is redundant, as I already called it once. def add_location_exe(request): if request.method == 'POST': ln = UserLocForm(request.POST or None) if ln.is_valid(): name = ln.cleaned_data.get("name") ## is name in userloc list ## Thanks for your help. -
Django css background-image
My css file is working but i can't add bacgorund image. I try 3 way but don't work. This is my style.css .first-info{ width: 100%; height: 300px; background-image: url( "{% static 'img/bg.jpg' %}"); } This is my base.html ( img is working) {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{% block title %}VPW{% endblock %}</title> <link href="{% static 'css/style.css' %}" rel="stylesheet"> <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet"> <link href="{% static 'css/font-awesome.css' %}" rel="stylesheet"> <script href="{% static 'js/bootstrap.js' %}"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="container-fluid"> <div class="row head"> <div class="col-md-12"> <div class="col-md-4"> </div> <div class="col-md-4 logo"> <img src="{% static 'img/logo1.png' %}"> </div> <div class="col-md-4"> </div> </div> </div> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> And this is my main.html where i have class first-info. {% extends "shop/base.html" %} {% load static %} {% block title %}VPW{% endblock %} {% block content %} <div class="container-fluid"> <div class="row first-info"> <div class="col-md-4"> <div class="box"> Lorem Ipsum </div> </div> <div class="col-md-4"> <div class="box"> </div> </div> <div class="col-md-4"> <div class="box"> </div> </div> </div> </div> {% endblock %} I try change in css background-image: url( "{% static 'img/bg.jpg' %}"); to background-image: url( "img/bg.jpg"); but don't work … -
Polls application — django tutorial not working
I am working through the Polls tutorial for Django. I have made it as far as the start of part six. For some reason all of my class based generic views are working EXCEPT the class based index view. When trying to load localhost:8000/ I get the following error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The current URL, , didn't match any of these. Here is my mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] And here is my polls/urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] And here is the polls/views.py. I am just pasting the IndexView portion. The rest of the class based views are currently working: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Choice, Question # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): … -
pip install MySQLdb is not working
I am using python-3.6.0 & windows10. During learning django I created a project and when I typed python manage.py makemigrations it began to show errors. I checked many Q/A. But nothing is working as there suggestion. I tried pip install mysqlclient, pip install MySQLdb and some other commands. Here is some screenshots Now what can I do. Please need your help. -
Django data migration not creating data but showing odd behavior
I’m setting up a new app in my project. I’ve added it to the settings, been able to run an initial migration, and see the table in the db & app in my Django Admin. With this app, I'm trying to load data through an empty migration. Problem When I run the datamigration, the shell shows the objects being created (through print statements & using pdb), however they do not appear in the database and thus the Django Admin. Bizarre things I’m seeing: When the same functions through the django shell, the objects are getting created AND do appear in the DB & Django admin. When running the migration below, it is iterating the DataPoint (my model) id as if the migration objects were created in the db (even though they do not appear in the db) Example: 1,2,3,4, 12430, 12431 When I put in a set_trace(), I am able to "create" an object, but then looking in the db, the object does not exist. Any ideas? Model: class DataPoint(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=False) name = models.CharField(max_length=200) timedelta = models.IntegerField() end_date = models.DateTimeField(auto_now_add=False, null=False) value = models.DecimalField(max_digits=11, decimal_places=2) content_type = models.ForeignKey( ContentType, verbose_name=_('content'), null=True, blank=True, ) object_id = models.PositiveIntegerField( verbose_name=_('related … -
how can I export multiple images using zipfile and urllib2 - django
I am trying to add multiple image files into my zip. I have searched around and knows how to add a single one. I tried to loop through multiple images then write into it but it didn't work. I kind of did the same thing with txt format and it works that I can compress a few files into the zip but somehow not when with image. Can someone please give me a hand? Thanks in advance. # get all photos in db which will be a queryset as result photos = Photo.objects.all() # loop through the queryset for photo in photos: # open the image url url = urllib2.urlopen(photo.image.url) # get the image filename including extension filename = str(photo.image).split('/')[-1] f = StringIO() zip = ZipFile(f, 'w') zip.write(filename, url.read()) zip.close() response = HttpResponse(f.getvalue(), content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=image-test.zip' return response This would give me the last image which in a way I can see why. -
403 Forbidden when trying to access API via DRF
I am trying to access a django server using django-rest-framework from angular using the following service: myapp.factory("GetData", ["$resource",function($resource) { return $resource( "http://local/path/**/users/:username/", {}, { "query": { method: "GET", isArray: true, headers:{ "Content-Type":"application/json" } } }, { stripTrailingSlashes:false } ); }]); When I put the URL in the browser, I get the desired output, but the problem is that when I try to access via Angular, in my console I am getting a 403 forbidden error. Can anyone explain to me whats causing this. and how I can possibly fix this issue. My url.py looks as follows: from rest_framework.routers import DefaultRouter from .views import UserViewSet router = DefaultRouter() router.register(prefix='users', viewset=UserViewSet) urlpatterns = router.urls My views.py file is as follows: from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from .models import users from .serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = users.objects.all() serializer_class = UserSerializer -
How can i use select_related rest framework
I am new in django, I am creating basic website where user can post some message and add some tags to that post. I have 3 models Person, Posts and Tags. Using rest framework I created API for Posts, which should give me list of Posts with person name, tags which posts relate with. for small number of posts this is working fine, but for large posts it is taking too long to respond. Using django-toolbar I am able to figure out too much queries are being fired, so I used prefetch_related and select_related in queryset. Here number of queries are reduce by half but still for foreign key relation ship query is executing for each record. below is sample of my code. For getting 10 records it is firing 34 queries without using prefetch_related on tags model. After using prefetch_related on Tags , it is 15 queries. Now for individual post it is firing query on person with self join. How can I reduce this number of queries? models.py class Tag(models.Model): name = models.CharField(max_length=200,unique=True) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=200,unique=True) friends = models.ManyToManyField("self", blank=True) def __str__(self): return self.name class Post(models.Model): person_id = models.ForeignKey(Person) text = models.TextField(blank=True,null=True) … -
Django 1.10 patterns rewrite
The Wagtail docs contain the following example for setting up urls.py: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() # tell gunicorn where static files are in dev mode urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) urlpatterns += patterns('', (r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'myapp/images/favicon.ico')) ) patterns is deprecated in Django 1.10. How can the last urlpatterns be rewritten to work in Django 1.10? I use python 3.5. I appreciate any help. -
How to change the interpreter of the project
I created a django project and its interpreter is an 3.5.2 ENV, all the extensions that I install in Pycharm it doesn't recognize them, when I try to add them in Installed APPS, they aren't available. But if the interpreter is only python.exe it recognizes. So, How do I change the intrepeter of a project that is set to the 3.5 2 ENV to another, I don't know exatly what ENV is, and why it doesn't allow me to use installed extensions. -
User Registration after mobile verification
I want the user to submit the registration form and then redirect to another page to verify the number he entered in the mobile number field. If the verification is successful, my user should be created otherwise an error. Currently my Register View looks like this: def register_view(request): template = "accounts/register.html" print(request.user.is_authenticated()) next = request.GET.get('next') print next title = "Register" form = UserRegisterForm(request.POST or None,) if form.is_valid(): user = form.save(commit=False) # number = user.mobile_number # to_check = phonenumbers.parse(number,"TR") # if phonenumbers.is_possible_number(to_check) and phonenumbers.is_valid_number(to_check): # formatted_number = phonenumbers.format_number(to_check, phonenumbers.PhoneNumberFormat.E164) # params = { # 'api_key': ' api-key', # 'api_secret': 'api-secret', # 'number': formatted_number, # 'brand': 'MobileVerification', # } # url = 'https://api.nexmo.com/verify/json?' + urllib.urlencode(params) # response = urllib.urlopen(url) # resp_dict = json.loads(response.read()) # request.session["user_request_id"] = resp_dict['request_id'] # messages.success(request,"A 4 digit pin has been successfully sent to your number.") # return HttpResponseRedirect(reverse('pin_verify')) # else: # messages.error(request,"Enter a valid mobile number.") # params2 = { # } # url = 'https://api.nexmo.com/verify/search/json?' + urllib.urlencode(params) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.mobile_number, password=password) login(request, new_user) if next: return redirect(next) return redirect("/") context = { "form": form, "title": title } return render(request, template, context) The commented code in the view is what I tried by … -
django sitemap custom template response format is not in xml
I try to override existing sitemap template to enable deep link, but response format not in xml. **urls.py** url(r'^sitemap\.xml$',sitemap,{'sitemaps':sitemaps,'template_name':'sitemaps/sitemap.xml','content_type':'application/xml'},name='django.contrib.sitemaps.views.sitemap') **sitemap.xml** <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> {% spaceless %} {% for url in urlset %} <url> <loc>{{ url.location }}</loc> <xhtml:link rel="alternate" href="android-app://{{ url.location }}" /> {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod> {% endif %} {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %} {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %} </url> {% endfor %} {% endspaceless %} </urlset> please help, am not getting not solution from google. -
Editing the models fields to required specification :)
Here I am making a basic MCQ(multiple choice question) using Django. So I created two models question and option, here are the models class Question(models.Model): question_id=models.IntegerField(default=170) question_text=models.CharField(max_length=1000) def __str__(self): return self.question_text class Options(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) options=models.CharField(max_length=500) def __str__(self): return self.options How can I limit the number of options that added to the question, and giving the user a notification that there should be a minimum number of options for a question?For example, limit the number of options to 5 and minimum number of questions to four -
Django using ES6
I did a lot of research about RequireJS vs Browserify vs Webpack vs JSPM and also HTTP/2, ES6 and came up with the result that native ES6 and HTTP/2 will simplify a lot of former best practices. I don't know in detail how the build process of webpack, jspm, browserify work but i think Node will be required and I wanna use definitively python+Django as back-end stack. Unfortunately, native ES6 is only supported by Edge 15 and Safari, so i'm not able to come around to do a build process until ES6 becomes more native. I found django.pipeline but this will bundle a group of JS files to one single file and thats not what iam looking for if we consider that HTTP/2 is able to do multiplexing. I only want to use ES6 code and python django (compiling ok, cause its worth to convert es6 to es5 code, but please no bundling)...is there a way to do that? Maybe we consider that in future i's like to use hot reloading with django. -
TypeError: view must be a callable or a list/tuple in the case of include().hh
TypeError: view must be a callable or a list/tuple in the case of include(). urls from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^$',"newhomaa.views.home", name='home'), url(r'^admin/', include(admin.site.urls)), views from django.shortcuts import render def home(request): return render(request,"home.html",{}) INSTALLED_APPS = [ 'newhomaa', i need solv my Problem -
Why isn't the following ajax code working?
I am trying to login the user by opening the bootstrap login modal and filling it with username and password but when i hit 'Login' in my bootstrap modal it just disappears and displays nothing. Shouldn't it display "Invalid" or "Valid" ?? And i also wanna mention that i get this error in every users password: html: ( bootstrap modal code ) <div id="loginmodal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <form id="loginForm"> {% csrf_token %} <div class="modal-content" data-method="post" id="modalform" > <div class="modal-header"> <!--Heading and the closing button --> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3 class="modal-title">Log In.</h3> </div> <div class="modal-body"> <div class="form-group"> <input type="text" autocomplete="off" placeholder="Email." class="form-control" id="usrnm"><br/> <input type="password" autocomplete="off" class="form-control" id="pwd" placeholder="Password."><br/> <input type="checkbox"> Remember me <br/> <a style="float: right;" href="#" data-dismiss="modal" data-toggle="modal" data-target="#signupmodal">Not a member ? </a><br/> <p style="float: left;"><a href="#"> Forgot Password?</a></p> </div> </div> <!--Closing Button in footer --> <div class="modal-footer"> <button type="submit" id="login" class="btn btn-default">Login</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close </button> </div> </div> </form> </div role="modal dialog"> </div role="model of login"> ajax: $('#loginForm').on('submit',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/librarysystem/Login/", data: { 'username':username, 'password':password, csrfmiddlewaretoken:$ ('input[name=csrfmiddlewaretoken]').val () }, dataType: 'json', success: function(data){ if (data.response){ alert("Invalid"); }else alert("Valid"); } } }); }); views.py: from django.shortcuts import render … -
image handling(donwloading/display) in django using html and form
i want to do some image processing using Django and now work and on the image handling(donwloading/display) using Django. first on my task i dont want to store that images on my server. but i have some problems. that my code : urls.py from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$',views.index, name='index'), url(r'^$',views.calc, name='calc'), ] file.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="button" value="Submit"> </form> {{ flow_direction_uri.url }} </body> </html> forms.py from django import forms class ImageUploadForm(forms.Form): """Image upload form.""" image = forms.ImageField() views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from pygeoprocessing import routing from django import forms from blog.forms import ImageUploadForm def calc(request): form = ImageUploadForm() if request.method == "POST" and form.is_valid(): image_file = request.FILES['image'] form.save() '''do something image process''' '''and finaly i take that output in standalone python script out of django''' outpu1 = "outpu1.tif" outpu2 = "outpu2.tif" outpu3 = "outpu3.tif" outpu4 = "outpu4.tif" {'form':form,'output1':output1}, RequestContext(request)) and i take that error : UnboundLocalError at / local variable 'output1' referenced before assignment but i thing so its not that error why if i change request … -
Load data file into Django with one demo user
I am new to Django. I am planning to a have a demo user account and i want to load all the files based on demo user's UUID. Is there another way to load the seed file without using fixtures? seed file. User.objects.create( first_name = "John", last_name = "Doe", email = "john.doef@example.com", gender = "M" ) u = User.objects.last() u.set_password("safestpassword") u.save() Track.objects.create( title = 'track1', description = "some description", image_url = "image_url", track_url = "track_url", artist = "artist", user_id = User.objects.last() ) Track.objects.create( title = 'track2', description = "some description", image_url = "image_url", track_url = "track_url", artist = "artist", user_id = User.objects.last() ) Thank you.