Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
password authentication in django returning false
Jwt broken, tried to do it manually but it keeps returning false In [2]: me = User.objects.all()[1] In [3]: me.password Out[3]: 'password' In [4]: me.username Out[4]: 'cchilders' In [5]: me.email Out[5]: 'cchilders' In [9]: me.check_password('password') Out[9]: False -
Save a form with Django from a view
I need to save a form with Django from my views. I'm geting data from an API and need to save direct on my database: form = NewSubject() #API request form.owner = request.user #Another fields form.teacher = teacher form.group = request.user.group form.save() But I get: Exception Value: NOT NULL constraint failed: subjects_subject.owner_id So I tried by another way: form = NewSubject() #API request subject = form.save(commit=False) subject.owner = request.user #Another fields subject.teacher = teacher subject.group = request.user.group form.save() Now, the form is saved, but I allways get the error: Exception Value: 'NewSubject' object has no attribute 'cleaned_data' -
ImportError: No module named 'posts.urls'
I am new to Django and started making my first Django app using django official tutorial from https://docs.djangoproject.com/en/2.0/intro/tutorial01/. I have installed python3.5.2 and pip 9.0.1, using Ubuntu 16.04, Django version is 2.0. my urls.py file has following code from django.contrib import admin from django.urls import path from django.conf.urls import url, include urlpatterns = [ path('posts/', include('posts.urls')), path('admin/', admin.site.urls), ] If there is anything you can help me work this out. below is the error i am getting after running command - python manage.py runserver here is the error i am getting Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fe20fe92d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = … -
CRUD Operation in Python Django REST
I am trying to implement simple CRUD operation in Django Rest. I have successfully created, GET and POST . Now, I want to update the row data with PUT and delete a row with DELETE. Currently, my table looks like :- id item_1 item_2 item_3 date_created date_modified 1 test1 test2 test3 16-12-2017 16-12-2017 2 ex1 ex2 ex3 16-12-2017 16-12-2017 API End point :- localhost/itemlist If we GET localhost/itemlist it returns the list of items. If we POST localhost/itemlist with fields item_1, item_2, item_3 , it creates the row. Now, I want to use PUT to update a particular row. Like, if I want to update the value of item_3 where item_1 == "test1" DELETE should delete the row where item_1 == ex1 urls.py from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from .views import ItemView urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="create"), } urlpatterns = format_suffix_patterns(urlpatterns) views.py : from rest_framework import generics from .serializers import itemlistSerializer from .models import itemlist class ItemView(generics.ListCreateAPIView): queryset = itemlist.objects.all() serializer_class = itemlistSerializer def perform_create(self, serializer): serializer.save() serializers.py from rest_framework import serializers from .models import itemlist class itemlistSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model = itemlist fields = … -
How is a Python class successfully imported from a seemingly wrong module path?
The following line from the official documentation of the Graphene Django Integration works just fine: from graphene_django import DjangoObjectType Yet, the class DjangoObjectType is defined in graphene_django.types, as the project's source code may show. Moreover, running the following after the above from import inspect print(inspect.getmodule(DjangoObjectType)) yields this output: <module 'graphene_django.types' from '<myVirtualEnv>/lib/site-packages/graphene_django/types.py'> How is this possible? -
In certain cases(when copying text from word) when creating an object I get a Key error
I have a blog site with a form for creating and updating posts. For certain content, when I copy/paste from a word document into the form for creating/editing I get a key error. It doesn't happen for text that is directly written into the form and it doesn't always happen for text that is copied from Microsoft word. I am completely flummoxed about this. Any help would be much appreciated. here is bpaste with the relevant code: https://bpaste.net/show/51c4aa8d7834 -
Configuring 2 Form Views to a URL - django
I have two different FormView classes, and I'm trying to link them to corresponding url patterns as shown below. My urls.py contains: urlpatterns= [ #pattern: /nutrients/ url(r'^main/$', views.MainView.as_view(), name='main'), url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'^profile/$', views.ProfileFormView.as_view(), name='profile') ] The FormView classes are: class MainView(TemplateView): template_name = 'profile.html' def get(self, request, *args, **kwargs): user_form = UserForm(self.request.GET or None) profile_form = ProfileForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['profile_form'] = profile_form context['user_form'] = user_form return self.render_to_response(context) class UserFormView(FormView): form_class = UserForm template_name = 'profile.html' success_url = '/' def post(self, request, *args, **kwargs): user_form = self.form_class(request.POST) profile_form = ProfileForm() if user_form.is_valid(): user_form.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( user_form=user_form, ) ) class ProfileFormView(FormView): form_class = ProfileForm template_name = 'profile.html' success_url = '/' def post(self, request, *args, **kwargs): profile_form = self.form_class(request.POST) user_form = UserForm() if profile_form.is_valid(): profile_form.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( profile_form=profile_form, user_form=user_form ) ) But I keep getting the following error ImportError: Import by filename is not supported. from my import module. Any ideas, leads or solutions would be greatly appreciated because I've been stuck for the past 3 weeks with no working solution. I have read through solutions from https://krzysztofzuraw.com/blog/2016/two-forms-one-view-django.html as well as documentation notes … -
Data model issues related to foreignkey
I'm attempting to get my data model correct, but I keep getting errors the model doesn't exist depending on the order of the models or a SQL error stating there is no foreign or candidate key in the table. I'm struggling to get the User tables coid field to relate to my FacilityDimension model on coid, it keeps trying to relate on formattedusername. I've simplified all models and removed fields that aren't key fields. I'm working with an existing data set except for the User table and QVFormAccessRequest. This is the Custom User table: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) coid = models.CharField(max_length=5) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username # REQUIRED_FIELDS = "username" def __str__(self): return '%s - %s %s' % (self.username, self.first_name, self.last_name) Here is my Facility Model: class FacilityDimension(models.Model): coid = models.CharField(db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase. class Meta: managed = False db_table = 'Facility_Dimension' CFO table: class QvDatareducecfo(models.Model): cfo_ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',max_length=11, primary_key=True) # Field name made lowercase. class Meta: managed = False db_table = 'QV_DataReduceCFO' def … -
Linking stylesheet to Django website on Apache
I'm trying to get my Django website to use a stylesheet that until now worked just fine on a development server. As you can see below, I've been using the static files loader until now but no luck ever since I deployed it on Apache. I'm hardcoding it now but that doesn't work either. I used collectstatic thus I should have all static files I need. I modified Apache config file to serve static files (I followed tutorial). <!-- {% load static %} <link href='{% static "stylesheet.css" %}' rel='stylesheet' type='text/css'>--> <link href='var/www/html/site/static/stylesheet.css' rel='stylesheet' type='text/css'> Any ideas? -
Displaying the last object of nested relationship
i'm having trouble with returning data from many to many relationship between two models. i wan't to show all Currency? objects with their newestTickerobject related to that currency based on thecreated_at` field. i'm wondering how i can create such an output in json? desired output [ { "id": 1, "name": "Bitcoin", "symbol": "BTC", "img": "/media/static/img/currencies/bitcoin_uzSOQkH.png", "tickers": { "rank": 1, "price_dkk": "111239.222648", "market_cap_dkk": 1861795518438, "percent_change_1h": "0.03", "percent_change_24h": "2.44", "percent_change_7d": "46.80", "created_at": "2017-12-12T20:11:49.995851Z" } } ] view class CurrencyGetView(ProtectedResourceView): def get(self, request): currencies = CurrencySerializer(Currency.objects.all(), many=True) return JsonResponse(currencies.data, safe=False) serializers class TickerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Ticker fields = ('rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d', 'created_at', ) class CurrencySerializer(serializers.HyperlinkedModelSerializer): tickers = TickerSerializer(many=True) class Meta: model = Currency fields = ('id', 'name','symbol', 'img', 'tickers',) models class Ticker(models.Model): rank = models.IntegerField() price_dkk = models.DecimalField(max_digits=20, decimal_places=6) market_cap_dkk = models.BigIntegerField() percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = _('Ticker') def __str__(self): return self.id class Currency(models.Model): symbol = models.CharField(max_length=4, default='BTC', unique=True) name = models.CharField(max_length=20, default='Bitcoin', unique=True) img = models.ImageField(upload_to = 'static/img/currencies', blank=True) is_active = models.BooleanField(default=False) tickers = models.ManyToManyField(Ticker) class Meta: verbose_name_plural = 'currencies' def __str__(self): return self.name -
Django CreateView wit ForeignKey field
I want to add phone number to person. models.py class Person(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) description = models.CharField(max_length=64) class Phone(models.Model): CHOICES = ( ('P', 'personal'), ('C', 'company') ) person = models.ForeignKey(Person) number = models.CharField(max_length=20, unique=True) type = models.CharField(max_length=1, choices=CHOICES) views.py class PersonCreate(CreateView): model = Person fields = ['first_name', 'last_name', 'description'] class PhoneCreate(CreateView): model = Phone fields = '__all__' urls.py url(r'^(?P<pk>\d+)/$', PersonDetailView.as_view(), name = 'detail'), url(r'^(?P<pk>\d+)/addPhone$', PhoneCreate.as_view(), name='phone_create') Now it works like this. I am entering Person detail view (url: 'detail'). Here I have a button Add Address. It redirects me to view (url: 'phone_create') but I still have to choose person. How to create phone number to person from detail view automatically? -
How to override intermediate delete confirmation queryset in admin, I need not show related objects
I have a master model with 1 to 10,000 related objects, when I choose to delete one of them, confirmation delete view takes too long to show and I really do not need to show them in that confirmation in admin. How can I overrides intermediate confirmation queryset? Thanks in advance. -
Django get coupon code and check the boolean value ("is available") in another column for that code
I currently have a model for coupon codes that looks like this [code_number | code_available] class CouponCode(models.Model): code_number = models.CharField(max_length=256,default='') code_available = models.BooleanField() And i am using ajax to send a request to the server to see if the code is still available var couponCode = document.getElementById('id_coupon').value; $.ajax({ url: '/ajax/validate_coupon_code/', data: { 'coupon_code': couponCode }, dataType: 'json', success: function (data) { if (data.is_available) { alert("Coupon code is available."); } else { alert("not available") } } }); Where it stands right now my code checks if the code exists and returns a boolean value whether it exists or not def validate_coupon_code(request): coupon_code = request.GET.get('coupon_code', None) data = { 'is_available': CouponCode.objects.filter(code_number=coupon_code).exists(), #code number 'is_bool': CouponCode.objects.filter(code_number=True).exists() #boolean column } return JsonResponse(data) But what I am trying to do is get the coupon code and check the corresponding field in the code_available column to see if it is still set to True and return that. I feel like im close but i cant seem to get to it ::note the "is_bool" part is where i was trying to make this work -
build_absolute_uri inside model in Django
I'm using Django 2.0 In my application's models.py file I have defined get_absolute_url() to get the absolute URL of the instance. from django.conf import settings from django.http import request class ShortUrl(models.Model): short_key = models.CharField(max_length=25, blank=True) def get_absolute_url(self): reverse_url = reverse('short-url', kwargs={'key': self.short_key}) if hasattr(settings, 'SHORT_URL_HOST'): url_host = settings.SHORT_URL_HOST else: url_host = request.build_absolute_uri("/").rstrip("/") return url_host + reverse_url If is working fine. But in else statement, I want to get complete URI of current host concatenated with the reverse URL. But this gives error as module 'django.http.request' has no attribute 'build_absolute_uri' How can I return full absolute URI with domain name from model's get_absolute_url(self) function? -
custom name of a flash message Django
I'd like to flash a message in a template, which there is a ton of information on, but I haven't seen any way to give it a custom name, which would allow it to have the appropriate class or id for styling. In Laravel: webpage.php @if (session()->has('login_success')) <div id="loginFlash">{{ session('login_success') }}</div> @endif Where login_success is defined before rendering the page So far with Django: webpage.html {% for message in messages %} <div id="{{ message.tags }}"> {{ message }} </div> {% endfor %} But I can't get message.tags to return a SINGLE custom value. For instance: messages.add_message(self.request, messages.INFO, self.request.user.username, 'loginFlash') This returns: <div class="loginFlash info"> username </div> How to remove the second argument? It seems like all of the message methods already specify at least one tag. Thanks so much! -
Google calendar API returning different results than API explorer
I'm using the python client library to make a request to the google calendar API. It works fine but I'm not getting all of the events on the calendar. If I go to the API explorer however, I get everything and in a different format (for example it includes a "summary" key which I need.) Why is that? credentials = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_JSON_FILE_PATH, scopes) http_auth = credentials.authorize(Http()) calendar = build('calendar', 'v3', credentials=credentials) currentTime = datetime.datetime.now() maxTime = currentTime + relativedelta(months=+1) #do this to get all events on this day maxTime = maxTime.replace(minute=59, hour=23, second=59) currentTime = currentTime.isoformat('T') + '-06:00' maxTime = maxTime.isoformat('T') + '-06:00' response = calendar.events().list(calendarId="*******", singleEvents=True, maxResults=2500, showHiddenInvitations=True, timeMin=currentTime, timeMax=maxTime).execute() return JsonResponse(response) -
KeyError like model name (django)
I have problem with django-rest-framework (dynamic rest) I have KeyError like model name error https://pste.eu/p/ngrm.html models.py class PersonalData(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) third_name = models.CharField(max_length=30) gin_number = models.IntegerField(unique=True) login = models.CharField(max_length=45) password = models.CharField(max_length=45) phone_number = models.CharField(max_length=75) email = models.EmailField() born_date = models.DateField() passport = models.OneToOneField(Passport) snils = models.OneToOneField(Snils) inn = models.OneToOneField(Inn) drivers_license = models.OneToOneField(DriversLicense) photo = models.ForeignKey(DocumentImages) serializers.py from dynamic_rest.serializers import DynamicModelSerializer from res_employee.models import PersonalData class PersonalDataSerializer(DynamicModelSerializer): class Meta: model = PersonalData name = 'personal_data' fields = '__all__' urls.py from rest_framework import routers from res_employee.views import PersonalDataViewSet router = routers.SimpleRouter() router.register(r'^test', PersonalDataViewSet) urlpatterns = router.urls -
creating extrarow for django queryset
my model Table col_1 col_2 col_3 ################## 1 a 3 2 b 5 3 c 6 i did in view.py results = Item.all() for result in results total=+ result.col_3 i have total=14 How to do same through model method total()? I mean: results.total() will return 14 -
Django - Adding password validations in a ModelForm
I have made a ModelForm in Django for the registration of new user. It has 4 fields (username, email, password, and confirm_password). I want to add some validations for password. For example, if password is shorter than 8 characters or password is similar to the username, then raise an error message. How can I do this? Here is my forms.py file: from django.contrib.auth.models import User from django import forms class user_form(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput) confirm_password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = ['username','email', 'password','confirm_password'] -
Django html set up
I have a basic website set up with Django and have been following the sentdex tutorials. I cannot figure out how to include the blog posts (I'm assuming this would be either blog.html or post.html) in the bootstrap 'about' section, which I Have renamed blog. Basically, I want the blog posts (derived from the database) to appear here in the 'about' section in bootstrap, rather than at the bottom or in a separate page. I have an 'aboutme' app (main website) that contains the home.html {%extends "aboutme/header.html" %} {%block content%} <p>Welcome to this "about" page that is all about the website: {%include "aboutme/includes/mysnippet.html"%} {% endblock %} {%block blogcontent%} {% endblock %} ..and a header.html which contains the whole index.html of the bootstrap site itself. Below is the about section of the bootstrap websit about/blog section that includes the django templating logic (block content) <!-- About Section (Blog)--> <section class="bg-primary text-white mb-0" id="about"> <div class="container"> <h2 class="text-center text-uppercase text-white">Blog</h2> <hr class="star-light mb-5"> <div class="row"> <div class="col-lg-4 ml-auto"> <p class="lead">This is the blog section</p> {%block blogcontent%} {%endblock %} </div> <div class="col-lg-4 mr-auto"> <p class="lead">The blogs outlined in the models section and stored in the database, are going to be displayed here.</p> </div> … -
Local variable not assigned in Django
Building a fairly straightforward "website" for a class project. It's essentially a list of formulas. Each page is a different formula. Here's an example of the Django: def calc(request): form = PecletForm(request.POST or None) answer = None if request.method == 'POST': if form.is_valid(): #first_number = form.object.get('first_number', 0) #second_number = form.object.get('second_number', 0) #first_number = form.get('first_number', 0) l = form.cleaned_data.get('l', float(0.0)) v = form.cleaned_data.get('v',float(0.0)) d = form.cleaned_data.get('d', float(0.0)) #second_number = form.get('second_number', 0) answer = float(v) * float(l) / float(d) return render(request, 'peclet_number/index_peclet_number.html', {'form' : form, 'answer' : answer}) That one works fine. This one, however, does not: def calc(request): form = debyeForm(request.POST or None) answer = None if request.method == 'POST': if form.is_valid(): z = form.cleaned_data.get('z', float(0.0)) c = form.cleaned_data.get('c', float(0.0)) lile = 710e-12 F = 96487 R = 8.314 t1 = 293 t2 = 300 answer = ((lile*R*t1)/((F**2)*(z**2)*c))**0.5 answer1 = ((lile*R*t2)/((F**2)*(z**2)*c))**0.5 return render(request, 'debye_length/index_debye_length.html', {'form' : form, 'answer' : answer, 'answer1' : answer1}) When I try to run it, I get "UnboundLocalError at /debye_length/" and "local variable 'answer1' referenced before assignment" So what's the problem? The variable seems not to be used anywhere but locally, and it's not self-referential or iterative. So what's referencing it before it's assigned? -
Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown
In the Django admin, when the choice Custom is selected from a dropdown list, I want to display the inline start_date and end_date fields to allow the user to specify a specific start and end-date instead of a pre-defined time period. After researching for some time, suggestions include: use hidden fields, define override get_form in ModelAdmin, or use custom Javascript (which I have zero experience with). The Question: how can I display (show) the inline start_date and end_date fields when a specific value (Custom) is selected in the dropdown of a Django Admin field? When Custom is not selected, start_date and end_date would be hidden from view. Step 1: Step 2: Step 3: Below is a complete example of the exact example code I have locally: settings.py INSTALLED_APPS = [ 'django.contrib.admin', ... 'dropdown.apps.DropdownConfig', ] apps.py from django.apps import AppConfig class DropdownConfig(AppConfig): name = 'dropdown' models.py from django.db import models class DropdownModel(models.Model): CHOICES = ( ('Today', 'Today'), ('Yesterday', 'Yesterday'), ('Last 7 Days', 'Last 7 Days'), ('Last 14 Days', 'Last 14 Days'), ('Last 30 Days', 'Last 30 Days'), ('Last 60 Days', 'Last 60 Days'), ('Last 90 Days', 'Last 90 Days'), ('This Year', 'This Year'), ('All Time', 'All Time'), ('Custom', 'Custom') ) date_range … -
django import in template
I know how to paginate in a function view or CBV, but that doesn't help here: The POC model has a foreign key pointing to the Tag model. In the Tag detail template, I want to show all the POCs that point to that Tag. {% for poc in tag.poc_set.all|dictsort:"name" %} The problem is there are thousands. Can I import Paginator in the template and construct a Paginator passing tag.poc_set.all to the constructor (or "wrap" the queryset in a Paginator - excuse my javaspeak)? -
Import unstructured excel file to database
I have to import data from excel files into the database. The structure of these files do not match with the structure of the model, so I guess i need to do some kind of data-manipulation to arrange the tupels accordingly. The files I have to import look like this: The django-model has the following attributes: Country, Commodity, Year, Value So what would be the best way to read the data, arrange it in the correct structure and import it into the database (preferably with automatic updates of existing tupels). I spent a lot of time researching the existing python- and django-libraries for this requirements (like PyExcel, Pandas, Django-Excel, Django-Import-Export), but I couldn't really find out wich is the best and if it supports the rearrangement of the data before importing. I hope you can give me some recommendations and solutions for this task :) -
Django - gunicorn on App Engine. Error: 'No Module Named my_project'
I'm trying to upload my Django(v2.0) application to Google App Engine, but Gunicorn(v19.7.1) can't find my app. When I deploy my app using gcloud app deploy I get error 'No Module Named AppFlex' Full screenshot of the error and app.yaml config is below. The contents of the wsgi.py are: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AppFlex.settings") application = get_wsgi_application() Additionally, I can run the app locally using: gunicorn AppFlex.wsgi --workers 16 Another screenshot where I can run the app using gunicorn locally :