Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to write this querySet with Django?
I started learning Django QuerySets but I didn't succeed to write it in this case where I must agregate 2 models related by a foreign key . I have 2 models user and course where course contains a foreign key of user and I want to translate this sql statement into querysets : select * from user u, course c where u.id = c.user_id and c.course_name='science' ; could someone help me please ? -
Add custom http hearde in RedirectView
I want to add the http header but it does not work. I'm trying to test solve by using the print, but it appears nothing This is my code but not works: class MyRedirectView(RedirectView): def head(self, *args, **kwargs): response = HttpResponse() response['X-Robots-Tag'] = 'noindex' print('TEST LOL') return response -
Django functional test: selenium.quit() doesn't reset database?
class FunctionalTest(LiveServerTestCase): def setUp(self): print("setUp") self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): print("tearDown") self.browser.quit() class MyTest(FunctionalTest): def test1(self): cart = Cart.objects.create() print(cart.id) def test2(self): cart = Cart.objects.create() print(cart.id) def test3(self): cart = Cart.objects.create() print(cart.id) When I run the test, setUp 1 tearDown .setUp 2 tearDown .setUp 3 tearDown . ---------------------------------------------------------------------- Ran 3 tests in 7.024s I don't understand why each test function's result affect other test function(cart's id) What I expected : setUp 1 tearDown .setUp 1 tearDown .setUp 1 tearDown . ---------------------------------------------------------------------- Ran 3 tests in 7.024s -
How to reduce Django class based view boilerplate
I really hate boilerplate. However, I can't deny that code such as the following is a huge benefit. So my question, what does one do in Python to make up for the fact that it doesn't come with a macro (template) pre-processor? One idea would be to write a factory function, but I'll willingly admit that I don't know where to start. (Please note that this is Django with its declarative classes and interesting "magic" metaclassy stuff going on underneath, which I know enough to recognise and not enough to understand or debug if I break it) The other would be to turn this into a template and import it through a trivial pre-processor that implements something like ${var:-default} in Bash. (see What is an alternative to execfile in Python 3.0? ), with my_preprocessor("somefile.py") as f: code = compile(f.read(), "somefile.py", 'exec') exec(code) # in the current namespace But there are lots of warnings about exec that I've seen over the years. The cited SO answer mentions line numbers for debugging as an issue. Then there is this, http://lucumr.pocoo.org/2011/2/1/exec-in-python/ , warning of subtle problems including memory leaks. I suspect they won't apply to a code defining classes which are "never" deleted, … -
Template doesnot exist error in Django
Am developing an angular frontend and Django backend app.I don't know where i am going wrong but Django cant seem to locate the template and displays a template doesn't exist message.The project directory looks like this.The backend server is in the "django project" folder base.py import environ project_root = environ.Path(__file__) - 3 env = environ.Env(DEBUG=(bool, False),) CURRENT_ENV = 'dev' # 'dev' is the default environment # read the .env file associated with the settings that're loaded env.read_env('./mysite/{}.env'.format(CURRENT_ENV)) #Database DATABASES = { 'default': env.db() } SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ROOT_URLCONF = 'mysite.urls' STATIC_URL = '/static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ env('FRONTEND_ROOT') ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [env('FRONTEND_ROOT')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Environment variables file(dev.env) DATABASE_URL=sqlite:///mysite.db DEBUG=True FRONTEND_ROOT= ('C:/downloads/mysite/frontend/') SECRET_KEY= '##########################' urls.py from django.contrib import admin from django.conf.urls import include, url from mysite.applications.api.v1.routes import api_router from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', admin.site.urls), # Web App Entry url(r'^$', TemplateView.as_view(template_name="/app/index.html"), name='index'), ] -
Setting current working dir in Django deployment
I am trying to deploy my Django project using the WSGI and Apache. This is supposed to be easy, but I keep running into problems. The main issue I think is that when running Django using manage.py runserver is that the current working dir is set to the dir where manage.py is located, so when I create a file (or try to access it), Django looks for it in that path. When running in WSGI, it seems like the working dir is set to /. How / where can I set my current working dir? Preferably in the apache config, because I do not want to touch me code. It should be identical to the development version (otherwise I have to jump through hoops every time I deploy any change). -
Django Error - django.db.utils.DatabaseError: Data truncated for column 'applied' at row 1
I am getting a weird issue when executing "python manage.py migrate". Below is the error. Can anyone help me django.db.utils.DatabaseError: Data truncated for column 'applied' at row 1 -
How to get all objects in a Django model(Databse table) based on a filter using AngularJs
Hi I have a Django model as below: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class Journal(models.Model): name = models.CharField(max_length=120) created_by = models.ForeignKey(User, related_name='+') date_created = models.DateTimeField(auto_now=False, auto_now_add=True) date_modified = models.DateTimeField(auto_now=True, auto_now_add=False ) def __unicode__(self): return (self.name) And my angularJs below: var app = angular.module("journalApp", []); app.controller("myCtrl", function($scope) { }); How can I make a query in AngularJs so that i get all the objects from my Django model based on the user who logged in? Any idea guys? Thanks in advance. -
Django grapelli change column width to full screen
I'm using django for the first time. I've experience with python but not with web development. Now i'm trying to design an admin page with grappelli. Only grappelli doens't show the tables full screen (column width too small) and it looks horrible. Only a third of my screen is used. Is there a way to set the column width keeping the users screen size in mind. It look somewhat like this only worse. I can' t post any of the real data since it' s for scientific purposes. I tried to fins the answer as well but couldn't find any that work for me. I'm using django 1.10, python 2.7 and grappelli 2.8.2. The reason i'm using grappelli is because of the drop down filter. If anyones knows how to make a drop down filter in django that' s also fine by me. Thanks in advance for your help. Grapelli interface -
Pytest-bdd cannot log in to django
I am trying to write feature tests for a django app and I can't get logging in to work. This test should pass but doesn't: # coding=utf-8 """Users can log in feature tests.""" import pytest from django.contrib.auth.models import User from pytest_bdd import ( given, scenario, then, when, ) @pytest.mark.django_db @scenario('user.feature', 'Logging in') def test_logging_in(browser): """Logging in.""" pass @given('A user exists') def a_user_exists(): """A user exists.""" user = User() user.username = 'vagrant' user.set_password('qwer') user.is_staff = True user.is_active = True user.is_superuser = True user.save() @when('I log in') def i_log_in(browser, live_server): """I log in.""" browser.visit(live_server.url + '/backadmin/login/?next=/backadmin/') browser.fill('username', 'vagrant') browser.fill('password', 'qwer') browser.find_by_value('Log in').click() assert User.objects.all().first().check_password('qwer') @then('I should be logged in') def i_should_be_logged_in(browser): """I should be logged in.""" assert browser.is_text_present('vagrant') The user.feature file just has those three steps in that order. The test fails, ending on the login page with an error note: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. The same test without pytest-bdd: from splinter import Browser from django.contrib.auth.models import User import pytest @pytest.mark.django_db def test_logging_in(browser, live_server): user = User() user.username = 'vagrant' user.set_password('qwer') user.is_staff = True user.is_active = True user.is_superuser = True user.save() browser.visit(live_server.url + '/backadmin/login/?next=/backadmin/') browser.fill('username', 'vagrant') browser.fill('password', 'qwer') … -
How to query using GenericForeignKey in Django model
I have table structure as follows in models.py : class A(models.Model): name = models.CharField(max_length=200) created_date = models.DateTimeField(default=now) description = models.CharField(max_length=1000) class B(models.Model): name = models.CharField(max_length=200) created_date = models.DateTimeField(default=now) description = models.CharField(max_length=1000) class C(models.Model): object_id = models.PositiveIntegerField() variable = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') Now my problem is my view i have to get name field from model A and model B on the request of any user , I understand the use of generic foreign key as foreign key to any model. How shall i make the query so that if in request parameter my variable is 1 , i throw the name from model A and if 2 i throw the name from model B. ? -
Showing a related fields attribute
How would I do this to show the ForeignKey protected_area's name field?: class NotificationReceiverSerializer(serializers.ModelSerializer): class Meta: model = NotificationReceiver fields = ('pk','cellphone', 'protected_area__name') So now its just showing as PK, as expected: protected_area":1 -
How to add additional fields on the base of inputs in django rest framework mongoengine
I am developing an API, using django-rest-framework-mongoengine with MongoDb, I want to append additional fields to the request from the serializer on the base of user inputs, for example If user enters keyword=@rohit49khatri, I want to append two more fields to the request by manipulating keyword, like type=username, username=rohit49khatri Here's my code: Serializer class SocialFeedCreateSerializer(DocumentSerializer): type = 'username' class Meta: model = SocialFeedSearchTerm fields = [ 'keyword', 'type', ] read_only_fields = [ 'type' ] View class SocialFeedCreateAPIView(CreateAPIView): queryset = SocialFeed.objects.all() serializer_class = SocialFeedCreateSerializer def perform_create(self, serializer): print(self.request.POST.get('type')) But when I print type parameter, It gives None Please help me save some time. Thanks. -
Django functional test: selenium 'live_server_url' doesn't load static files
I'm using django-pipeline for loading static files. Strange thing is that StaticLiveServerTestCase's live_server_url can not load static files correctly. Here is part of code: class CartItemEditTest(ProductSetupTestCase, StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(2) Firefox browser comes up and I execute follow command: self.browser.get(self.live_server_url) # self.live_server_url value is localhost:8081 And when I check js file using development tool, it shows like this: <script type="text/javascript" src="/static/js/message.8d038600d898.js" charset="utf-8"></script> When I copy the src(http://localhost:8081/static/js/message.8d038600d898.js) and paste it in new tab, it doesn't show Not Found. Now I used other url, http:localhost:8000, which is django runserver url. self.browser.get(http://localhost:8000`) When I checking this time, it load static files pretty well: <script type="text/javascript" src="/static/js/message.js" charset="utf-8"></script> Why does it happend? Should I not use live_server_url anymore? -
Django Application Error Whille Deploying On Service Fabric Cluster AS Guest Executable
I have created one service fabric application with guest executable as service type for django application to send email which web application. I deployed application on service fabric cluster but receiving error. I am not able to run the application. I have created package for application using VS 2015 & tested the it using power shell commands. Please refer all attached screen shot for your reference. Please kindly help to run the application successfully. Thanks enter image description here -
How to run django server with ACTIVATED virtualenv using batch file (.bat)
I found this post to be useful on how to code a batch file to automate django web server start. But the problem is, there is no virtualenv activated, How can i activate it before the manage.py runserver inside the script? I would like to run this server with virtualenv activated via batch file. -
In zulip dev environment, how can i access zulip's first dev web browser using run-dev.py in vagrant env but i can't access from global ip
I have some problem now using zulip dev-env ... I did success-installation by Dev-env(using run-dev.py in vagrant env) in my Mac PC and then i could access the first-dev page successfully through my mac-pc's browser But i have been trying to show the first page using Dev-dev in my cloud hosting service (like AWS or google Cloud hosting) for several days but i could not access and could not show the first page by using global IP and browser Which part must I change the setting environment? (that is, i want to access my dev-env[using run-dev.py] by global IP after that, i want to test... ) Now I am using a cloud hosting, Of course i opened port 9991 and etc... I use vagrant env and succeed it in cloud host In vagrant ssh, i can access zulip by using curl 127.0.0.1:9991 and received a success message "29/Sep/2016 00:42:04]"GET / HTTP/1.0" 302 0" from running console but i cannot access it by host console like this ai2@mrtalk:~/project/zulip$ curl 127.0.0.1:9991 curl: (7) Failed to connect to 127.0.0.1 port 9991: Connection refused of course , i can't access http://182.162.90.79:9991/ through my pc browser for this i tryed like these In zproject/dev_setting.py EXTERNAL_HOST … -
Django xlsxwriter preview before download
I have a function to export a data into excel and it works well but I want to have a Preview first before proceeding with the download. Click the "Export" button A new tab will open then embed the processed excel into HTML for preview Click another button for "Continue Download" Downloads the file I am using Django 1.8 and Python 2.7 with latest version of xlsxwriter. Thanks! -
Django render different templates for two submit buttons in a form
I am a beginner at Django development, and I am trying to make a food diary application. After a user enters his email on index.html, another web page should be rendered according to whichever button he clicks. I can possibly add two templates, but I also want my app to work if a user manually types a valid URL such as /apps/<user_email>/addDiaryEntry/. I don't know what to add in /apps/urls.py. Also, can I somehow access a user object's Id so my routing URL become /apps/<user_id>/addDiaryEntry/ instead? /templates/apps/index.html <form method="post" action="/apps/"> {% csrf_token %} <label for="email_add">Email address</label> <input id="email_add" type="text"> <button type="submit" name="add_entry">Add entry</button> <button type="submit" name="see_history">See history</button> /apps/views.py def index(request): if request.POST: if 'add_entry' in request.POST: addDiaryEntry(request) elif 'see_history' in request.POST: seeHistory(request) return render(request, 'apps/index.html'); def addDiaryEntry(request): print ("Add entry") def seeHistory(request): print ("See history") /apps/urls.py urlpatterns = [ url(r'^$', views.index, name='index'), ] Thank you for your help! Please feel free to share any best practices which I am not following. -
django: modelformset_factory save return empty list
I'm newer in django and I have this code, i don't know what it's wrong, I coding django with bootstrap, it worked until I include the widgets in form.py and styles in templates :( class QuotesView(View): def post(self, request, *args, **kwargs): qModFac = modelformset_factory(Quote, fields=('SerNr','SalesMan','Status'),extra=0) fieldsModel = ('Stock','Currency','Price','FinalPrice','Total','Comment','DeliveryDate','Suggested') query = Quote.objects.filter(somefilters).distinct() paginator = Paginator(query, 10) try: objects = paginator.page(pageNumber) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) formSet = qModFac(queryset=query) widgets = {'Stock':NumberInput(attrs=numAttrs),'Price':NumberInput(attrs=numAttrs),'FinalPrice':NumberInput(attrs=numAttrs),'Total':NumberInput(attrs=numAttrs),'Currency':Select(attrs=textAttrs),'Comment':TextInput(attrs=textAttrs),'Suggested':TextInput(attrs=textAttrs)} qduModFac = modelformset_factory(QuoteDetailUser,form=QuoteDetailUserForm, fields=fieldsModel,extra=0,widgets=widgets) #some debug #if i print request.POST i can see the values from html #it's like a u'form-0-DeliveryDate': [u'14/09/2016', u''], formDetailUserSet = qduModFac(request.POST) # I think qduModFac(request.POST) is the problem, but i don't know how do this manually if formDetailUserSet.is_valid():#Thats return TRUE!!!! #some debug #instances = formDetailUserSet.save() return empty list for rec in instances: res = rec.save() #res is an object but, not updated :( return render(request,'supplierweb/quotes.html',{'formset':formSet,'formDetailUserSet':formDetailUserSet, 'QuoteStatus':status,'brand':brand,'objects':objects}) form.py class QuoteDetailUserForm(forms.ModelForm): DATEPICKER = { 'type': 'text', 'class': 'datepicker inputText', } numAttrs = {'class' : 'inputQty'} textAttrs = {'class' : 'inputText','type':'text'} labelAttrs = {'class' : 'labelText cellMatrix','type':'text'} ArtCode = forms.CharField(max_length=20,required=False) Brand = forms.CharField(max_length=20,required=False) AlternativeCode = forms.CharField(max_length=20,required=False) Description = forms.CharField(max_length=100,required=False) Qty = forms.IntegerField(required=False) Stock = forms.IntegerField(required=False,widget=forms.NumberInput(attrs=numAttrs)) MY_CHOICES = ( ('USD', 'Dólares'), ('PEN', 'Soles'), ) … -
Where to write the save function in Django?
Where to write my save function in django whether in models.py in a class model or in forms.py in form ? For example : models.py class Customer(models.Model): name = models.CharField(max_length=200) created_by = models.ForeignKey(User) def save(): ........ some code to override it....... forms.py class Addcustomer(forms.ModelForm): class Meta: model = Customer fields = ('name',) def save(): ........code to override it.... where shall i override my save function -
django.db.utils.OperationalError: no such column: PItable.id
I'm trying to using django to read from an existing database, 'p.n.db', it already has 100 rows data. I put 'p.n.db' in the directory as manage.py. The settings.py look like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'chinookdb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'p.n.db'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }} I run python manage.py inspectdb --database=chinookdb > chinook/models.py It created the models.py class Pitable(models.Model): pid = models.TextField(db_column='PID', blank=True, null=True) # Field name made lowercase. lname = models.TextField(blank=True, null=True) fname = models.TextField(blank=True, null=True) affs = models.TextField(blank=True, null=True) pmidlist = models.TextField(db_column='PMIDlist', blank=True, null=True) # Field name made lowercase. clustering = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'PItable' Then I run python manage.py makemigrations chinook python manage.py migrate Then I runserver to access the table in p.n.db, it gives the error django.db.utils.OperationalError: no such column: PItable.id Thanks for any help! My goal is to use django to read from an existing database. -
In Django how to do filter, followed by get queries and get a field value?
Following is a simplified models.py of one of the apps of my Django program: #This is the custom queryset manager class TenantManager(models.Manager): def for_tenant(self, tenant): return self.get_queryset().filter(tenant=tenant) #This is one of the models: class accountChart(models.Model): name=models.CharField(max_length =200) remarks=models.TextField(blank=True) key=models.CharField(max_length=20) tenant=models.ForeignKey(Tenant,related_name='accountchart_account_user_te nant') objects = TenantManager() #This is another data model, related ith FK to 1st model shown here class paymentMode(models.Model): name = models.TextField('Payment Mode Name') payment_account=models.ForeignKey(accountChart,related_name='paymentMode_accountChart') default=models.CharField('Default Payment Mode ?', max_length=3,choices=choice, default="No") tenant=models.ForeignKey(Tenant,related_name='paymentmode_account_user_tenant') objects = TenantManager() Now, I'm doing the following queryset based on user inout. However, Django is throwing up errors. Request your kind help, as this thing is killing me for more than 2 days. #Queryset: payment_mode=paymentMode.objects.for_tenant(request.user.tenant).get(name__exact=request.POST.get('payment_mode')) payment_account=payment_mode.account However, Django is throwing up error with the second line of queryset. Even if I use filter instead of get, its showing error - Queryset doesn't have filter!! From what I understand, first django is giving me all the payment modes related to this user, then getting the payment mode from the request.POST.get object and then in the second line it's trying to get the related foeignkey. Can anyone kindly tell where I'm going wrong? -
Django filter child by parent
I'm trying to filter children by its parent in my templates. Example being I have houses that are displayed and want to display their amenities(children) along with them. When I try and do so each house list all amenities for every house. How would I make is so that I list a house and only its amenities? Here are my models: class Home(models.Model): name = models.CharField(max_length=255) photo = models.ImageField() def __str__(self): return self.name class Amenities(models.Model): home = models.ForeignKey(Home) amenities = models.CharField(max_length=255) In my views I am trying to filter the child by its parent: def index(request): home = Home.objects.filter() amenities = Amenities.objects.filter(home=home) return render(request, 'home/home.html', {'home': home, 'amenities': amenities}) In my template I am try and loop through each home and their amenities like so: {% for house in home %} <div class="row"> <div class="col-md-6 portfolio-item"> <a href="house1.html"> <img class="img-responsive" src=" media/{{ house.photo }}" alt=""> </a> <h3> <a href="house1.html">House</a> </h3> <ul> {% for i in amenities %} <li>{{ i.amenities }}</li> {% endfor %} </ul> </div> </div> {% endfor %} thank you -
Django CBV Login and Redirect user to profile page, such as https: example.com/profiles/user
Django 1.10 Python 3.5.3 Using CBV, I am able to log a user into the site. However, I cannot get the user to redirect to their profile after login. I want them to go to this page after login: https://example.com/profiles/user. Instead, I get this error: NoReverseMatch at /accounts/login/ Reverse for 'profile' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['profile/(?P<slug>[\\w-]+)/$'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) username = models.CharField(max_length=30, unique = True, default='') email = models.EmailField(default='', unique = True, max_length=100) profile_image = models.ForeignKey(Image, null=True) slug = models.SlugField(default='') is_active = models.BooleanField(default=True) is_authenticated = models.BooleanField(default=True) is_anonymous = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] @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() def next_birthday(born): today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) def get_absolute_url(self): return reverse('profiles:profile', kwargs={'slug': self.slug}) def __str__(self): return self.username views.py class LoginView(FormView): template_name = 'registration/login.html' """ Provides the ability to login as a user with a username and password """ success_url = 'profile/<slug>' form_class = AuthenticationForm redirect_field_name = REDIRECT_FIELD_NAME @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # …