Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django factories for unit test: "Cannot assign "'1'": "User.group" must be a "Brand" instance."
I'm getting an error when I run my unit test for my user_profile/model.py: "Cannot assign "'1'": "User.group" must be a "Brand" instance." I believe this error is because, in my factories for my unit test (factories.py), I'm not correctly assigning group when I'm creating an instance of UserFactory(). I thing group should map to the Brand class/factory but I'm not sure how to do this.. this is my user_profile/model.py: class Brand(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( 'username', max_length=50, unique=True, db_index=True ) email = models.EmailField('email address', unique=True) group = models.ForeignKey(Brand, null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_approved = models.BooleanField(default=True) and in my user_profile/test/factories.py: from user_profile.models import User, Brand class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ( 'username', 'email', 'password', 'is_approved', 'is_active', 'is_staff', 'is_admin', 'group' ) class BrandFactory(factory.django.DjangoModelFactory): class Meta: model = Brand django_get_or_create = ('name',) BrandFactory(name='BRAND1') BrandFactory(name='BRAND2') BrandFactory(name='BRAND3') BrandFactory(name='BRAND4') UserFactory( username='myuser1@gmail.com', email='myuser1@gmail.com', password=12345, is_approved=True, is_active=True, is_staff=True, is_admin=True, group="1" <--- HOW DO I MAP THIS TO THE 'BRAND1' FACTORY/CLASS?! ) UserFactory( username='myuser2@gmail.com', email='myuser2@gmail.com', password=12345, is_approved=True, is_active=True, is_staff=True, is_admin=True, group="2" <--- HOW DO I MAP THIS TO THE 'BRAND2' FACTORY/CLASS?! ) -
Python WebSocket Client connecting but not sending messages
While using websocket client to send test messages to a django server, I cannot get a script to work which can both send and receive messages. The following python script is what I have attempted: import websocket import threading import json from time import sleep # handle message event def on_message(ws, message): print("message recieved: %s" % message) # handle close event def on_close(ws): print("channel closed") # execute as main script if __name__ == "__main__": websocket.enableTrace(True) # new app object connecting to headstation ws = websocket.WebSocketApp("ws://192.168.0.106:8000/?testI123", on_message = on_message, on_close = on_close) # run in a new thread - kill if script ends ws_listener = threading.Thread(target=ws.run_forever()) ws_listener.daemon = True # start second thread ws_listener.start() # attempt connection 5 times timeout = 5 while not ws.sock.connected and timeout: sleep(1) timeout -= 1 # error on timeout if (timeout == 0): print("Connection to server timed out") print("test 1") # periodically send test message to server message_num = 0 while ws.sock.connected: # send node id and message message = 'hello %d'%message_num ws.send(message) sleep(1) message_num += 1 This connections successfully, indicted by the server, and receives messages sent from the server, but does not send anything. Periodically, something like this is displayed on the terminal: … -
Django keep track of object exports
I have my models in models.py with custom export method (that dumps my data to .xml file - in order to be included in .xml file company must have some fields manually filled in by me) class Country(models.Model): name = ... class Company(models.Model): country = ForeignKey(Country .. ) name = .... address = .... Companies are scraped from different sources and sometimes don't contain all the necessary information. Then I manually go through each company and I fill in the gaps. I need to somehow track how many companies I exported after clicking 'export button' for each country. I don't want to export multiple times the same company. My question is: How to approach this? Should I create a new class named Export where I will track everything or are there better methods? All the best and Merry Christmas! -
I am getting this invalid syntax error and I do not see error. Could someone help me locate the syntax error?
from django.urls import include, path from django.contrib import admin urlpatterns = [path('polls/', include('polls.urls')), path('admin/', admin.site.urls),] File "C:\Documents\Projects\mysite\polls\urls.py", line 1 This is line 1 ^ SyntaxError: invalid syntax -
Gunicorn giving me Module Not Found Error
I'm attempting to build a Django blog. I have a couple of apps in there, but for some reason Gunicorn is giving me trouble with - ` . ├── Procfile ├── blog │ ├── blog │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── db.sqlite3 │ ├── manage.py │ ├── media │ │ ├── 1820-3-large.jpg │ │ ├── 1820-3-large_XGHcfcZ.jpg │ │ ├── 1820-3-large_ZTmLkYt.jpg │ │ ├── 1820-3-large_dPbPsPW.jpg │ │ └── paul-morris-144777.jpg │ ├── posts │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20171217_0000.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-36.pyc │ │ │ ├── 0002_auto_20171217_0000.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ │ ├── models.py │ │ ├── static │ │ │ └── posts │ │ │ ├── css … -
Django-registration 'Password_reset_done' goes to the wrong URL route
On Djano-registration with Django 2.0 everything seems to be working OK. However, when I go to reset password, type in the email and submit, it redirects me to: http://127.0.0.1:8000/accounts/password/reset/auth_password_reset_done instead of: http://127.0.0.1:8000/accounts/password/reset/done/ It seems that it's confusing the url with the url name: ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] Any ideas why? -
sitemap takes exactly 1 argument (0 given) in django 1.11
I tried to create a sitemap for my website using django's sitemap system. django version is 1.11.7 and I included both 'django.contrib.sitemaps' and 'django.contrib.sites' in settings.py file. urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.contrib.sitemaps.views import sitemap from app.views import postSiteMap sitemaps = {'postMap':postSiteMap} urlpatterns = [ # other urls url(r'^sitemap.xml/$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] sitemap view in views.py: def postSiteMap(Sitemap): changefreq = "daily" priority = 1.0 def items(self): return Post.objects.filter(is_draft=False) def lastmode(self, obj): return obj.postDate the error is : postSiteMap() takes exactly 1 argument (0 given) but i don't know where exactly I most add a argument. -
DJANGO: TemplateDoesNotExist: auth/user_confirm_delete.html
I'm trying to create a "delete account" functionality in Django. I use DeleteView for this purpose. The problem is that after calling this view, Django raises: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/delete-account/ Django Version: 1.11.7 Exception Type: TemplateDoesNotExist Exception Value: auth/user_confirm_delete.html My view: class DeleteAccount(LoginRequiredMixin,DeleteView): model = User def get_object(self, queryset=None): user = self.request.user userprofile = user.userprofile userprofile.prepare_to_delete_account() return user Why it tries to render this template and why there is no such template if it's being called? Do you know how to fix this? -
In an DeleteView with the form, how does django know where to redirect to?
url.py url(r'^delete_student/,(?P<pk>\d+)/$' ,views.StudentDelete.as_view(), name='delete_student'), Error message: No URL to redirect to. Provide a success_url. Django Version: 1.9 Exception Type: ImproperlyConfigured Exception Value: No URL to redirect to. Provide a success_url. -
Django 2.0 reusable apps - TemplateDoesNotExist at /polls/
Python 3, Django 2.0 I just got to the end of the official Django tutorial, and I'm working on the advanced portion - "How to write reusable apps" It seems like I was at least partially successful, I can access the Questions and Choices through the admin interface, but when I try to display the http://127.0.0.1:8000/polls/ I get this error: TemplateDoesNotExist at /polls/1/ I get a similar error for trying to access a detail page, at http://127.0.0.1:8000/polls/1/ I looked through all the troubleshooting questions I could, and my main question is - how can you access templates that are packaged into an app? The thing I see going wrong is that Django is trying to find the app templates inside the main project directories(ie: /tutorial/templates/polls/detail.html), but they should be "inside" the module I imported from pip. Are you actually supposed to package the templates into apps this way? I tried throwing the template files back into tutorial/templates/polls/ and it works just fine, but this goes against what I think should be "reuseability" because then the packaged app won't have it's own templates. The answers I was able to find seem to be more for older versions of Django, and used … -
Django: send context to 'base.html'
I have a nav bar item that is used to register/login. As, it's gonna be in different pages, I'm thinking of calling this form "once" for every page, in the 'base.html'. I've found about the 'context processor' (Django - How to make a variable available to all templates?), however, as I can see, it passess only a variable to all templates. For that, it uses a function like this one on the file: view.py: def categories_processor(request): categories = Category.objects.all() return {'categories': categories} However, I'm using Class Views in my views.py, and, generally, I do pass the 'request', 'url to be rendered', 'context'. Like this: view.py: class RegistroClienteView(View): def get(self, request): ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto') form = ClienteCreationForm() context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento} return render(request, 'app_cliente/frontend/ingreso.html', context) def post(self, request): ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto') form = ClienteCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'app_cliente/frontend/ingreso.html', context) context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento} return render(request, 'app_cliente/frontend/ingreso.html', context) My question is what to return in the View? After following the steps for seetting up the 'context-processor.py', in this file, I have: Please, notice that I'm only returning the context from app_cliente.forms import ClienteCreationForm from django.views import View from nucleo.models.tipo_documento import … -
Django admin loads blank page
I'm writing my first Django project in Django 2.0. I have created an app named sharednotes The contents of sharednotes/models.py is from django.conf import settings from django.db import models from notes.models import Note User = settings.AUTH_USER_MODEL class Shared(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) can_write = models.BooleanField(default=False) can_delete = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.note.title Here the note instance can be shared with user instance or to the email if user is not available. I have registered this model in sharednotes/admin.py from django.contrib import admin from sharednotes.models import Shared admin.site.register(Shared) on browing http://example.com/admin/ it lists Shareds which links to http://example.com/admin/sharednotes/shared/ but when clicking on it loads a blank page with no item on it. There is not even any error message or warning printed in terminal console. Could not understand what is causing this error. -
How to create a "Quiz" model that has unknown number of options with one or more correct answers?
I am trying to make a model for a "Question/Quiz" . A question can have as many choices (Charfields) as user wants , and there can be one or many correct answers (out of those options) . How should I define this model? Question: Some long description. Choice 1 Choice 2 Choice 3 - Correct Ans Choice 4 - Correct Ans So far I came up with this but I think it is a bad design: class Question(models.Model): description = models.CharField('Description', max_length=300) correct_answer_id = models.UUIDField('answer_id', null=True) options = models.ManyToManyField(Answer) class Answer(models.Model): """ Answer's Model, which is used as the answer in Question Model """ text = models.CharField(max_length=128, verbose_name=u'Answer\'s text') ans_id = models.UUIDField(default=uuid.uuid1()) -
django 2.0 - url match everything
I am trying to set my django 2.0 project urlconf so that all URLs go to the same app, and within that app all URLs point to the same view. Seems really simple! Still, my intuition and looking for help on the Internet fails me. I am completely new to django, but have experience with programming in general. Here is what I tried: I have the main project project/url.py with the setting: urlpatterns = [ path('admin/', admin.site.urls), path('', include('main_app.urls')) #Pattern A ] And then in the main_app/url.py: urlpatterns = [ path(r'^.*$', views.index, name='index') #Pattern B ] but using the address even with an empty URL (just the domain name) gives me an error: Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ ^.*$ [name='index'] The empty path didn't match any of these. Looking for help directed me to these places (among others): What is the python regex to match everything? the suggestion there is to put r'^' as Pattern A, but this didn't work for me. Django URL template match (everything except pattern) the suggestion there is to use r'^.*' as Pattern B, which is exactly what I used. I noticed in the web … -
Very elementary TypeError in Django
I'm following all of the instructions in this tutorial, time 2:26 https://www.youtube.com/watch?v=gqRLPx4ZeSw&t=3s and I cannot get the expected result. The TypeError I'm getting is raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). File: urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/$', 'posts.views.post_home'), # url(r'^posts/$', '<appname>.views.post_home'), ] File: views.py from django.shortcuts import render from django.http import HttpResponse def post_home(request): return HttpResponse("<h1>Hello</h1>") And here are the relevant screenshots, however I cannot post them because the computer thinks that they're code. Because it thinks they're code when I hit cntrl k the screenshots go away, but if I do not hit cntrl k, then I cannot post the thread. -
Django views.py raises requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected
I want to retrieve an image using requests in a Django View but it keeps on throwing error while doing. python org_logo = requests.get("http://github.com/org.png?size=32") print(org_logo) In this case it throws: HTML responses requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) HTML page response ConnectionError at / ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.8 Exception Type: ConnectionError Exception Value: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) Exception Location: /usr/local/lib/python3.6/site-packages/requests/adapters.py in send, line 473 Python Executable: /usr/local/opt/python3/bin/python3.6 Python Version: 3.6.0 I think this has something to do with the library requests -
Memory leak using django channels, apscheduler, and google oauth2client
My code pulls data from Google Analytics every X seconds and pushes it to a WebSocket frontend via Django Channels. I'm using an apscheduler BackgroundScheduler to run the tick function on the specified interval. But when I run this, the memory usage grows at a pretty constant rate even if all I do is authorize the oauth API. Example code from consumers.py: from channels.sessions import channel_session from apscheduler.schedulers.background import BackgroundScheduler from oauth2client import transport from apiclient.discovery import build scheduler = BackgroundScheduler() def tick(group_id): user = GoogleUser.objects.all()[0] # gets DjangoORMStorage instance credentials = get_credentials(user).get() # THESE TWO LINES SEEM TO CAUSE THE MEMORY LEAK oauth_http = credentials.authorize(transport.get_http_object()) analytics = build('analytics', 'v3', http=oauth_http) @channel_session def ws_connect(message): # accept socket connection and add channel to group message.reply_channel.send({"accept": True}) # add channel to websocket channel group redis_group = Group(group_id, channel_layer=None) redis_group.add(message.reply_channel) # schedule job scheduler.add_job(tick, 'interval', id=slug, kwargs={ 'group_id': group_id, }, seconds=settings.INTERVAL) scheduler.start() -
Django Form ChoiceField set choices in View in Form initial
This is the form class Form(Models.Form): title = forms.ChoiceField() I need to set choice values in title field according to what i get in queryset, how can it be done?? def func(request): titles = Titel.objects.all() form = Form(initial={ "title": "???titles???"}) return render('template.html', locals()) -
Override Field attribute in Django Model
I have a problem. I'm trying to change the directory on which a file gets uploaded, using the upload_to attribute of a FileField, without success. The main issue is that I have defined a parent class, with a file attribute, and I want to change the directory on the child class. My models are defined in this way : class DocumentBase(models.Model): file = models.FileField(upload_to=get_filename) class Document(DocumentBase): file_type = models.CharField(max_size=150) I tried to overwrite the FileField in the child class, without success (I'm aware now that this is not possible.) I also tried the answers on this other question (that is very similar to my problem), without success. Could somebody help me with this? Thanks! -
How to retrieve value from one to one field tables in Django?
I have used two models and a django built in User model. class UserInfo(models.Model): user = models.OneToOneField(User) user_contact = models.CharField() age = models.IntegerField() class Review(models.Model): user = models.ForeignKey('exam.UserInfo') is_reviewed= models.BooleanField() The UserInfo field is one to one with the User model. User model have the 'username' field that I want to retrieve. But I can't get through how to get the username of those users who have is_reviewed field is 0. So far what I was trying but failed to retrieve: result=Review.objects.select_related('user_id__id').filter(is_reviewed=0) -
[Django]Import data into mysql from file
Let's explain my problem. I'm trying to import data from a file ( 3 columns) into my local mysql database. It contains 27442 rows. i use code below def import(file): base_dir= '/home/xxxxx/Desktop/' with open(os.path.join(base_dir, file), 'r') as f: for line in f.readlines(): line=line.split() #remove all useless space if len(line) >= 3: host.objects.create( hostaddress=line[0], hostname= line[1], comment=line[2] #' ' by default ) else: raise('Invalide format') Everything seem work properly but when i check the table after importation. i get less than the half of total row (11xxx). code for django model class host(models.Model): hostname= models.SlugField(max_length=50) hostaddress= models.GenericIPAddressField(primary_key=True) comment= models.CharField(max_length=100) i need a help. Sorry for my bad english. Thanks. -
Changing Default python path on macs?
I've been doing some research on this matter but could not find a proper solution. python by default is preinstalled on Mac OS. I'm currently trying to run python 3.6 and above, but when I am using Django and creating a new virtual environment, it is referencing python 2.7. I have downloaded the newest version of python, but that does not seem to overwrite python 2.7. I believe the issue has to do with the default path of python on Macs. How would I go and change that path so that when I create a virtual environment and when I use the Django framework, it will reference python 3.6 instead of python 2.7 ? -
Django tell if last item with certain attribute in dual ordering (order_by)
In a Django queryset how can I tell if the list item I'm on (when iterating) is the list item that has a certain attribute. Example: I order a queryset by: MyModel.objects.all().order_by('-featured', '-created_at') So, all objects which are featured first by their appropriate time and then all non-featured items sorted by time properly as well. When iterating in the template I want to be able to tell if I've hit the last "featured" item in the dual-ordering (such that featured = True). Example usage: If last item -> display banner separating featured / non-featured -> continue iterating displaying non-featured after banner. {% for object in object_list %} # display object {% if last item with attribute %} # display banner {% endif %} {% endfor %} I know I can do another queryset to get the count, but that's an extra query I'd like to avoid. -
Accessing variables from other methods in a django app
I am quite new to django and python, and I have an issue using methods and define them properly. I would like to store calculation in a method .. and call that method in another method here is how it looks : def get_info_array(self, format=None, *args, **kwargs): current_response_list = get_current_team(self) member_info_array = [] for response_dic in current_response_list: current_response = list(response_dic.values())[0] chunk_score = get_chunk_score3() print(chunk_score) return chunk_score def get_chunk_score3(self, format=None, *args, **kwargs): answer_question1 = current_response.answers.get(question_id = 2) answer_question2 = current_response.answers.get(question_id = 3) json_answer_question1 = json.loads(answer_question1.body) json_answer_question2 = json.loads(answer_question2.body) answer_key_question1 = list(json_answer_question1.keys())[0][0] answer_key_question2 = list(json_answer_question2.keys())[0][0] if answer_key_question1 == "1" or "3": score1 = list(json_answer_question1.values())[0] else: score1 = -list(json_answer_question1.values())[0] if answer_key_question2 == "1" or "3": score2 = list(json_answer_question2.values())[0] else: score2 = -list(json_answer_question2.values())[0] chunk_score = math.ceil((score1+score2)/2) return chunk_score when I try to run that code I get that in current_response in get_chunk_score3 is not define, how can I access variable from other methods ? Any tips is well welcome to progress. -
Django authentication between views
I'm having some trouble using the django authentication i have a view that uses the decorator @login_required. Once logged the user will procede to a page, fill some data and use a post request to access the next page, however when trying to go back to the previous page django will show the log in form again. Is there a way to prevent this? I was thinking on using a button to go back with a post with the session so django wont ask for login again but i'm not sure if that can be done.