Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect after login based on user-type
I am a newbie to Django. The project I am working on has a requirement that I am stating below. There will be many users. Each user will belong to a particular group (for this case let us assume that the groups are X,Y,Z). Also, each user group will have a url associated with it. What I want is, whenever a user accesses the sytem, the Django-admin-authentication-system must check the group of the user and according to the user group, the user must be re-directed to a url that is pre-defined for the particular user group. For example if user belonging to group X accesses the system, the user will be redirected to a url abc.xys.df. How can I achieve this using Django-admin? -
Django custom user model issue
I am trying to customize user model (name: UserProfile) but when I did makemigrations I got an error: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.UserProfile' so I follow the suggestion from (Manager isn't available; User has been swapped for 'pet.Person') and made some changes. I put from django.contrib.auth import get_user_model User = get_user_model() in every files which custom user model imported (settings, serializers, model, forms, admin) but this time I got another error message: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. How can I fix this problem? Here are files: settings.py > import os import datetime from django.conf import settings > > > # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = > os.path.dirname(os.path.dirname(os.path.abspath(__file__))) > > > # Quick-start development settings - unsuitable for production > # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ > > # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ruho^096p16m=vg!sn(&o46-qwe#y(zf^bee&!wujo-4h@%hgl' > > # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True > > ALLOWED_HOSTS = ['*'] > > > # Application definition INSTALLED_APPS = [ > 'rest_framework', # Django rest framework 套件 > 'rest_framework.authtoken', > 'grappelli', # grappelli admin 版面套件 > 'django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', … -
Why m I getting this error in django urls?
I am very new to Django and still trying to understand most things. l am currently working on a project where I need to add a details page for each link. But I am getting the following error. Error: NoReverseMatch at /discover/ Reverse for 'disc-details' with arguments '('',)' not found. 1 pattern(s) tried: ['discover/(?P<discover_id>[0-9]+)/'] Following is my urls patterns for app: url(r'discover/$', views.discover, name = 'discover'), url(r'discover/(?P<discover_id>[0-9]+)/', views.disc_details, name = 'disc-details'), and my views.py look something like: def discover(request): disc = Discover.objects.all() return render(request, 'main/discover.html', {'disc': disc}) def disc_details(request, discover_id): dis = get_object_or_404(Discover, pk = discover_id) det = Discover.objects.get(pk = discover_id) return render(request, 'main/discDetails.html', {'det': det, 'dis': dis}) Whats happening here is discover is a html page containing various links and each link should have its on disc_details section. My html section has the following: <a class="btn btn-success" href='{% url 'main:disc-details' dis.id%}' class = "detail-link">Details</a> Help me fix this and please provide an explanation. -
Django Base url Redirection for API
i am new to Django Python and working on redirection of Apis I am Having issues in Redirection. For ex : www.example.com which is working now and the second server is www.api.example.com in which i have to redirect all the apis from www.example.com to www.api.example.com and /apis are all the apis which is will remain the same for api hits. url(r'^$', RedirectView.as_view(permanent = False, url='https://api.example.com/'), name='static_data'), It redirects to the url but the parameters does not pass. -
good way to write thread safe middleware in django
I want apply required filtering for almost all models, all queries in quite big django application. Actually I am looking for a right way to implement a "query-set driven" middleware (instead of standard "request-driven middleware") but without manipulate any db driver (no patching, wrapping, etc). Idea is to use one common mixin for QuerySets and Managers, to see this method always available: AnyModel.objects.filter_by_organization() without need to pass a parameter there. and later: AnyModel.org_objects doing filter_by_organization() own self my main concern is about thread safety. could you review my approach below? this_thread = threading.local() ... standard django middleware: class OrganizationMiddleware(object): def process_request(self, request): this_thread.request = request ... ... mixin/manager: class OrganizationQuerySet(models.QuerySet): def _get_current_request(self): return getattr(this_thread, "request", None) def filter_by_organization(self): request = self._get_current_request() org_id = getattr(request.user, 'organization_id', None) return self.filter(...filtering by org_id + extra logic...) # keeping this in one place has additional benefits ... in models: org_objects = OrganizationQuerySet.as_manager() ... then using above without a need to pass request -
Django formset rendering
I'm trying to render a particular field in each form where each pair of fields should appear in a single row. <form method="post" action="settings/developer" id="ipwhitelist-form">{% csrf_token %} <input type="hidden" name="action" value="whitelistips"> <input type="hidden" name="apikey" value="{{apikey}}"> {{ formset.management_form }} <div class="row"> <div class="col-lg-6"> {{ formset.0.id }} {% bootstrap_field formset.0.ip_range placeholder="0.0.0.0/0" addon_after='<span class="glyphicon glyphicon-remove"></span>' %} </div> <div class="col-lg-6"> {{ formset.1.id }} {% bootstrap_field formset.1.ip_range placeholder="0.0.0.0/0" addon_after='<span class="glyphicon glyphicon-remove"></span>' %} </div> </div> <div class="row"> <div class="col-lg-6"> {{ formset.2.id }} {% bootstrap_field formset.2.ip_range placeholder="0.0.0.0/0" addon_after='<span class="glyphicon glyphicon-remove"></span>' %} </div> <div class="col-lg-6"> {{ formset.3.id }} {% bootstrap_field formset.3.ip_range placeholder="0.0.0.0/0" addon_after='<span class="glyphicon glyphicon-remove"></span>' %} </div> </div> <!-- 10 more fieldsto come --> </form> In the above, I just hard-coded the form number and accessed it through formset.form-num . What I want is to do iterate over forms instead of hardcoding it.. Note that I want only one field from each form to get rendered... -
id auto field error when saved in serializer
I will paste only the necessary code of my issue. I have the following model: class Event(models.Model): id = models.AutoField(primary_key=True) Serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'name') @transaction.atomic def create(self, validated_data): print("before") print(validated_data) event = Event.objects.create(**validated_data) print("after") return event I get on line event = Event.objects.create(**validated_data) the following error null value in column "id" violates not-null constraint . When i print the validated data it does not includes any id. How do i solve my issue ? -
FastCGI process has failed frequently, getting while deploying the Django application on windows 2012 server using IIS
I am trying to deploy Django application on Windows 2012 server using IIS. my web.config file : <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Django Handler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\chinmay_arima\env_resolution\Scripts\python.exe|C:\Users\chinmay_arima\env_resolution\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </configuration> Getting "HTTP Error 500 - Internal server error". Please find the attachment to see the error. I am following the below to link : http://blog.mattwoodward.com/2016/07/running-django-application-on-windows.html Please help me out , I need to deploy the Django application on windows using IIS server. -
Nginx Pagespeed module not working properly
I'm using the Pagespeed module on Nginx with the configuration of Google's page: pagespeed on; # Needs to exist and be writable by nginx. Use tmpfs for best performance. pagespeed FileCachePath /var/ngx_pagespeed_cache; # Ensure requests for pagespeed optimized resources go to the pagespeed handler # and no extraneous headers get set. location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; } location ~ "^/pagespeed_static/" { } location ~ "^/ngx_pagespeed_beacon$" { } I'm using uwsgi as a server for a django application. Pagespeed does not write well the urls of some images like those of leaflet map library: https://example.com/static/css/images/xmarker-icon.png.pagespeed.ic.is6gszlWFp.webp%22)marker-icon.png when it should be https://example.com/static/css/images/xmarker-icon.png.pagespeed.ic.is6gszlWFp.webp Another big problem is that I have a JS Script with declared constants and they import themselves well but when they are called it says that the constants do not exist... -
How to use Django Rest API for Video streaming Android application?
I am building an application that uploads and stores user generated video content and that content is accessible to few people in his network. I am writing a Django based REST api for the same. I have exploring how to stream video content in an Android application and find out about the Exoplayer. But it asks for a url of video file to run. I don't want to make the url public(that can be accessed by anyone if he knows the url), rather I want to authenticate the user first and check if he has access or not and then only make person stream that video. So, I have been searching a lot but couldn't find how to input a get request in Exoplayer or any media player on android. Can someone please help me point towards the documentation for the same. Basically, I will be working in Django to get the desired video file. Also, is there something different I will have to do from Server side to handle this issue. Thanks in advance. -
Django: Save New Inline Formset Based on Existing One
I have a use case where a user can either update an existing inline formset or save it as a new one (which may or may not have been edited). When saving a new one, the original needs to be kept so that you are left with 2 inline formsets. The difficulty I am having is saving the new formset from an existing one. I cannot get the new parent model to link to the child models. I suspect that it has something to do with the formset id's (eg: my_formset-0-id) which (from what I understand) are only present when editing a fomset. And so, when I try to save the new formset, it's expecting an update because the id's are present. I was thinking that one solution would be to remove the id's fields of the formset when it comes in as editing, but this seems a bit hackish. views.py def pivot_report_post_modal(request, report_type=None, report_id=None): """View for a POST that creates a new pivot report view or edits an existing one """ if report_type: # new pivot_report = get_object_or_404(PivotReport, identifier=report_type) report_view = PivotReportView(pivot_report=pivot_report, default=False, client=request.user.client) elif report_id: # edit report_view = get_object_or_404(PivotReportView, id=report_id, client=request.user.client) pivot_report = report_view.pivot_report report_type = pivot_report.identifier … -
Django Store a value of selected dropdown item in database
I want to store the value of selected dropdown item and store it in database.I am unable to understand how to do this. Here is my dropdown list -
Django invalidate previous unexpired reset password tokens?
If user send multiple password reset token, then How to invalidate previous unexpired tokens? -
Transfer Objects from another App into a ChoiceField
I've made a Choice Field for HTML File with th MY_CHOICES = ( ('0', 'Johnny B. Goode'), ('1', 'Lightning McQueen'), ('2', 'Iron Man'), ) def get_student(): student_data = MY_CHOICES student_list = student_data return student_list def get_my_students(): student_list = get_student() choices_list = student_list return choices_list class studentForm(forms.Form): def __init__(self, *args, **kwargs): super(studentForm, self).__init__(*args, **kwargs) self.fields['my_students_field'] = forms.ChoiceField(choices=get_my_students()) def get_data(request): form = studentForm() if form: print('form') return render_to_response('bills/generator.html',{'form': form}) else: return print('no Form') My problem now is, that MY_CHOICES is a normal Tuplet with some arguments that are shown up in my view. As next step I want to take Objects form my App "Students" (first_name + last_name) with this class: class Student(models.Model): first_name = models.CharField(_(u'Vorname'),max_length=30) last_name = models.CharField(_(u'Nachname'),max_length=30) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) postal_code = models.CharField(_(u'Postleitzahl'),max_length=30) city = models.CharField(_(u'Ort'),max_length=30) def __str__(self): return "%s %s" % (self.first_name, self.last_name) So I'm searching for a kind of strategic way, how to solve that problem. Hopefully someone can give me a hint. -
Django Sqlite3 creating a database on a specific path
I have a django project which creates a sqlite3 database at the end. It automatically creates the database on my project folder, but I want it to be created on a specific path/directory. I tried to write the full path instead of report.sqlite3 in this line: conn = sqlite3.connect(reportname.sqlite3) No luck. How can I change where my sqlite3 file is created? -
override model field choices option does not pass validation
in Django 1.11: I have a model field declared like that: a = models.CharField(choices= (('a','a'),('b','b')) In a ModelForm I try to override these choices: class ModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['a'].choices = [('a', 'a'), ('b', 'b'), ('d', 'd')] The form is rendered correctly (the option 'd' is added), but when submitted a form return an error Select a valid choice. d is not one of the available choices. Whatever I do, nothing works. What am I doing wrong? -
AttributeError: module 'django.db.models' has no attribute 'DataTimeField'
I'm trying to make my first project on Django and here is the code for the project file(~blog/model.py). from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey("auth.User",on_delete=models.CASCADE) title = models.CharField(max_length = 200) text = models.TextField() created_date = models.DataTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title python manage.py makemigrations blog (Written on Terminal) File "/Users/makotonakai/djangogirls/blog/models.py", line 11, in Post created_date = models.DataTimeField(default=timezone.now) AttributeError: module 'django.db.models' has no attribute 'DataTimeField' How can I remove this error? I would appreciate if you give me any ideas to solve this problem. -
I want to make two queryset search in Django
Using django.Filter() to search or filter the details of posts already saved in django. Using Q of django to make search in queryset. using checkbox, so that this filter(), to add a filter in my webpage when -- /?q=Bangalore Im getting correct value as Search posts LOCATION BANGALORE PUNE ujjwal 56789 hgjk@hgjhk.vds bottle bisleri bangalore Sept. 20, 2018, 3 p.m. but when I am selecting both of the checkbox and perform search >> ?q=Bangalore&q=Pune if you notice the above url , it is performing '&' (and) opertion and, rather i want to show in search, the data of either of the value. Suppose, in database only, Bangalore is saved but not pune or vice-versa. It is showing nothing . .. my code >>if query: >> queryset = queryset.filter( >> Q(Name__icontains = query) | >> Q(Location__icontains= query) ) Hope I am able to make you understand my situation.. -
Django image placement
this is how I want to display the pictures this is how it is displayed <div class="container" style="background-color: white; border-color: white;"> <img class="mx-auto thumbnail" src=" {% static 'mike/Anon.png' %} " width = 25 > <p > Hi how are you </p> </div> <div class="container" style="background-color: white; border-color: white;"> <img class="mx-auto thumbnail" src=" {% static 'mike/Anon.png' %} " width = 25 class="right"> <p class="float-right">Hey! I'm fine. Thanks for asking!</p> </div> It works in normal HTML but not with Django. Please Help. -
How to include DRF 3.8 router url patterns in Django 2.1
from app_listing import views from django.urls import path, include from rest_framework import routers router = routers.DefaultRouter() router.register(r'category', views.CategoryViewSet) urlpatterns = [ path('api/', include('router.urls')) ] urlpatterns += router.urls Here is the error while trying to include router.urls ,ModuleNotFoundError: No module named 'router'. I am using Django2.1,DRF 3.8.2 and python 3.6. Tried a lot, but couldn't find a proper solution for this. Is this still an open issue ? Please help!. -
Django Showing errror like "Import Error No module named radis"
!/usr/bin/env python import os import sys if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "queuearoo.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I am Accesing this from remote server using puTTY and getting the errors like the following Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/init.py", line 308, in execute settings.INSTALLED_APPS File "/home/devbase/env/local/lib/python2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/home/devbase/env/local/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/devbase/env/local/lib/python2.7/site-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/devbase/devbase/queuearoo/queuearoo/settings.py", line 2, in import os,redis ImportError: No module named redis -
Django for Industrial application
I have written a project with django for an industrial machine which sends some commands to arduino and also controls some processes. Since the main purpose of django is not for such a use, I had a lot of trouble in my way. Just now I have actually finished the project, I'm a little worried, since I haven't found a good way for encrypting my codes and also I think django was not a good choice. Am I right? If so can anyone tell me a substitution? -
Foreign key value is returning as an object instead of id in datatables in django
when i try to get the data from the datbase im getting foreign key value as object instead of value. in Models.py class UP_ROLE_MENU_MAP(models.Model): iRMID = models.AutoField(primary_key=True) iRoleID = models.ForeignKey(UP_ROLE_MASTER,on_delete=models.CASCADE,default='',db_column='iRoleID') iMenuID = models.ForeignKey(up_menus,on_delete=models.CASCADE,default='',db_column='iMenuID') iStatus = models.PositiveSmallIntegerField(default=1, blank=True,null=True) In Views for DataTables class OrderListJson(BaseDatatableView): model = UP_ROLE_MENU_MAP columns = ['iMenuID', 'iDeleteAccess','iAddAccess','iViewAccess'] order_columns = ['iMenuID', 'iDeleteAccess','iAddAccess','iViewAccess'] max_display_length = 10 def render_column(self, row, column): if column == 'iViewAccess': return ... else: return super(OrderListJson, self).render_column(row, column) output: ["up_menus object (3)", "0", "1", "link"] How can i get the value instead of object. -
How to import a .csv table with a foreign key into a django database
This is my first Django project and I am having difficulty loading data from a .csv file into a model with a foreign key. Here are my models: class Artist(models.Model): artistID = models.IntegerField(primary_key=True, null=False, unique=True) artistName = models.CharField(max_length=50) artistNotes = models.TextField(blank=True) class Art(models.Model): artID = models.IntegerField(primary_key=True, null=False, unique=True) artistID = models.ForeignKey(Artist, db_column='artistID', on_delete=models.CASCADE, default = 1) title = models.CharField(max_length=100, default = "No Title Given") location = models.CharField(max_length=100) owner = models.CharField(max_length=50, blank=True) origin = models.CharField(max_length=150, blank=True) medium = models.CharField(max_length=50, blank=True) artNotes = models.TextField(blank=True) I wrote a view that would import the data: def importArt(request): myFile = open('misc/Art.csv', 'r') for line in myFile: line = line.split(',') temp = Art.objects.create() temp.artID = line[0] temp.artistID = line[1] temp.title = line[2] temp.location = line[3] temp.owner = line[4] temp.origin = line[5] temp.medium = line[6] temp.artNotes = line[7] temp.save() myFile.close() return render(request, 'dtccArt/importArt.html', {}) This strategy worked fine for the Artist table but this is the error that I am getting: Cannot assign "'2'": "Art.artistID" must be a "Artist" instance. My first line of data looks like this: 1,2,Wisdom & Knowledge,Main Library,College,Visiting Artist at DTCC 19??-19??,Stone Sculpture,, I fixed two errors before getting to this stuck point. I added db_column='artistID' and default = 1 to the Art … -
Cannot obtain user by using filter with username and password
I am using the following code email = validated_data["login"] password = validated_data["password"] user_obj = User.objects.filter(Q(email__exact=email) & Q(password__exact=password)) I changed the password from admin however no user is returned. However if I remove the password check then I get a user object back.The object that I get back if I remove the Q(password__exact=password) condition has _password field as None. This code has been working fine for a while but today it is not returning back the object. Am I missing something here ? I verifies that I am receiving the correct username and password from the client.