Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password string comparison in Django app
It's impossible to get passwords of a user in any Django app, by design. I'm implementing a change password feature for my Django app, and one of the requirements is to ensure users don't keep a new password that's the same as their previous one. I can't do string comparison here, so what's the optimal pattern to follow in this case? Here's what I'm thinking: accessing my change password feature requires re-auth (i.e. users have to input the pass again). I can conceivably save the password string in a session variable at this point (e.g. session.request['old_password']), and then compare this session variable with the string of the new password the user sets? Any security concerns with this kind of a pattern? -
Assign existing ForeignKey to model fields via command line/script using pk or other means
I'm trying to import this csv data: 1/30/1987,C152,6408H,CXO-CXO,1,0.5,1,,,,,,,,,,0.5,,,,, 4/29/1987,C172,97320,CXO-CXO,1,1,1,,,,,,,,,,1,,,,, 12/12/1987,C150,10002,CXO-CXO,1,1,1,,,,,,,,,,1,,,,, 11/12/1988,C150,10002,CXO-CXO,1,0.6,2,,,,,,,,,,0.6,,,,, 11/17/1988,C150,10002,CXO-CXO,1,1.1,3,,,,,,,,,,1.1,,,,, 9/9/1989,C150,10002,CXO-CXO,1,0.8,2,,,,,,,,,,0.8,,,,, 9/11/1989,C150,10002,CXO-CXO,1,0.7,1,,,,,,,,,,0.7,,,,, 9/18/1989,C150,10002,CXO-CXO,1,0.8,1,,,,,,,,,,0.8,,,,, 9/28/1989,C150,10002,CXO-CXO,1,0.7,3,,,,,,,,,,0.7,,,,, 9/29/1989,C150,10002,CXO-CXO,1,1,3,,,,,,,,,,1,,,,, 10/3/1989,C150,10002,CXO-CXO,1,0.6,5,,,,,,,,,,0.6,,,,, Using this script: import os.path import sys import csv import django import datetime os.environ["DJANGO_SETTINGS_MODULE"] = "logbook.settings" django.setup() from flights.models import Flight, Aircraft, Approach # converts values, if they exist, to boolean objects def convertBool(row_id): if row_id: row_id = True else: row_id = False return row_id # assigns row_id as aircraft object def assignAircraft(row_id): aircraft = None aircraft_queryset = Aircraft.objects.all() if aircraft_queryset.filter(aircraft_type = row_id).exists(): pass else: aircraft = Aircraft( aircraft_type = row_id, ) aircraft.save() aircraft = Aircraft(aircraft.pk) return aircraft # adds N to registration if needed def editReg(row_id): if row_id.startswith('N'): pass else: row_id = 'N' + row_id return row_id #os agnostic file path userhome = os.path.expanduser('~') path = os.path.join(userhome, 'django_/logbook/', 'logbook.csv') with open(path, 'r') as logbook: reader = csv.reader(logbook) next(reader) # skips header for row in reader: # iterates rows # date to python datetime object date = datetime.datetime.strptime(row[0], '%m/%d/%Y').date() row[0] = date # makes any empty entry default to 0 for n, i in enumerate(row): if i == '': row[n]=0 aircraft = assignAircraft(row[1]) flight = Flight( date = row[0], aircraft = aircraft, # how do I make this assign an existing object … -
order_by doesn't work with __in
I am implementing a playlist system in my webapp for audio, I'm using DRF for the API and I've been trying to sort playlist items by index. playlist = self.get_playlist() qs = playlist.items.order_by('index') qs = Track.objects.filter(playlist_items__in=qs) However this does not work, as soon as the __in query is used, it's ordering by track pk, not the index of a playlist item. -
Django : Heroku deploy Error 500 on app pages but admin working
I am trying to deploy my django app on to heroku. It success fully working if in Procfile: web: python manage.py runserver. After updating the settings to local and production and in production.py DEBUG=False is causing the error 500 page from my django app. But if I am navigating to appname.herokuapp.com/admin the css files are broken but I can still access the app admin pages. Look at my project file tree: settings folder in project settings │ base.py │ local.py │ production.py │ __init__.py │ production.py from django.core.exceptions import ImproperlyConfigured import logging try: from .base import * import dj_database_url SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Update database configuration with $DATABASE_URL. ALLOWED_HOSTS = ['www.appname.herokuapp.com', 'appname.herokuapp.com'] log = logging.getLogger(__name__) log.info(msg='Setting is from production.py') DEBUG = False ADMIN = ('admin','xxx@gmail.com' ) # Get production configuration SECRET_KEY = os.environ.get('SECRET_KEY') DATABASES['default'] = dj_database_url.config() except (ImportError, ImproperlyConfigured) as e: print('Error occurred while importing the base.py in production.py') Procfile web: gunicorn project.wsgi The app is deployed successfully and I can navigate through the admin pages, but not the applications Upon research I thought this might be the issue with ALLOWED_HOST=[] but unable to get ALLOWED_HOST=['appname.herokuapp.com'] without adding [*] to it. -
Can django-polymorphic models be abstract?
I am trying to implement a mid level abstract class that has a polymorphic parent. Would it cause any problems class A(PolymorphicModel): name = models.CharField() class B(A): class Meta: abstract = True class C(B): pass class D(B): pass Would class C and D still be in multi-table inheritance relation with A? I am trying to implement some common methods and fields in class B. -
How to get data from ManyToManyField to choices in MultipleChoiceField
I have a form: class CreateConferenceForm(forms.Form): ... participants = forms.MultipleChoiceField(choices=?) ... And I need to put in choices argument instead of "?" data from friends field in this model: class Person(models.Model): ... friends = models.ManyToManyField( 'self', related_name='+', ) ... How can I do it? -
Catch exception from save() in Django ModelForm
I have some model and call check_root() in models save() method. This is admin form: class CategoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CategoryForm, self).__init__(*args, **kwargs) self.fields['parent'].queryset = self.Meta.model.objects.filter(is_endpoint=False) self.fields['item_class'] = ItemClassField(required=False, model=self.Meta.model) class Meta: exclude = ['is_root', 'is_endpoint'] def clean(self): cleaned_data = super(CategoryForm, self).clean() if not cleaned_data['parent']: try: self.Meta.model.check_root(cleaned_data['title'], self.Meta.model) except CategoryRootCheckError as e: self.add_error('title', '') self.add_error('parent', '') raise forms.ValidationError(e) return cleaned_data How to catch CategoryRootCheckError in save()? Then i try override save() like this: def save(self, commit=True): try: instance = super(CategoryForm, self).save() return instance except Exception as e: if isinstance(e, CategoryRootCheckError): self.add_error('title', '') self.add_error('parent', '') raise forms.ValidationError(e) I get ValidationError as Django exception: -
how to uncache Django model
I have an model called Chat that can store and retrieve cookies from itself like so: >>> chat = Chat.objects.get(pk=43265) >>> chat.cookies >>> chat.set_cookie('1','2') >>> chat.cookies '{"1": "2"}' the set_cookies method is implemented with a simple json.dumps: def set_cookie(self, key, value): if self.cookies: current_cookies = json.loads(self.cookies) else: current_cookies = dict() current_cookies.update({key: value}) self.cookies = json.dumps(current_cookies) self.save() The problem is that if if the chat object is retrieved in two different namespaces, they update its cookies independently, each one overwriting the results of another one. Example: import django django.setup() from bots.models import Chat # Let's clean all the cookies beforehand c = Chat.objects.get(pk=43265) c.cookies = None c.save() def outer_namespace(): chat = Chat.objects.get(pk=43265) # here chat.cookies are empty inner_namespace() # Now we are supposed to have inner cookie here - right? Let's set another one. chat.set_cookie('outer namespace cookie', '1') # Let's retrieve the model again and see print(Chat.objects.get(pk=43265).cookies) def inner_namespace(): inner_chat = Chat.objects.get(pk=43265) inner_chat.set_cookie('inner namespace cookie', '2') outer_namespace() If I run this I'll get: >>> {"outer namespace cookie": "1"} >>> # we lost one of the cookies! How can this situation be avoided? THe only solution I came up with involves re-retrieving the chat object in the middle of its own set_cookies … -
How to clone a django inlineformset_factory formset?
Is it possible to clone a formset (inlineformset_factory)? I'm not sure what would be the correct way to do so. I am able to clone the form by: form = self.get_form(form_class) form.instance.pk = None form.instance.save() When it comes to the formset I don't know the method. I think I understand that it is the formset's management_form that I need to manipulate to set the foeignkey to the cloned form.pk Any suggestions? I hope my question makes some sense. Thanks Adam -
How to know every user create for every object without using logging in django?
Now I have 5 models and I want to retrieve objects filtered by the user created specific object models.py for instance this model class FileCategory(models.Model): file_type = models.CharField(_('type'), max_length=128) def __unicode__(self): return self.file_type Now I have an objects with file_type equals ABC, ENB, ORJ and I want to list only the file_types which the request user created only. Is it doable? Sure I know I can add user attribute OneToOne to user model -
Django - submit multple forms in a view
I have two forms in my views, when I hit on save it's not working properly, when I want to display on my templates what I saved not showing as expected. Here's what I have: views.py def index(request): queryset = Personinfo.objects.all() queryset2 = Person.objects.all() qs = chain(queryset,queryset2) form = personform(request.POST or None) form2 = personinfoform(request.POST or None) context = { "queryset": queryset, "queryset2": queryset2, "qs": qs, "form2":form2, "form":form, } form2_valid = form2.is_valid() form_valid = form.is_valid() if form2_valid and form_valid: a = form2.save() b= form.save(commit=False) b.ForeignkeytoA = a b.save() return render(request, "index.html", context) index.html <form method="POST" action="">{% csrf_token %} {{form2.as_p}} {{form.as_p}} <input type="submit" value="Save!" /> </form> <table > <tr> <th>Name</th> <th>Address</th> <th>Number</th> <th>Hobbies</th> </tr> {% for item in qs %} <tr> <td>{{ item.name }}</td> #form2 <td>{{ item.address }}</td> #form1 <td>{{ item.phone_number }}</td> #form1 <td>{{ item.address }}</td> #form1 </tr> {% endfor %} </table> my output: As you can see my table isn't showing my items as expected. Is there a possible way to show every item in the same row? -
Celery task logging ERROR instead of INFO
I have a number of expected exceptions which should mark the task failed, but log them at INFO level instead of ERROR. According to the celery documentation: @shared_task(throws=(KeyError, HttpNotFound)): def get_foo(): something() Should log KeyError at INFO level. And it does. But if I do: @periodic_task def run_get_foo(): get_foo.delay() KeyError is logged as an actual error -
django-rest-auth authentication not working
I wanted a simple api authentication route using django-rest-framework and 'django-rest-auth`. The register part is working fine as confirmed by the default django admin console and i can also see the users. Unluckily the api authentication keeps on returning me with error { "non_field_errors": [ "Unable to log in with provided credentials." ] } Currently the configuration that i have for my allauth is as follows # all-auth configuration ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_AUTHENTICATION_METHOD="email" ACCOUNT_USERNAME_REQUIRED=False ACCOUNT_EMAIL_VERIFICATION="none" ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=False # CORS Configuration CORS_ORIGIN_ALLOW_ALL=True I am unsure what part i am missing. Please guide me on the right direction. There are no errors and the response code is 400. The credentials are correct as verified from django admin panel. Thanks in advance -
Django - store globally some values
I would like to store globally number of sites in my database. In my index view I have something like this: sites_inactive = Site.objects.filter(is_active=False) sites_all = Site.objects.all() context['sites_inactive'] = sites_inactive.count() context['sites_all'] = sites_all.count() I would like to have an access to these variables in my every view. Now I must repeat my code in every view. Is it possible to store these values and simply put it in my base.html file? I mean: Number of sites: {{ sites_all }} -
Django User model is good enough to be used in production
Is it good to use django custom user model if you want to create a website for production purposes with some tweaks using AbstractBase -
What type of field do I have to use in order to associate related parent object in serializer
I have two models with one to many relation. I will use the default example. class Album(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() The question I have is how do I implement serializer in order to associate a track with an album by providing only Album 'id' key. What I want is to know which type of serializers.Field do I have to declare is the serializer. Here is an example class TrackSerializer(serializers.Serializer): album = serializers.MagiclyRelatedFieldByUUID() # <---- ??? title = serializers.CharField() order = serializers.IntegerField() duration = serializers.IntegerField() class Meta: model = models.Track Request looks like this: { 'album': '137b5a6c-dd76-11e6-bf26-cec0c932ce01', 'title': 'my new track', 'duration': 10 'order': 31 } -
Django REST framework: Basic Auth without debug
Got a problem with Basic authentication in Django REST framework when debug mode is turned off. I am using Django 1.8.4 and Django REST Framework 3.2.2. Looks like it saves credentials for all computers with the same IP address when the first is logged in. But after some time it prompts for the username and password again. However, this problem does not occur when the debug mode in Django REST framework settings is set to True. I would like to have the same behaviour when debug is turned off. What is causing the problem? -
Django CRUD doesn't reloads the model
When I do a crud action to my database it won't change on the website after refreshing the page. I have to restart the server "python manage.py runserver" everytime to see the changes on my website. I asked another student about this problem and he said he didn't had the problem. I tried to find it on the internet but with no success. If you need any code of my project, please let me know. -
does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import
I got does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import error . I wrote in urls.py of child app from django.conf.urls import url from django.contrib.views import login,logout urlpatterns = [ url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout') ] in urls.py of parent app, from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), url(r'^api/', include('UserToken.urls')), url(r'^UserDataAPI/', include('UserDataAPI.urls', namespace='UserDataAPI')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am thinking urls.py of child or parent app,but I do not know how to fix it. What should I do? -
Manage Many-to-many relationships in Django
I have a question about Many-to-many relationships in Django. I need something like this: I have User model I have Locations model An User can add more Locations. I need to avoid duplicates in Locations so: If more Users add same location (i.e. New York) I would have a single Location NewYork in Locations Model. When an user will delete a Location I will delete also the corresponding element in Locations table only if the count of users, that they added the same location, is Zero (location is referred to none users) Does it exist a good way to handle this scenario? -
django: NoReverseMatch for the new object
Use Django 1.10.4. I have a model Stream, for which I created CreateView. When objects are created through the admin panel everything works fine, but when I use the form CreateView, an object is created (either in admin or in the database is no different from the other), but attempts to provide a link to it through DetailView result in an error: NoReverseMatch at / Reverse for 'detail_stream' with arguments '()' and keyword arguments '{'pk': 17}' not found. 2 pattern(s) tried: ['(?P[0-9])/$', 'streams/(?P[0-9])/$'] This error occurs when displaying the ListView, and then only for an object created through CreateView. The place where the error occurs: {% for item in stream_list %} <a href="/streams{% url "detail_stream" pk=item.id %}"> ... </a> {% endfor %} When you try to go directly to DetailView (http://127.0.0.1:8000/streams/17) 404 error. urls.py: from django.conf.urls import url from .views import StreamList, StreamDetail, StreamUpdate, StreamCreate, ChannelList, ChannelDetail, ChannelUpdate, ChannelCreate, autocomplete, search, filter, follow, follow_list, following_online urlpatterns = [ url(r'^$', StreamList.as_view(), name='streams'), url(r'^(?P<pk>[0-9])/$', StreamDetail.as_view(), name='detail_stream'), url(r'^(?P<pk>[0-9])/update/$', StreamUpdate.as_view()), url(r'^add/$', StreamCreate.as_view(), name='new_stream'), url(r'^channels/$', ChannelList.as_view()), url(r'^channel/(?P<pk>[0-9])/$', ChannelDetail.as_view(), name='detail_channel'), url(r'^channel/(?P<pk>[0-9])/update/$', ChannelUpdate.as_view()), url(r'^channels/add/$', ChannelCreate.as_view()), url(r'^autocomplete/$', autocomplete), url(r'^search/$', search), url(r'^search?limit=(?P<limit>[0-9])/$', search), url(r'^filter/$', filter), url(r'^follow/$', follow), url(r'^following/$', follow_list, name='following'), url(r'^following_online', following_online) ] Also, the url for the streams … -
Unable to edit Redis.conf file in ubuntu 16.04 LTE?
I installed Redis in Ubuntu 16.04 LTE and during configuration i have to edit redis.conf file, but unfortunately i could not be able to save the file, because file is having read-only access -rw-r--r-- 1 root root 46695 Jan 18 19:57 redis.conf I used chmod 777 redis.conf to get the access writes but it is not happening chmod: changing permissions of 'redis.conf': Operation not permitted Thanks in advance for your valuable solution -
__init__() got an unexpected keyword argument 'context' when calling with get in Django Rest Framework
I'm getting that error when I'm trying to get all objects. I wrote my model so: class Message(models.Model): created = models.DateTimeField(auto_now_add=True) type = models.CharField(_('type'), choices=MESSAGE_TYPE, default='Invitation', max_length=100) content = models.TextField(_('content'), blank=False) sender = models.ForeignKey(User, related_name='sender_message', verbose_name=_("Sender"), ) recipient = models.ForeignKey(User, related_name='receiver_message', null=True, blank=True, verbose_name=_("Recipient")) url_profile_image = models.URLField(_('url_profile_image'), max_length=500, blank=True, default='') class Meta: ordering = ('created',) My serializer: class MessageSerializer(serializers.HyperlinkedIdentityField): class Meta: model = Message fields = ('url', 'id', 'type', 'content', 'Sender', 'Recipient', 'url_profile_image') and my views: class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer I'm able to "create" those kind of messages in the django-admin. But I can't get them, whit the endpoint when they are created. This is the whole error: Internal Server Error: /users/messages/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/rest_framework/viewsets.py", line 83, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/rest_framework/mixins.py", line … -
SSO with Windows Integrated Authentication(Active Directory) using nginx web server and Django
I'm working on a Django project. We currently have a model backend for authentication. We need to include Single Sign On for users logging into a windows machine with a domain user (registered on Active Directory). This needs to be done without asking the user for a username/password again(since they are already logged into their windows machine with a domain account) and the users are going to be either using IE(11+) or Chrome I have read up on https://docs.djangoproject.com/en/1.8/howto/auth-remote-user/ But I don't understand how the webserver(nginx in this case) would authenticate. We need to authenticate using Kerberos. I find a lot of articles on the web related to this with Apache or IIS but barely anything for nginx. Switching web servers is not a feasible option for the project. nginx v1.8 django v1.8 -
how to access a python variable in java script
I have a python variable which returns json data ,i can access that data in html but my doubt is how we can pass that data to ajava script variable. I tried var json_data={{json_data}} var json_data={{json_data}} but nothiing work. Please hemp me guys. Thank You in advance