Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error using xadmin
This is my registered xadmin APP INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'courses', 'operation', 'organization', 'xadmin', 'crispy_forms' ] This is the urls from django.conf.urls import url from django.contrib import admin import xadmin urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^xadmin/', xadmin.site.urls), ] But I don't know what to do with this problem, I just started to learn django File "C:\Users\PC_LF\Envs\testvir2\lib\site-packages\xadmin\__init__.py", line 4, in <module> from xadmin.sites import AdminSite, site File "C:\Users\PC_LF\Envs\testvir2\lib\site-packages\xadmin\sites.py", line 3, in <module> from future.utils import iteritems ImportError: No module named 'future' -
Django 1.11 can't get static files to work locally
I know there are a ton of similar questions, but I can't get it to work with any of the other answers. My settings.py DEBUG = False STATIC_URL = '/static/' # This is /Users/marcuslind/Documents/Dev/Dev/Python/Hemmon/website/static STATIC_ROOT = str(ROOT_DIR('static')) STATICFILES_DIRS = ( str(APPS_DIR.path('static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) My urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^location/(?P<pk>\d+)/$', location_views.location, name='location'), url(r'^$', hemmon_views.index, name='index') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My folder structure . project/ templates/ static/test.txt manage.py I try to visit /static/test.txt and I get a 404 error. It fails to serve. What am I missing? I've done these type of settings a ton of times before but for some reason on this project I just can't get it working with Django 1.11. -
How to limit the actions of a user in django CBV
I've got a theoretical question. For example I've got 2 blogs of 2 users. When I'm logged in as a first user I can see posts of the second user, but not only see but also update them and delete them. The same holds true to the second user which can delete and update the posts of the first user. What should i do in django class base view so that the first user can only edit and delete his own posts but not the posts of other users. I've come across request.user == post.user check in function based view. But what are the solutions for class based views. Thank you. -
what is the best way tool or method to create login via my app using python django?
I am trying to create a website (python django) where the user can login to using another website (python django) similar to login via facebook or twitter.I will have a parent website where child websites can login via their credential on the parent site.i allready did research about Oauth but i could not find a well explained tutorial and i don't know if this is the right path to cross. -
GeoDjango: PostgreSQL not running migrations, object has no attribute 'geo_db_type
Django v1.11.5 I'm trying to install GeoDjango to play around with GoogleMaps. I installed PostgreSQL app for MAC and installed pip install psycopg2. I also used home-brew to install GDAL. Edited settings.py to add: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'djangodb', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } However, when I run python manage.py migrate I get: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' I created the user using:CREATE DATABASE djangodb OWNER admin; Full Error: Running migrations: Applying users.0011_location...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 254, in create_model definition, extra_params = self.column_sql(model, field) File "/Applications/Anaconda/anaconda/envs/DjangoEnv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 144, … -
How Set DateTimeField in django with postgres
i had in model DateTimeField and in postgres display 2017-08-18 00:00:00 i want to change it to 2017-08-18 models.py class sortiestk(models.Model): idsort=models.AutoField(primary_key=True) qtesrt = models.IntegerField(default=0) datesrt=models.DateTimeField(default=datetime.datetime.now,blank=True) ref=models.ForeignKey(Produit) codmag=models.ForeignKey(magasin) views.py @csrf_exempt def srti(request): if request.method == 'POST' : received_json_data=json.loads(request.body) refpr = received_json_data["srtfprod"] prod = Produit.objects.get(ref=refpr) qtepro = prod.qte qtesrt = int(received_json_data["qte"]) if qtepro < qtesrt : return JsonResponse ({'boo':True}) else : m = magasin.objects.get(codmag=received_json_data["refmag"]) s = sortiestk( qtesrt=qtesrt, datesrt = received_json_data["dat"], ref = prod , codmag = m ) p = Produit.objects.get(ref=refpr) p.qte = p.qte - qtesrt p.save() s.save() return redirect ('/ges/sortie/') when i display in template i get Sept. 19, 2017, midnight i just want display date not date with timezone -
Django URL reversing NoReverseMatch issue
I'm trying to use reverse to redirect a user to a login page from a third party App I'm using. The URL config has: urlpatterns = [ # authentication / association url(r'^login/(?P<backend>[^/]+){0}$'.format(extra), views.auth, name='begin'), How can I accomplish this? I've tried return redirect(reverse('social:login'), args=('facebook',)) and return redirect(reverse('social:login'), kwargs={'backend':fb}) (to get to /login/facebook) but I'm getting a NoReverseMatch The Django URL system and RegExes are confusing me a bit =( -
Fat models - oparations on database in models or in views?
I heard that fat models are good idea and I should avoid operations on database in my views so I do something like this below. Can you tell me if it's good idea and which version is better? views.py class CandidateCreateProfileView(AnonymousRequiredMixin, FormView): form_class = CandidateCreateProfileForm template_name = 'users/candidate_create_profile.html' success_url = reverse_lazy('account_login') def dispatch(self, request, *args, **kwargs): activation_key = self.kwargs['activation_key'] self.user = get_object_or_404(User, activation_key=activation_key) if self.user.key_expires < timezone.now(): return render_to_response('users/candidate_confirm_expired.html') if self.user.is_active: return HttpResponseRedirect(reverse_lazy('account_login')) return super(CandidateCreateProfileView, self).dispatch( request, *args, **kwargs) def get_initial(self): initial = super(CandidateCreateProfileView, self).get_initial() initial['name'] = self.user.name initial['mobile_phone'] = self.user.mobile_phone return initial def form_valid(self, form): self.user.name = form.cleaned_data['name'] self.user.mobile_phone = form.cleaned_data['mobile_phone'] self.user.notification_type = form.cleaned_data['notification_type'] self.user.set_password(form.cleaned_data['password']) self.user.is_active = True self.user.save() return super(CandidateCreateProfileView, self).form_valid(form) vs. models.py class User(models.Model): name = models.CharField(max_length=50) ... def create_candidate_profile(self, name, mobile_phone, notification_type, password): self.name = name self.mobile_phone= mobile_phone self.notification_type=notification_type self.set_password(password) self.is_active = True self.save() and then in my CandidateCreateProfileView view: def form_valid(self, form): self.user.create_candidate_profile( name = self.cleaned_data['name'], mobile_phone = self.cleaned_data['mobile_phone'], notification_type = self.cleaned_data['notification_type'], password = self.cleaned_data['password'] ) return super(CandidateCreateProfileView, self).form_valid(form) -
Django ModelFormset Validation Error
I'm getting a Validation Error: ['ManagementForm data is missing or has been tampered with'] When attempting to submit a modelformset form, however I cannot seem to work out why this is occuring. Code: --views.py def formset_view(request): context = RequestContext(request) EmpFormSet = modelformset_factory(Employee,form=UpdateForm,extra = 0) if request.method == 'POST': formset = EmpFormSet(request.POST, queryset = Employee.objects.filter(companyid__company_user__id = request.user.id, prefix='formsettest') if formset.is_valid(): for form in formset.forms: if form.is_valid(): form.save() redirect('/home/') else: formset = EmpFormSet(queryset = Employee.objects.filter(companyid__company_user__id = request.user.id, prefix = 'form2') return render(request, 'emp_update_list.html', {'formset': formset}) Template: <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.as_table }} <button type="submit" name="action" value="Submit">Submit</button> </form> -- forms.py class UpdateForm(ModelForm): class Meta: model = Employee fields=('empid','forename','surname') As you can see, I have the management form in my template so not sure what is causing this error. It only happens when I attempt to submit the formset. The error seems to occur on the line in views - if formset.is_valid(): -
NameError: account not defined
I'm trying to create a simple registration form using django1.11.5 I created a project called mysite using the command: django-admin.py startproject mysite . And I have created an app called account using the code: python manage.py startapp account In the urls.py file of the folder mysite I specified the urlto be accessed as follows: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^account/',include(account.urls)), url(r'^admin/', admin.site.urls), ] However when I'm trying to migrate or runserver I'm getting the following error. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000273BFBDFC80> Traceback (most recent call last): File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 398, … -
django filter comparison by version string
I have a Django model like the following: class MyModel(models.Model): verion = models.CharField() with the following objects: obj1: version = '9.0.1' obj1: version = '9.2' obj1: version = '9.2.3' obj1: version = '10.0' I want to do the following filter MyModel.objects.filter(version__gte='9.2.3') What is the best way to approach this? Im using Django 1.8 -
Can't redirect to another view/url
I have django app (1.8) and I want to have redirection from BookingRedirect to ArchiveListView after click link below: <a href="{% url 'archive:list' %}" title="{% trans 'Archive' %}"> {% trans 'Archive' %} </a> I recived this error: Reverse for 'archives' with arguments '()' and keyword arguments '{'kwargs': {'year': '2014', 'month': '1'}}' not found. 1 pattern(s) tried: ['en/archive/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$'] My view where I want to have redirect to another url with another view: from django.shortcuts import redirect class BookingRedirect(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): return redirect('archive:archives', kwargs={'year': '2014', 'month': '1'}) urls: urlpatterns = [ url('^$', views.BookingRedirect.as_view(), name="list"), url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$', views.ArchiveListView.as_view(), name="archives"), ] -
django how to add image in JSONfield?
I want to add an image in JSONfield. Here is my json data:` {"name": "some name", "image": "static 'ontheway/images/m1.jpg'", "overview": "some data"}, {"name": "some name", "image": "static 'ontheway/images/a1.jpg", "overview": "some data"}] In template I have done something like this : {% for data in place.places_to_visit %} {% for key, value in data.items %} {% if key == 'image' %} <img src="{{ value }}"> {% else %} <div> {{ key }}:{{ value }} </div> {% endif %} {% endfor %} {% endfor %} The images are not getting displayed instead its path is displayed. I have stored images in static files, do I need to store images in media? Thank you in advance -
Django ORM - ForeignKey with 3 models involved
I have the following models: class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A) c = models.ForeignKey(C, null=True, blank=True) class C(models.Model): ... I would like to get all A's that have any B, that have any C = null. I have tried doing A.objects.filter(b__c__isnull=True) but that isn't fetching the correct results apparently. Am I missing something? -
Django Search Form
I need help with Django search. I am doing this with .filter(). In short this code does not work and i need to redirect user to new page (result.html) where should be appear results. Guys please help. I am just new in django. filters.py from .models import News import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = News fields = ['news_title', 'news_text',] view.py from . models import News from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.shortcuts import render, redirect from django.contrib.auth import login,authenticate from .filters import UserFilter def search(request): news_list = News.objects.all() news_filter = UserFilter(request.GET, queryset=news_list) return render(request,'news.html', {'filter': news_filter}) template:news.html <div class="search-area-area"> <form method="get"> {{ filter.form.as_p }} <input type="text" name="search" id="search-area" placeholder="Lets search" maxlength="20" autocomplete="off"> <button class="all" type="submit"> </button> </form> </div> Results of search should be here: result.html <section class="pull-right" style="margin: 0 14px 30px 0;"> {% for news in filter.qs %} <h2>{{ news.news_title }}</h2> <p>{{ news.news_text }}</p> {% endfor %} </section> models.py class News(models.Model): news_title = models.CharField(max_length=255) news_text = models.TextField(max_length=5000) -
Is it possible to run Horizon server on Windows?
I'm using windows as my development machine. Recently we are developing some features on OpenStack Horizon. Which means we need to checkout horizon source code from github: https://github.com/openstack/horizon Then I tried to follow the document to start horizon Django service on Windows. But it failed. But on Linux(Ubuntu virtual machine) it works fine. Does anyone ever been able to start Horizon Django server on windows? -
Django Forms - how to check in __INIT__ method whether request.POST was provided
After two years of experience with Django forms, I ran into the following dilemma related to __init__ method: I have a Django form definition as follows: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(MyForm, self).__init__(*args, **kwargs) if not MyModel.objects.filter(user = self.user).exists(): self.fields['field_1'].widget = forms.HiddenInput() self.fields['field_2'].widget.attrs['placeholder'] = 'Enter value' This code is ok if I initialize the form like this: my_form = MyForm() However, the problem arises when I try to save user input in the following way: my_form = MyForm(request.POST) My point is that I do not want to waste code execution time for setting placeholder property or deciding upon whether some field should be hidden or not AFTER the user has already submitted form. My concern is that maybe that's because I misuse __init__ method? Is there any way to check whether request.POST parameter has been provided? And if yes, is it considered best-practice to perform this check and do thinks like settings placeholder, initial values, etc. only if request.POST is not provided? -
python data search and data bind algorithm
i have following data in following formate {u'partno': u'0191124M01', u'partdescription': u'SHIELD BEARING (5 DOT)', u'Vendor': u'AA1231'} {u'partno': u'0191124M01', u'partdescription': u'SHIELD BEARING (5 DOT)', u'Vendor': u'AA1232'} {u'partno': u'0191124M01', u'partdescription': u'SHIELD BEARING (5 DOT)', u'Vendor': u'AA1233} {u'partno': u'0390734X01', u'partdescription': u'PLAIN WASHER M10', u'Vendor': u'AA1263'} {u'partno': u'0390734X01', u'partdescription': u'PLAIN WASHER M10', u'Vendor': u'AA1264'} {u'partno': u'0390734X01', u'partdescription': u'PLAIN WASHER M10', u'Vendor': u'AA1265'} {u'partno': u'1442864X01', u'partdescription': u'SPLIT PIN', u'Vendor': u'AA1263'} {u'partno': u'1442864X01', u'partdescription': u'SPLIT PIN', u'Vendor': u'AA1264'} {u'partno': u'1442864X01', u'partdescription': u'SPLIT PIN', u'Vendor': u'AA1265'} i need to bind data in following formate using above sample: {'partno':1442864X01,'partdescription':'SPLIT PIN','Vendor':[AA1263,AA1264,AA1265]}, {u'partno': u'0191124M01', u'partdescription': u'SHIELD BEARING (5 DOT)', u'Vendor': [u'AA1231',u'AA1232',u'AA1233']} {u'partno': u'0390734X01', u'partdescription': u'PLAIN WASHER M10', u'Vendor': [u'AA1263',u'AA1264',u'AA1265']} how i can do this please help me . -
Django in runfcgi mode application on windows
I can not understand why project doesn't start. I copy all project files to my computer. It situated in c:\python27\scripts.... I copied all data to my disk (c:\python27\scripts...). Try to run application(such command successful run application on server ): C:>c:\Python27\Scripts\project\Scripts\python.exe c:\Python27\Scripts\project\tender\manage.py runfcgi method=threaded host=127.0.0.1 port=8000 and... nothing. App not started, don't print any messages, and don't show next command line. it's hanging. Try to check: C:>c:\Python27\Scripts\tenderproject\Scripts\python.exe c:\Python27\Scripts\project\tender\manage.py check System check identified no issues (0 silenced). Variables: C:>set U USERDOMAIN=letnab USERDOMAIN_ROAMINGPROFILE=letnab USERNAME=Skif USERPROFILE=C:\Users\Skif C:>set C CommonProgramFiles=C:\Program Files\Common Files CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files CommonProgramW6432=C:\Program Files\Common Files COMPUTERNAME=LETNAB ComSpec=C:\Windows\system32\cmd.exe C_EM64T_REDIST11=C:\Program Files (x86)\Common Files\Intel\Shared Files\cpp\ C:> dbshell work fine. I can manipulate tables. I can not understand what need application yet. Can you help me run application? -
Python not working on Live server
When I am running python project on live server then I am getting so many problem mail problem is: This is running in cmd : System check identified no issues (0 silenced). September 06, 2017 - 10:38:39 Django version 1.9.9, using settings 'app_baxter_com.settings' Starting development server at http://38.99.188.187:8000/ Quit the server with CONTROL-C. But When I am checking in browser then its not working . I am getting this error 404 Not Found nginx/1.10.2 -
How to put html code into template in Django
Trying to send to template html code from another html file. The view code looks like: def homepage( request ): return render(request, 'homepage.html', { 'table': generateTable(), }) def generateTable(): x = render_to_response( 'tableSchema.html' ) return x And in a template: {{ table|safe }} Everything is okay, but I see an information about UTF8 above the table : I mean the table is generating correctly ,but above is the following text: Content-Type: text/html; charset=utf-8 Do you know why and how to remove it ? Thanks in advance, -
Django : Iterating over data
I am having a variable cc in which I getting data from session: cc = request.session['cc_list'] and the data is in this format : [ {"model": "InBound.challengecode", "pk": 1, "fields": {"challenge_code": 50, "sve_challenge_text": "Good"}}, {"model": "InBound.challengecode", "pk": 2, "fields": {"challenge_code": 48, "sve_challenge_text": "Voter Not Signed"}} ] Now I want to know how to iterate over it and get values of challenge_code and sve_challenge_text as whenever I iterate over its starts iterating by characters like '[', '{', '"'...... Thanks in advance -
I want to customizing django.contrib.auth.views.login form
I have a template and css with it. <form class="form"> <input type="text" placeholder="Username"> <input type="password" placeholder="Password"> <button type="submit" value="Login" id="login-button">Login</button> </form> I know that I have to add {{ form.username }} and {{ form.password }} but How can I add a placeholder to fields? -
Django _get_pk_val() returns None while pk exists
I use Python, Django, djongo and MongoDB. I've created a simple model and want to save and delete documents from my webpage. I manage to save them (checked in DB) with _id being ObjectID type. But when I try to delete them I have AssertionError (object can't be deleted because its id attribute is set to None). For document d I've printed pk by d.pk and got a correct value, but when I run d._get_pk_val() output is None. Do you know how to let Django know the primary key? I've tried to assign pk in the model by _id = models.AutoField(primary_key=True) but then _id is still of an ObjectID type, but delete() expect it to be int() and fail with an error (int() argument must be a string or a number, not ObjectID). My model: class DevList(models.Model): dev_num = models.CharField(max_length = 200) dev_name = models.CharField(max_length = 200) dev_descr = models.CharField(max_length = 200) dev_type = models.CharField(max_length = 200) And my views use simple d.save() and d.delete() functions. Thank you! -
ModuleNotFoundError: No module named 'import_export'
I've used the following tutorial. I used the command pip install django-import-export, then added to the Installed Apps section. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'import_export', 'frontend', 'userauth', 'methods', ] When I run python manage.py collectstatic I get error ModuleNotFoundError: No module named 'import_export'