Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django timezones and Postgresql
I know this question has discussed not for the first time but I stuck with a problem and confused a little. So I have a celery task that should send reminders in time. In my config: USE_TZ = True TIMEZONE = 'Asia/Singapore' for example I have a model like: class Reminder(models.Model): created = models.DateTimeField(default=timezone.now) This is a simplified model it has more fields but problem laying inside DateTime fields. So then I open django shell and get time like: timezone.now() reminder.created It shows right time in UTC like: datetime.datetime(2016, 12, 22, 8, 47, 43, 370101, tzinfo=<UTC>) #tz now datetime.datetime(2016, 12, 22, 8, 47, 43, 370101, tzinfo=<UTC>) #reminder created But if I run the task from console and set up prints or trying debug with ipdb I got for time above: 2016-12-22 09:17:19.141242+00:00 # tz now 2016-12-22 16:52:43.366542+00:00 # reminder time CONVERT UTC+8 like Singapore but it became UTC now!!! So, I can't understand how it's going. And of course I can't compare datetimes correctly in this case. Django 1.8 and DB PostgreSQL -
How to write python-django queries which is ultimately going to call these queries from django
data : { "Fruit": "Pomegranate", "District": "Nasik", "Taluka": "Nasik", "Revenue circle": "Nasik", "Sum Insured": 28000, "Area": 1200, "Farmer": 183 } { "Fruit": "Pomegranate", "District": "Jalna", "Taluka": "Jalna", "Revenue circle": "Jalna", "Sum Insured": 28000, "Area": 120, "Farmer": 13 } { "Fruit": "Guava", "District": "Pune", "Taluka": "Haveli", "Revenue circle": "Uralikanchan", "Sum Insured": 50000, "Area": 10, "Farmer": 100 } { "Fruit": "Guava", "District": "Nasik", "Taluka": "Girnare", "Revenue circle": "Girnare", "Sum Insured": 50000, "Area": 75, "Farmer": 90 } { "Fruit": "Banana", "District": "Nanded", "Taluka": "Nandurbar", "Revenue circle": "NandedBK", "Sum Insured": 5000, "Area": 2260, "Farmer": 342 } { "Fruit": "Banana", "District": "Jalgaon", "Taluka": "Bhadgaon", "Revenue circle": "Bhadgaon", "Sum Insured": 5000, "Area": 220, "Farmer": 265 } I want to write all types of complex queries, for example : If someone wants information "Fruit" is "Guava" in "Pune District" then they will get data for guava in pune district. htt//api/?fruit=Guava&?district=Pune If someone wants information "Fruit" is "Guava" in "Girnare Taluka" then they will get data for guava in girnare taluka. htt://api/?fruit=Guava&?taluka=Girnare If someone wants information for "Fruit" is "Guava" and "Banana" then they will get all data only for this two fruits, like wise htt://api/?fruit=Guava&?Banana But, when I run server then I cant get correct output If … -
Virtual Environment for Python Django
I'm currently a novice in web programming. I've been working on this Django project lately, and I've been reading about virtual environments. At the start of my project, I was unable to set up a virtual environment, and so I proceeded with the project without it. My questions are Whether or not this virtual environment is really necessary? If I want to make more Django projects in the future, will I need this virtual environment to differentiate the projects since right now I'm running all the commands in the command prompt from my main C: directory? Does this virtual environment differentiate multiple projects or does it separate each project with respect to the version of Django/Python it's coded with or both? I'm wondering because I currently input commands such as python manage.py runserver (without the virtual environment) in my main C:drive directory. So does that mean I can't do multiple projects at once without a virtual environment for each? Can I still work on multiple projects without a virtual environment? (I've been confused about this especially) Should I just try to set up a virtual environment for my next project or can I still do it for this current one … -
Filter by multiple django-taggit tags with Django Rest Framework
Default SearchFilter only allows us to filter (tags in my case) if all the provided terms are matched. class MyModelViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = (filters.SearchFilter, ) search_fields = ('tags__name',) serializer_class = MyModelSerializer model = MyModel queryset = MyModel.objects.all() Filtering then works with: http://localhost:8000/api/v1/objects/?search=tag1,tag2 With above URL I only get objects if all tags are present on the object. Is there any chance I could make this filter to allow me to filter if any of the provided tags match? -
How to reflect python changes in django, uwsgi and nginx setup
Hi I have deployed Django using UWSGI and Nginx using following tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html Everything is running fine. I face a challenge while updating python code. I don't know the efficient way to deploy new changes. after hit and trial, I used following commands to deploy git pull; sudo service uwsgi stop; sudo service nginx restart; sudo service uwsgi restart; /usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals this command works fine. But I face following problems Usagi runs in the foreground. Every time I make changes, a new UWSGI instance start running. Due to multiple UWSGI instances, My AWS server get crashed, due to memory exhaustion. I want to know what commands should I run to reflect changes in python code. PS: in my previous APACHE Django setup, I only used to restart apache, is it possible to reflect changes by only restarting nginx. -
Django Project intro Tutorial 02 for Django 1.9
I've been having a problem with Django for a couple of days now and I'm stuck on this url https://docs.djangoproject.com/en/1.9/intro/tutorial02/ . I got to the topic 'Activating Models' where we have to edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls.apps.PollsConfig'. Once I did that I had to run another command: $ python manage.py makemigrations polls and should have gotten the output: Migrations for 'polls': 0001_initial.py: - Create model Choice - Create model Question - Add field question to choice However I get enter image description here Can someone help me with this Problem? Thanks! -
Use Django's pre_fetch_related function
Given the following scenario: In a library, a book can be placed in only 1 sleeve. Over the course, the book could be moved from sleeve to sleeve. And the models class Sleeve(models.Model): sleeve_name = models.CharField(max_length=60) sleeve_number = models.DecimalField() class Book(models.Model): book_title = models.CharField(max_length=120) sits_in_sleeve = models.ForeignKey(Sleeve, null=False) Now I would like to create a Django Queryset to query all the Sleeves with a number between 1 and 10, and query all the books titles belonging to that. How do I do so with prefetch_related? In other words, I can do something like: sleeves = Sleeve.objects.filter(sleeve_number__lte=10,sleeve_number__gte=1) for s in sleeves: b = Book.objects.get(sits_in_sleeve=s) s.book = b But is there a more elegant way to do so? -
Argument not reflected in Python function call
I'm calling a class method like this: soup = bs4.BeautifulSoup(self.req_proxy.generate_proxied_request(some_url).text, "html.parser", "United States") and the class method is defined like this: def generate_proxied_request(self, url, params={}, req_timeout=30, country=None): if country is not None: searched_proxies = [] for proxy in self.proxy_list: if str(proxy[1]) == country: searched_proxies.append(proxy) else: searched_proxies = self.proxy_list United States is meant to resolve to the country variable, but it doesn't. When the function is called, it takes the value None. Why isn't country reflecting the United States value? -
Django allauth: empty 'signup_url'
Using django 1.8.16 and package django-allauth==0.27.0 Login works fine, but signup page cannot be reached from login page. The default login template 'login.html' contains a link to a signup page: <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> But since the value of 'signup_url' is empty, this points nowhere. Question is: where should 'signup_url' get its value from? django-allauth documentation doesn't mention this: http://django-allauth.readthedocs.io/en/latest/installation.html More info: 'mysite.com/user/login' works fine 'mysite.com/accounts/signup' actually shows the signup page, so this is what 'signup_url' should refer to Django debug toolbar doesn't work on this page, as one needs to be logged in for the toolbar to work? Settings extract: LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') LOGIN_EXEMPT_URLS = ( r'^about$', r'^accounts/password/reset/$', r'^accounts/signup/$', ) ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" -
How to synchronize users in django rest api with Auth0
I use Angular 2 as frontend, django rest framework as backend. At frontend I use Auth0 for authenticating user (https://auth0.com/docs/quickstart/spa/angular2 ). and after I send the idtoken to my backend for creating news users (https://auth0.com/docs/quickstart/backend/python connected auth0 the code in angular 2: import { Component } from '@angular/core'; import { Auth } from './auth.service'; import { AuthHttp } from 'angular2-jwt'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'ping', templateUrl: 'app/ping.template.html' }) export class PingComponent { API_URL: string = 'http://localhost:8000/callback/'; message: string; constructor(private auth: Auth, private http: Http, private authHttp: AuthHttp) {} // the code for sending idtoken to my backend //correct me please if I am wrong public securedPing() { this.message = ''; this.authHttp.post(`${this.API_URL}`,localStorage.getItem('id_token')) .map(res => res.json()) .subscribe( data => this.message= data.text, error => this.message = error._body || error ); } }; and here the code of my backend in Django : from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from places_management.serializers import UserSerializer from django.contrib.auth.models import User import jwt class Callbacks(APIView): authentication_classes = [] permission_classes = [] def authenticate(error): return Response(error,401) def post(self, request, format=None): """ Callback for after user logs in. It creates … -
Should django templates name for each app be unique?
I'm developing a django app. It has three apps in it, each with it's own template directory and index.html file. But when I call view from the second app it picks up the template file from the first app rather than the second one. Is it a must that every template name be unique? my projects directory: ├───jobs │ ├───migrations │ ├───static │ └───templates ├───job_portal ├───main_app │ ├───migrations │ ├───static │ └───templates ├───project_static │ ├───css │ ├───fonts │ ├───images │ └───js └───recruiters ├───migrations ├───static │ ├───css │ ├───fonts │ ├───images │ └───js └───templates -
Django inherited models are not fully deleted
I have a model inheritance in django something like this: class A(models.Model): name = models.CharField (max_length = 255, unique = True) class B(A): desc = models.CharField (max_length = 255) and when doing delete on B it leaves a trail of "garbage" objects of A behind. obj = B.objects.create(name = "My", desc = "left overs") obj.delete() now I cant change the model to have t 1to1 FK to A instead of inheritance because it is an already running software. Is there any good way to do a proper delete? Thank you in advance! -
How to put line break or new line in description of fb post when sharing from our website
How can i insert a new line in description of facebook post when sharing from my website. i tried all solution which is available on stack overflow but they did not work for me. i tried: <center></center> <br/> \n &nbsp i need a solution for this. thanks. -
how to disable readonly fields in django admin
i want to convert readonly_fields to editable text fields in django using object action button.Any suggestions? how to call readonly_fields outside modelAdmin ? -
Django How to retrieve relating data with hitting database much less in situation of two tables with m2m relationship
Let's say there are two tables. #table A : Category class Category title = models.CharField() #table B : Devices class Devices device_category = models.ManyToManyField(Category) name = models.CharField() If I want to see table like above. simply I can make code using Category.devices_set.all(), then show each devices by Forloop. but problem is that you have to query individually for A, B, C, D, E. If you have more category, it seems you need to hit database more to retrieve devices relating to each category. I think the best way is retrieve all data from two tables at once. And then make table like above with javascripts. Is there any easy way to do that without hitting database many times? -
Displaying a Table with multiple rows from Database, edit default value and Update all rows to database.
I have table with multiple rows with some default values. I want to display all rows of table on single form using Django framework and edit the rows value, update all values to database on Action Submit. -
How to run raw SQL inside a Django unittest
How do you run a raw SQL query inside a Django unittest? I find if I use a cursor, it seems to break the unittest's transaction so that any changes to the Sqlite database aren't reverted at the end of the unittest. My unittest looks like: class Tests(TestCase): def test_first(self): print('FIRST:', MyModel.objects.all().count()) cursor = connection.cursor() try: cursor.execute('SELECT * FROM myapp_mymodel;') r = cursor.fetchone() finally: cursor.close() MyModel.objects.create(name='abc') def test_second(self): print('SECOND:', MyModel.objects.all().count()) and it currently outputs the unexpected: FIRST: 0 SECOND: 1 and if I comment out the cursor code, then it outputs the correct result: FIRST: 0 SECOND: 0 What black magic is going on here? Is connection.cursor not support inside Django's special unittest transaction? -
input type password not working in windows safari with python django environment
Hi I have a form in my website.the form have input type text and password. the input type password field is work fine an all browser.but input type password working on all browser but not work in safari.im using safari 5.1.7.please help to solve the problem. -
Form submit button not working and getting URL redirect error
I'm experiencing two form/redirect issues in deployment only (using Django) that could be related: I have a form to create new blog posts which, upon hitting Submit, should redirect you to a url based on the category selected in the form. In production it works fine, but in deployment clicking the Submit button to create a new post does nothing (no redirect, form stays as is, nothing gets added elsewhere in the site) and nothing pops up on my error log. Note that I haven't set a value for "action=" in the form template and am not sure what (if anything) I should include to still allow me to redirect to different pages depending on the values in the form. I can also edit a blog post which takes me to the form page with all the fields filled out. When I edit a value and hit Submit, it DOES update the blog post but redirects me to a page error: Not Found: The requested URL /resources/books.views.resources was not found on this server. If you check out the urls.py file, there is no "books.views.resources" url anywhere. Books is what I named the model. I'm not sure why in deployment this … -
Copying a model instance with many2many fields without saving
I have a view that copies a model instance. It sets .pk=None and then renders a form for the user to cancel, change stuff, and save. However the M2M fields are blank in the form, and I'd like them to be prepopulated with the same values as the original model instance. def event_copy(request, id=None): new_event = get_object_or_404(Event, id=id) new_event.pk = None # autogen a new primary key form = EventForm(request.POST or None, instance=new_event) if form.is_valid(): event = form.save() messages.success(request, "New event created") return HttpResponseRedirect(event.get_absolute_url()) context = { "form": form, } return render(request, "events/event_form.html", context) The Event model that is being copied has two M2M fields, and these are both blank in the form: class Event(models.Model): title = models.CharField(max_length=120) ... blocks = models.ManyToManyField(Block) facilita tors = models.ManyToManyField(User) How do I prepopulate these ManyToManyFields? -
Django crispy forms get call with search
I am trying to use django crispy forms to do a filter and search for items in a my database. All or most of the examples I found are related to "post" while a "get" call is necessary for a search. While I can get "country" to work by having the user select it from the modelform itself, I am having issues adding search ranges such as salary and a detailed search. Is there a way to add search functions that work together with the form inputs that are not part of the what is inside the database? For instance, the Div(AppendedText('salaryrange', '$') and Div(AppendedText('Test', 'Search') below is requiring me to insert a field into 'salaryrange' and 'test' but these are items that may or may not exist in the database. I have gone thought the documents but they give examples that require the field input, all the items I found online are related to posting. I think if crispy form method allows a "get" there should be a way to do this. Or is django crispy forms limited in this aspect? Below is my sample code class ExampleForm(forms.ModelForm): class Meta: model = Worker fields = [ "country", "salary", ] … -
Apache cannot read share folder
i'm using:- django 1.10 python 2.7 apache24 windows10 And I develop a system that will read a file from a network drive(share folder) which are X:// and Y://.When I running using python runserver all function works well.. But when I running in localhost/ i got error drive x:// and Y:// not specified Do i need to do something in my httpd.conf? -
Django Class-based ViewCreate and ViewUpdate file upload
I have a project where I wish to upload an image with the Django auto generated class-based views, and it works on the admin side, but I don't know what I'm missing to make it work from an html page. I've searched the web with little luck, or not enough clarification. So maybe someone can tell me what I'm missing. Here is my code: settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'project/app/media_cdn') models.py from django.db import models from django.core.urlresolvers import reverse ... ... # Create your models here. ... class Article(models.Model): title = models.CharField(max_length = 200) ... thumbnail = models.FileField(null = True, blank = True) ... def __str__(self): return self.title def get_absolute_url(self): return reverse('articles_detail', kwargs={'pk': self.pk}) class Meta: ordering = ['-pk'] views.py from django.shortcuts import render from app.models import Article from django.views.generic import * from django.core.urlresolvers import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. def index(request): return render(request, 'index.html') class ArticleList(ListView): model = Article class ArticleDetail(DetailView): model = Article class ArticleCreate(LoginRequiredMixin, CreateView): model = Article fields = ['title', 'description', 'abstract', 'thumbnail', 'author', 'category', 'publishDate'] class ArticleUpdate(LoginRequiredMixin, UpdateView): model = Article fields = ['title', ..., 'thumbnail', ...] class ArticleDelete(LoginRequiredMixin, DeleteView): model = Article success_url = reverse_lazy('articles_list') urls.py from … -
Django Image Uploading - Uploads do not work
I am currently working on a Django app and I have come across an error that I am unsure how to fix. I have looked about online but still haven't found an answer that suits my code. I am trying to allow users to upload a profile picture however I am not sure why it won't work. The files do not upload to the correct folder and IF they do upload somewhere I am not sure where. I think it may be something to do with the path that is referenced in settings.py and the upload_to in my model. All help is appreciated. Thanks in advance. :) Image of the directory setup of my files settings.py file (bottom of it) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') LOGIN_REDIRECT_URL = 'main:home' AUTH_USER_MODEL = 'main.Designer' INTERNAL_IPS = '127.0.0.1' models.py (Designer Model) class Designer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=25, unique=True) display_name = models.CharField(max_length=25) twitter = models.CharField(max_length=15) bio = models.TextField(max_length=145, blank=True, default="") avatar = models.ImageField(upload_to='img', default='img/default_profile_pic.jpg') up_votes = models.IntegerField(default=0) available = models.BooleanField(default=False) thumbnail_price = models.FloatField(null=True) channel_art_price = models.FloatField(null=True) monthly = models.BooleanField(default=False) promoted = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) If there are any other parts … -
Is it possible to setup MySQL with Django 1.10.4 on Python 3.5 with Visual studio community 2015? [duplicate]
This question already has an answer here: Python Connector for Django 1.9 and Python 3.5? [closed] 1 answer I have installed Django 1.10.4 on python 3.5 I am not able to install mysqlclient with the following command: pip install MySQL-python or pip install mysqlclient I get the following error: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,9,'final',1) -D__version__=1.3.9 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -Ic:\users\chandan\anaconda3\include -Ic:\users\chandan\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /Tc_mysql.c /Fobuild\temp.win-amd64-3.5\Release\_mysql.obj /Zl _mysql.c _mysql.c(29): fatal error C1083: Cannot open include file: 'my_config.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 Is this installation possible with Visual Studio community 2015 Will re-installation of VS community edition help?