Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python datetime: strptime and strftime not converting same data correctly
I am converting a datetime object into a string to be passed over http to another server (in a json object as a field) where it is again converted to a datetime object using strptime. However, intermittently the two-step conversion does not result in the same data that was originally converted. Always, the error is reduction of one second in the final datetime object. My python version on both servers is 2.7.6. The sending server is running on django version 1.8.2. The receiving server is running on django version 1.9. The date format I am using for conversion/de-conversion is "%Y-%m-%dT%H:%M:%S.%fZ". Is this supposed to happen or some version mismatch is causing this? Any help will be greatly appreciated. -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value
I'm building a web application that uses Django. One of it's purposes is to pull data using an API call and insert that into a database to be displayed on a web page. I'm able to pull the data but I'm having troubles inserting it into a the database. Whenever I try I get the error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I've followed the directions given by others and I haven't had any luck. This is the def in question: import requests from django.conf import settings settings.configure() from polls.models import Poll def getSnacks(): response = requests.get('https://api-snacks.nerderylabs.com/v1/snacks?ApiKey=xxxxxxxxxxxxxxxxxxx') print("adding to DB") html = response.json() snackArray = [] x = 0 p = Poll.objects.get(pk=1) while x < len(html): snackArray.append(html[x]) x += 1 for y in snackArray: print("uploading " + y["name"]) snackID = y["id"] snackName = y["name"] snackOp = y["optional"] snackLoc = y["purchaseLocations"] snackCnt = y["purchaseCount"] snackPrchDt = y["lastPurchaseDate"] p.snacks_set.create(name=snackName,source_ID=snackID,optional=snackOp,purchaseLocation=snackLoc,purchaseCount=snackCnt,lastPurchaseDate=snackPrchDt,votes=0) And this is the settings file. import os # Django settings for mysite project. import dj_database_url DEBUG = True TEMPLATE_DEBUG = DEBUG BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # print("pip1") ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { … -
How to convert search query results into Json serializable object in Django
I am running a filter query in Django and my return results are as follows. search_result = [{'code': '12345', 'city': 'city1', 'country': 'USA', 'state': 'state1'}, {'code': '15675', 'city': 'city2', 'country': 'USA', 'state': 'state2'}] I stored this returned data to a dictionary. data_dict["return_result"] = search_result data_dict["is_success"] = True Now I am returning this data_dict as JsonResponse.(bcz this url was called using AJAX). JsonResponse(data_dict) In this process I am getting below error - [{'code': '12345', 'city': 'city1', 'country': 'USA', 'state': 'state1'}, {'code': '15675', 'city': 'city2', 'country': 'USA', 'state': 'state2'}] is not JSON serializable. Above mentioned data is a NOT a valid Json because of single quotes. If all single quotes are replaced with double quotes then this is a valid json. Is there any way I can convert it to valid json or search query returns valid json. -
Django Is using ManyToManyField more flexible and extendable than other Fields?
I know difference between three relation fields; OneToOneField, ForeignKeyField, ManyToManyField. I also know basic concept of index, primary key, foreign key in database level. Well, I heard that making relationship between two classes with ManyToMany relationship in Django would be more flexible for change or modification later. Because In case of using ForeignKey in Django, you should have a column which directs relating table with FK in database table. In case of using ManyToMany in Django, it creates another table to show relationship between two classes with two columns directing each table with Foreign Key in database. You can get two separated classes and another table to show relationship between those two. Group, User, Permssion in Django also have relationship with ManyToMany Field. Of course, I found that people say that you can choose one for your usage case. ForeignKey Field and ManyToManyField in django have different role in relationship for sure. But I want to ask if ManyToManyField would be more flexible if you have possibility to modify your code(relatinoship between models) and your model class's field in the future. Because I think ManyToManyField can cover ForeignKey role even though you have to handle more to retrieve data. How … -
django_filter query_params = None
I have a Django model class Task(models.Model): ... executors = models.ManyToManyField(Member, related_name='tasks',) class Member(models.Model): ... person = models.ForeignKey(Person) and drf viewset from rest_framework import viewsets class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('project', 'executors__person','executors',) def get_queryset(self): if self.request.user.is_superuser: return Task.objects.all() queryset = Task.objects.filter(project__members=self.request.user.person) executor = self.request.query_params.get('executors__person', None) if executor is not None: queryset = queryset.filter(executors__person=executor) else: queryset = queryset.filter(executors=None) return queryset It worked when send request with query params as http://localhost:8000/api/tasks/?project=&executors__person=1 i get tasks with specified executor, and when send request without params http://localhost:8000/api/tasks/ i get only tasks with empty executors. But i need three conditions: Show all tasks (this didn't work when i set custom filter) Query params with selected person Query params when executors is empty How to do it? -
Dynamic queues in Celery
For example, I have a Django app. Each authorized user can add some (more than one) tasks to a Celery queue. All the tasks are long-time. I want tasks in a queue being solved not more than one for each user at the current time moment. For example, if I have {'user_a': task_1, 'user_a': task_2} and {'user_b': task_1}, Celery worker shouldn't pick up task_2 of user_a until task_1 of user_a ends. How to make it with Celery? Please give me advice. -
Django Static files not working after collect static
This has been making me dumbfounded for the last two months. Everything in the world works until I disable Debug mode. I collect static from [root]/dev_static to [root]/web/static and in my settings I have the static path set to 'static/'. I've looked at countless blogs, questions, posts, tutorials and even picked apart the docs, and nothing has helped. When I go to that path in the browser I simply get a 404. settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ 'www.instancegaming.net', 'instancegaming.net', '.instancegaming.net' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'blog' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'web.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates' ], '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', ], }, }, ] WSGI_APPLICATION = 'web.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { … -
400 Bad Request call when I try to send data through Ajax after pagination
I am pretty new to coding, so I apologize if this is not clear. I have created a quiz app with Django that takes yes or no answers for any question, and when ever a no answer is given, a Modal should pop up asking for the user to provide more details. This modal passes the information back to the database with an ajax call when the user hits submit. Everything works fine on the first question, but after the second question loads in the pagination, I get a 400 (bad request) error, and the console shows that all of my hidden fields with initial conditions are blank. I had previously resolved this by having the page refresh after each submission, but that does not save my answer to the database, only allows me to pass the modal information. Here is the code for my ajax $(document).ready(function(){ $("#submit-btn").click(function(event){ event.preventDefault(); var formData = $("#question-form").serializeArray(); var indexed_array = {}; $.map(formData, function(n, i){ indexed_array[n['name']] = n['value']; }); var answer = indexed_array.answer_id; console.log(answer); if (answer != 2) { $("#question-form").submit() } else { $("#questionModal").modal("show"); } $("#sendDiscrepancyForm").click(function(e){ e.preventDefault() var mForm = $("#sendForm").serialize() $.ajax({ type: "POST", url: "{% url 'ajax_hit_list' %}", data: mForm, success: function(data){ console.log(data) $("#modalMessage").html("<p>This … -
how to bypass the username default insert in django?
Currently having django 1.9 Using it's own built-in user model. I changed the way of login can either use username/email but when registering, I don't want username to be used. When I start saving it'll give me error of UNIQUE constraint failed: auth_user.username which I know it's because it must be entered. Is there a way to easily bypass it? -
Reading existing Django models from inside Scrapy spider
I am working on a project where urls are put into a Django model called UrlItems. The models.py file containing UrlItems is located in the home app. I typed scrapy startproject scraper in the same directory as the models.py file. Please see this image to better understand my Django project structure. I understand how to create new UrlItems from my scraper but what if my goal is to get and iterate over my Django project's existing UrlItems inside my spider's def start_requests(self) function? What I have tried: 1) I followed the marked solution in this question to try and see if my created DjangoItem already had the UrlItems loaded. I tried to use UrlItemDjangoItem.objects.all() in my spider's start_requests function and realized that I would not be able to retrieve my Django project's UrlItems this way. 2) In my spider I tried to import my UrlItems like this from ...models import UrlItem and I received this error ValueError: attempted relative import beyond top-level package. -
how to modify auth_user table and change login option in django?
I am currently using django 1.9 and really new with python. I see that django has it's build in user model and authentication. I realized the auth_user table is making username as unique and not the email I am able to make the login using the username and password but how can I make it do when register the email must be unique too and in login only email and password is needed? I have something like this in my user/view.py # registration page class RegisterUserFormView(View): form_class = RegisterUserForm template_name = 'registration_form.html' # display blank registration form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data and redirect to specified url def post(self, request): form = self.form_class(request.POST) # validate form and authenticate user else reload the page with errors if form.is_valid(): user = form.save(commit=False) # store locally but not into db yet # cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) # hash / md5 / salt the password user.save() # returns user objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/welcome/') return render(request, self.template_name, {'form': form}) # login page view … -
My Form is not appearing
Please how do I get my form to appear ? I'm a beginner. So far only the html heading and the submit button are showing. Views.py: from django.shortcuts import render # Create your views here. from signups.forms import SignUpForm def home(request): form = SignUpForm() return render(request,'signup.html') signup.html: <!doctype html> <html lang="en"> <head> </head> <body> <h1>Join Now !!!</h1> <form action='' method='POST'> {{ form.as_p }} <input type='submit'> </form> </body> </html> -
Why PyCharm is not suggesting autofill for django models?
Recently my PyChar, stopped suggestions for my django project. It is not suggesting model fields when I type. Here is example, my model.py file, class User(model): field_one = django.field field_two = djangp.field please ignore the info as it is not actual model, so whenever I try to use user = User.objects.get(field_one='something') my PyCharm used to give me fields suggestion inside .get() when my curser was inside the parenthesis like field_one, field_two and other objects/fields from super class etc but now it is not giving me any suggestion. It is painful because I have Foreign Keys in some of my model which has other foreign keys inside. It was easy to write queries but now, it is not easy as my models are big and contains different connections by foreign keys. I have tried changing preference, python interpreter, django support etc solutions that I have found online. PyCharm is suggesting me other python codes and autofills so if I write, user = User.objects. it will give me suggestions of methods like get(), filter(), get_or_create() etc but not field's inside the method. Can anyone tell me how to fix it? Thanks. -
How to actually reude an app in Django?
Take for instance the polls app in the official Django tutorial, if for example I had a homepage and would like to make a sidebar containing a poll, how to I actually code it in relation to that homepage using the polls app? Which app should the homepage belong? There is absolutely no tutorial that exist anywhere. -
Django - How to have multiple (4) distinct forms in CBV
I need 4 forms to: sign up for an event (1), un-sign up for an event (2), type in a passcode to manage an event (3) which then shows a modal box that allows that person to check in everyone that shows up at the event (4). I'm using a (ListView, FormView) to allow looping through the numerous events, each of which has a form on it (but it's the same class of form that's used for signing up). My current CBV: class EventsDisplay(ListView, FormView): template_name='events/index.html' context_object_name = "events_list" queryset = Events.objects.all().order_by("date") form_class = SignUpForm success_url = "/events/success" def get_context_data(self, **kwargs): self.object_list = self.get_queryset() context = super(EventsDisplay, self).get_context_data(**kwargs) context['announcement'] = Announcement.objects.all().order_by("-datetime") context['signup'] = SignUps.objects.all().order_by("fullname") return context def form_valid(self, form): instance = form.save(commit=False) instance.ip = get_ip(self.request) instance.save() return super(EventsDisplay, self).form_valid(form) How would I modify this to support up to 4 different classes of forms. Also, I know this may be considered a separate question, but how do I make it so that after POSTing a form successfully, it doesn't redirect to another page; instead, it takes you back to the same page the form is on and displays a message or show a Bootstrap modal box for example. -
django error for no reverse match
So I am teaching myself Django and had a good project going for awhile. I tried to add a registration module and set it up so that you could register for the site and only those who were logged in could see the content pages. Well in the process I have screwed something up and now none of the pages will load except for the admin module pages. When I start the development server I get a NoReverseMatch at / error. It says reverse for 'auth_logout' with arguments'()' and keyword arguments '{}' not found. I have tried to research anything I can find to figure out where I went wrong and have tried a number of different configurations to see if I can solve it but now I think I have screwed it up so bad I can't even get back to where I started. Can someone please take a look at see if they can point me in the right direction before I do too much more damage? Here is my views.py from django.shortcuts import render, render_to_response, redirect from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse from django.template import RequestContext, Context from app.forms import … -
Django installation, manage.py "Couldn't import Django"
I have been struggling to get Django up and running. I used pip to install Django version 1.10.4 and I have been following the tutorial for the poll app. However, when I get to the manage.py runserver step, I get the following error: "Couldn't import Django. Are you sure it's installed and" ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment" Paths = zip, DLLS, lib, Python 3.5, lib\site-packages django-admin is in Scripts, however I copied the exe to Python 3.5, which is the dir I ran: django-admin startproject mysite I ran the runserver command from Python3.5\mysite which contains manage.py Any help will be much appreciated. Thank you in advance. -
Strange behavior: some words breaks search Elasticsearch
I am using http://elasticsearch-dsl.readthedocs.io 0.0.10 and ES 1.7.3 Faced a strange behavior during search: some words that I pass to "should" query breaks search - search cannot find that words (I see that in console) - but also a lot of other words too. In code below "should" query consist of 1000 clauses. My guess was that this word is not in vocabulary (I use russian and english morphology config) - but no, with other unseen and special words search is good. So, when i remove these "problem" words search is working again. This is super strange - I tested "problem" words with https://django-haystack.readthedocs.io/en/v2.5.0/index.html and ES can find them.... for i in eat_search_raw_list_1024: q = Q('bool', #must=[Q('match', text='BBQ')], should=[(Q("match", text="\'bad service\'~3") | Q("match", text="\'bad eat\'~3") .........1000 more................], minimum_should_match=1, _name=name_query ) s = Search(using=client, index="haystack").query(q).query(~Q("match", text=minus_words)) s = s.highlight('text', fragment_size=50) response = s.execute() -
Optimize displaing results with django-haystack RealTimeSignalProcessor
I use Django as backend for my web-app and django-haystack(with Solr) for searching & displaying results. I use the RealTimeSignalProccessor form django-haystack , but I have one problem: - I have an Auction model and expires-(DateTimeField). When I'm displaying the results I'm doing it similar like e-bay (ex. Expires in: 1h 23m 5s ). The problem is that on the page that all Auctions are displayed, if you want to update the Expires in parameter on every time you visit this view (as I've read in the django-haystack documentation) , you'll have to use the object.save() method to update the Solr indexing database. But if I do that for 30 results everytime i go to that view where all auctions are listed , it's very slow and it's not efficient. Is there any other solution ? What do you suggest ? -
Django FileField manuall copying
class ModelFile(models.Model): ufile = models.FileField(upload_to="files") And I have some managmment command and inside: ... my_file = ModelFile.objects.create(ufile='/home/myfile.txt') And I have objects instance, but I don't see myfile.txt in my files directory in project? What am I doing wrong? -
django rest framework serializing a model to return its str representation
Say that my serializer looks like so class EntitySerializer(serializers.ModelSerializer): entity_instance = EntityInstanceSerializer(many=True) tags = EntityTagSerializer(many=True) class Meta: model = Entity fields = ('id', 'entity_instance', 'tags', 'note', 'source') class EntityTagSerializer(serializers.ModelSerializer): class Meta: model = EntityTagLabel fields = ('entity_tag_label',) My tags model looks like this: class EntityTag(models.Model): entity_tag_label = models.CharField(max_length=255, unique=True) def __str__(self): return self.entity_tag_label Now this is fine and all, but my response looks like this: ... "tags": [ { "entity_tag_label": "SENDER" } ], Is it possible for my tags serializer to simply return the string representation of each tag? That way I would just have "tags": [ "Sender", ], as an example -
Django - Deleting instance according a user's choice in a table
I have the following situation: At the user's area on the website he can see all his real estate posts in a table. There is a "trash button" for each one of the posts. When he press the button I want do delete from DB the exact instance he choose. This is the HTML that I have. Please note that I used an to use a view to access the DB and then delete from DB. But I don't know how to send the exactly parameters to find it on the DB. <div class="container"> <div class="col-xs-12"> <h1>Olá, {{ request.user.first_name }}</h1> </div> <div class="row col-md-12 col-md-offset-0 custyle"> <table class="table table-striped custab"> <thead> <tr> <th>Imagem Principal</th> <th>Data Criação</th> <th>Tipo do Anúncio</th> <th>Tipo do Imóvel</th> <th>Preço Venda</th> <th>Visualizações</th> <th>Expira</th> <th>Status</th> <th class="text-center">Action</th> </tr> </thead> {% for anuncio in anuncios %} <tr > <td> <div class="embed-responsive embed-responsive-16by9"> <img class="embed-responsive-item" src="{{anuncio.imagem_principal.url}}"> </div> </td> <td>Falta</td> <td>{{anuncio.tipo_anuncio}}</td> <td>{{anuncio.tipo_imovel}}</td> <td>R$ {{anuncio.preco_venda}}</td> <td>Falta</td> <td>News Cate</td> <td>News Cate</td> <td><p data-placement="top" data-toggle="tooltip" title="Delete"> <button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete"> <span class="glyphicon glyphicon-trash"></span> </button></p> </td> </tr> {% endfor %} </table> </div> </div> <div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span … -
Django - queryset in a charfield form
I need help please, I'm trying to showing a select in my template from a queryset() but it's not working properly. Here's what I got: from __future__ import unicode_literals from django.db import models # Create your models here. from django import forms from activos.models import activos from activos.forms import activosForm # Create your models here. class grupos(models.Model): nombre_grupo = models.CharField(max_length=100) frecuencia = models.CharField(max_length=100) offset = models.CharField(max_length=100) activos_class = activos() activos_query = activos.objects.all() res =str(activos_query) PORT_CHOICES = (res,res), nombre_puerto = models.CharField(max_length=100,choices=PORT_CHOICES) def __unicode__(self): return self.nombre_grupo def __str__(self): return self.nombre_grupo as you can see I'm calling usuario from activos() which is in another app from my project, I want to show that result in a select in my template but when doing so I got something like this: ------------- <QuerySet[<activos:alvaro>, <activos:david>,<activos:daniel>]> I want something like this: ----- alvaro david daniel I tried to avoid that editing this line res =str(activos_query[0]) but if I delete every user from my database I ll get index error Is there an efficient way to do that? Django version: 1.10.4 -
Select a valid choice ModelChoiceField
Whenever im running formset.is_valid() i get the error: Select a valid choice. That choice is not one of the available choices. Here is what I do in my view: timeframes = HostTimeFrame.objects.all() if request.method == 'POST': form = SelectDatesForm(request.POST, timeframes=timeframes) if form.is_valid(): pass else: form = SelectDatesForm(timeframes=timeframes) My form does this: class SelectDatesForm(forms.Form): timeframes = forms.ModelChoiceField(queryset=HostTimeFrame.objects.none(), widget=forms.CheckboxSelectMultiple, empty_label=None) def __init__(self, *args, **kwargs): qs = kwargs.pop('timeframes') super(SelectDatesForm, self).__init__(*args, **kwargs) self.fields['timeframes'].queryset = qs.order_by('start') Ive been trying for hours to find where this actual validation is done, but i cant find it for the live of me. -
Django Apache and Virtualenv ImportError: No module named site
The error from apache after a 504 page [info] mod_wsgi (pid=): Python home /var/venv/mybox. [info] mod_wsgi (pid=): Initializing Python. ImportError: No module named site This is with a barely configured app. <IfModule mod_wsgi.c> WSGIDaemonProcess myapp python-home=/var/venv/mybox WSGIProcessGroup myapp WSGIScriptAlias / /var/www/html/web/myapp/wsgi.py WSGISocketPrefix /var/run/wsgi <Directory /var/www/html/web> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </IfModule> Followed every post and tutorial I can. I am on CENTOS6 . using virutal env python 2.7 the default system env is 2.6 $ ldd /etc/httpd/modules/mod_wsgi.so linux-vdso.so.1 => (0x00007ffc06174000) mywsgi.py import os,sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") sys.path.insert(0,'/var/www/html/web') activate_this = '/var/venv/mybox/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) application = get_wsgi_application()