Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.x - filter redirects based on relational database content
I have an app I am developing that has 2 types of user (A & B) and I have a page that I want to redirect users that are not authenticated and not type B. The user type is set in a relational database. My two db tables for this are User - pk, etc... Profile - pk, uid (user pk), account_type What I have done so far: I have already used @login_required in my views.py doc to verify authentication successfully. I can filter for the content where pid is set manually: Profile.objects.filter(user__pk=1) And I can get the current user id with request.user.id What I am struggling with What I have attempted to do is create a conditional, where I am using the request.user.id with the filter to find that user and then verify account type. I am not sure how to pull the account_type and at this point my code is becoming a mess, and probably ineffective. I've searched for this, but everything I have found using the keywords I have here has revealed different problems than what I am trying to solve. -
settings.DATABASES is improperly configured Django error
I know there are similar posts to this, I've read them and they are different and didn't fix my problem. I am trying to connect my database I have the following settings: DATABASE = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '', 'NAME': '', 'USER': '', 'PASSWORD': '', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } In actual, I have every entry filled. I am getting the following error: settings.DATABASES is improperly configured. Please supply the ENGINE value. I've made sure ODBC Driver 17 is installed. I've looked at my SQL Server Configuration Manager and saw that my database was running. (I've went over the steps on this determining whether the database engine is installed and started). I am still getting the error I was wondering what else I could do to fix it or check to point me to the source of the problem? -
Django How to add to a foreign key field
I want to design a model for the currrent user to see all the people he referred. I create another model to keep track of all the referral relation between users, such as 'stephen -> jack', 'stephen -> mike' class CustomUser(AbstractBaseUser): // ....... a lot more fields referred_who = models.ForeignKey('referral', blank=True, null=True, on_delete = models.CASCADE) class Referral(models.Model): referrer = models.ForeignKey(CustomUser, on_delete = models.CASCADE) referred = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name='referred') class Meta: unique_together = (("referrer", "referred"),) def __str__(self): return self.referrer.username + ' -> ' + self.referred.username The question I am having right now is that one user can refer multiple users, but the field 'referred_who' I use to keep track of all the referral relations can only keep one of them. In my back-end admin it shows: Referred who: stephen1 -> stephen2 (with a dropdown with all the relations but I can only choose one of them) What I want is somethig like: Referred who: stephen1 -> stephen2 stephen1 -> stephen3 stephen1 -> stephen4 And I can access this 'Referred_who' field to get all the relations this current user has. Is there a way to add to the foreign key field instead of just choosing one of them? Can someone … -
Issues using Crispy Forms on Mac
I am trying to use Crispy Forms in my Django project but am having issues running the project on my mac. When I use the runserver command on my terminal, I get this error: ModuleNotFoundError: No module named 'crispy_forms' When I run pip freeze it says that I have both crispy forms and django updated and installed: adammart1n$ pip3 freeze Django==2.1.7 django-crispy-forms==1.7.2 olefile==0.46 Pillow==5.4.1 pygame==1.9.4.dev0 pytz==2018.9 Here is how I have it listed in my installed apps: INSTALLED_APPS = [ 'trade.apps.TradeConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] This code runs fine on my windows machine but will not run on my mac. Thanks in advance for the advice! -
Django Rest Framework inserting and updating writable nested serializer
I trying to insert and update a writable nested serializer with Django Rest Framework, following examples like this. But it doesn't work, because somehow after I execute serializer.is_valid() it lose the reference from serializer.validated_data like if it never was sent. What could I having doing wrong? My models class User(AbstractUser): institution = models.ForeignKey(Institution, on_delete=None, null=True, blank=True) class Meta: db_table = 'User' managed = True verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] def __str__(self): return self.email class Institution(models.Model): id = models.AutoField(db_column='id', primary_key=True) name = models.CharField(db_column='name', max_length=255, null=False) country = models.CharField(db_column='country', max_length=255, null=False) class Meta: db_table = 'Institution' managed = True verbose_name = 'Institutions' verbose_name_plural = 'Institutions' ordering = ['id'] def __str__(self): return self.name My serializers class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = '__all__' datatables_always_serialize = ('id', 'name', 'country') class UserSerializer(serializers.HyperlinkedModelSerializer): institution = InstitutionSerializer() def create(self, validated_data): return User.objects.create_user(**validated_data) def update(self, instance, validated_data): institution_data = validated_data['institution'] instance.institution = Institution.objects.get(pk=institution_data['id']) return instance class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'email', 'password', 'is_active', 'institution', ) datatables_always_serialize = ( 'id', 'username', 'first_name', 'last_name', 'email', 'is_active', 'institution', ) My view class UserViewSet(ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSuperUserPermission,) def list(self, request, **kwargs): params = Q() if 'search[value]' … -
django: Displaying database errors when debug = False
I am using Django Rest Framework to perform get() post() on existing database. In the models, I haven't defined any primary or foreign key relations as these constraints are handled at database level. When I have debug = True in the settings.py file, the database level errors with traceback get displayed. However, when debug = False, I wish to display the errors in the response. eg: error message: IntegrityError at /dqf_api/ReceiptLog/ (1062, "Duplicate entry 'ede pivot-dummy-ede_case_76-ede pivot command 76' for key 'PRIMARY'") When debug = True, this is displayed. When debug = False, how do I catch this error and display it? -
python social auth change referrer address
I have a level 7 gateway (lets say example.com), behind which I have a few stamps (example1.com, example2.com, etc) thereby building a fault tolerant website. I am using python social auth to authenticate my django app with microsoft graph (live.com). The issue is that when I click login from example.com, and it forwards that request to example1.com, the login request happens from example1.com. If I specify a OAuth callback addresses as example.com/complete/azuread-oauth2, example1.com/complete/azuread-oauth2, and example2.com/complete/azuread-oauth2, it doesnt work, social auth gives me the error: raise AuthStateForbidden(self) social_core.exceptions.AuthStateForbidden: Wrong state parameter given. This might be because of the referrer site being example.com, but the actual request going from example1.com, though I am not sure. Is there any way to fix it so that the redirection doesnt happen to example1.com, and I can hide example1.com behind example.com? -
Is serialization the best way to implement a save game feature in a Django game?
I'm writing a simulation game in Django and was wondering what the best way to implement a save game feature would be. I want each user to be able to create, save, and load multiple games independent of other users. Ideally they would create the game and a preconfigured set of objects would be used initially. As the game progresses, these will obviously be modified (either manually by the user or via the actions taking place in the simulation). I want these changes to be saved automatically, then the user should be able to switch between their various saved games and different information will be presented to them based on which game they decide to load at any particular point in time. Can this be done with serialization or is there a better way to accomplish this? I know Django has a built-in serialization module so I was thinking of using this. If serialization is the way to go, what would a basic implementation of this look like? Code examples or just general theory would both be very helpful. Thanks in advance! -
Why form._errors is working in generic.UpdateView but not in generic.CreateView?
When I use this in my mixins form._errors[forms.forms.NON_FIELD_ERRORS]=ErrorList(["age must be positive"]) in my UpdateView it works and the message is popped out in red. But in my CreateView nothing is popping out How can I achieve this? Here's my mixin.py: class AgePositiveMixin(object): def form_valid(self, form): print(form.instance.age) if form.instance.age>0: return super(AgePositiveMixin, self).form_valid(form) else: form._errors[forms.forms.NON_FIELD_ERRORS]=ErrorList(["Age must be positive"]) # raise forms.ValidationError('Age must be positive') return self.form_invalid(form) -
ModuleNotFoundError: widget_tweaks
I am trying to deploy my python project onto heroku. However there’s some error message stating that module not found for widget_tweaks despite having it installed as well as in my installed apps. How do I go about solving it. -
How to change django-wiki package to use slug field supporting unicode?
I want to use django-wiki package for supporting research work in company. But I came across unicode problem. SlugField only support "alphanumeric characters and - or _" How can I solve this problem. "This will be the address where your article can be found. Use only alphanumeric characters and - or _. Note: If you change the slug later on, links pointing to this article are not updated." -
How to get django admin change form to pre-select choice field?
I have a model field with choices, as defined here: class Pack(models.Model): SIZE_10x20 = Decimal(200.000) SIZE_10x10 = Decimal(100.000) SIZE_5x10 = Decimal(50.000) size_code_choices = ( (SIZE_5x10, '5x10'), (SIZE_10x10, '10x10'), (SIZE_10x20, '10x20'), ) size_code = models.DecimalField(max_digits=7, decimal_places=3, choices=size_code_choices, default=SIZE_10x20) My admin.py uses the default forms: class PackAdmin(admin.ModelAdmin): list_display = ('size_code') fields = ('size_code') admin.site.register(Pack, PackAdmin) However, when I open up my admin panel and check the model instance change form the dropdown menu is not pre-set to the choice that is stored in the database. I've attached to images to demonstrate what I mean: List display for all model instances Change Model Form It simply selects the one at the top of the list. I would like users to be able to make small changes to the model without always having to check and reset this field everytime this form is used. I've looked into overriding ModelAdmin.get_changeform_initial_data(request) but to no avail. I have a similar choice selection on a Model CharField and do not have this issue with it. Is there something going on with the DecimalField that I am unaware of? -
Checking for permissions in django template
I have a database of objects and each one of the objects has several permissions to view, edit, etc. The following example is a simplified version of the complete model. class Warehouse(models.Model): ... view_permission = models.ForeignKey(Permission, ...) edit_permission = models.ForeignKey(Permission, ...) ... When the object is created, a pre_save signal is sent to create and fill these permissions fields. The signal handler also creates a group with some of the permissions created. My problem is that when I set a user to one of these dinamically created groups, I can't figure out how to check if a user has that particular permission. I have been trying to do the following: > from django.contrib.auth.models import User > from myapp.models import Warehouse > w = Warehouse.objects.get(pk=1) # get the first object > u = User.objects.get(username='jhon') # get a user The user john belongs to the group where the permissons of w are set. If I use user.get_all_permissions() it returns a set of strings. If I use user.has_perm(w.view_permission) it returns false. The only way I managed it to work is by typing > p = w.view_permission > user.has_perm('%s.%s' % (p.content_type.app_label, p.codename)) True But it is ugly and somehow seems wrong. Do you guys … -
Disable Django model admin buttons (save, delete, etc.)
I would like to disable all buttons that they are present into the submit-row (save, save and edits, delete, etc...) after the click on one of they. I started to try to override the change_form for admin model. Something like this: class MyAdmin(admin.ModelAdmin): change_form_template = 'admin/reports/models/change_form.html' into the admin/reports/models/change_form.html file I added this code: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} <div class="submit-row"> {% block submit-row %} {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save">{% endif %} {% if show_delete_link %} {% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %} <p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p> {% endif %} {% if show_save_as_new %}<input class="myclass" type="submit" value="{% trans 'Save as new' %}" name="_saveasnew">{% endif %} {% if show_save_and_add_another %}<input class="myclass" type="submit" value="{% trans 'Save and add another' %}" name="_addanother">{% endif %} {% if show_save_and_continue %}<input class="myclass" type="submit" value="{% if can_change %}{% trans 'Save and continue editing' %}{% else %}{% trans 'Save and view' %}{% endif %}" name="_continue">{% endif %} {% if show_close %}<a href="{% url opts|admin_urlname:'changelist' %}" class="closelink">{% trans 'Close' %}</a>{% endif %} {% endblock %} </div> But I not see any changes (class="myclass" there aren't). My next changes will be the js code … -
Reverse for 'form_detail' not found. 'form_detail' is not a valid view function or pattern name
I'm trying to redirect to another view that goes to a randomly generated URL but Django can't doesn't know what to render. I'm not sure what is wrong with my URL's in this one. I think I did it correct, but Django disagrees. What am I doing wrong? Reverse for 'form_detail' not found. 'form_detail' is not a valid view function or pattern name. Views.py def index(request): randomUrl = str(uuid.uuid4()) return redirect("form_detail", random_url=randomUrl) def form_detail(request, random_url): template = "faq.html" context = {} form_detail = random_url context["form_detail"] = form_detail stripeUID = str(uuid.uuid4()) payment = stripe.checkout.Session.create( success_url="https://myUrl.com/accepted", cancel_url="https://myUrl.com/cancel", payment_method_types=["card"], client_reference_id= stripeUID, line_items=[ { "amount": 2000242, "quantity": 1, "name": "Expensive item", "currency": "usd", } ] ) context = payment.id return render(request, template, context) App urls.py from . import views app_name = 'request' urlpatterns = [ path('', views.index, name='index'), path('form-detail/(?P<random_url>[-\w]+)/$', views.form_detail, name="form_detail") ] -
Django - 'User' object has no attribute 'session_set'
I'm trying to add a session tab to my Django project, i called the page from my navbar using this line: <li><a href="{% url 'user_sessions:session_list' %}">Sessions</a></li> But i keep getting the following error: 'User' object has no attribute 'session_set''User' object has no attribute 'session_set' Exception Location: C:\Users\User\lib\site-packages\django\utils\functional.py in inner, line 214 I don't know where this error comes from, i did not find any other reference online, can anyone help me? Here is the login view that i'm using: https://github.com/Bouke/django-two-factor-auth/blob/master/two_factor/views/core.py -
Django two ForeignKey from same model
In Pegawai model, I need two ForeignKey from: Jabatan Model unit_kerja field from Jabatan Model How to apply these for my Pegawai Model? only number 1 worked here. here my models.py from django.db import models from django.urls import reverse # Create your models here. class UnitKerja(models.Model): nama_unit_kerja = models.CharField(max_length=100) def get_absolute_url(self): return reverse("users:unitkerja") def __str__(self): return self.nama_unit_kerja class Jabatan(models.Model): nama_jabatan = models.CharField(max_length=100) level_jabatan = models.IntegerField() unit_kerja = models.ForeignKey(UnitKerja, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse("users:jabatan") def __str__(self): return self.nama_jabatan class Pegawai(models.Model): nip = models.CharField(max_length=100, unique=True) nama_pegawai = models.CharField(max_length=100) alamat = models.CharField(max_length=255) jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE) #this line# unit_kerja = models.ForeignKey(Jabatan.unit_kerja, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse("users:pegawai") def __str__(self): return self.pegawai Sorry my broken English btw -
create objects of different models in single ModelForm?
Is it possible to use single ModelForm to create objects of different models? I'm trying something like this, but "...name 'model' is not defined..." : urls.py path('<modelname>/create', views.object_create, name='object-create') views.py def object_create(request, modelname): if request.method != 'POST': form = ObjectForm(modelname) return render (request, 'product/form.html', {'form':form}) else: form = ObjectForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('product:feature-list')) return render (request, 'product/form.html', {'form':form}) forms.py class ObjectForm(forms.ModelForm): def __init__(self, modelname, *args, **kwargs): super().__init__(*args, **kwargs) self.model = apps.get_model('product', modelname) class Meta: model = model -
Prevent clearing of field when field not rendered in form
Within a form, there is a field called 'title'. If title != None, the 'title' field should not be shown/be edited on subsequent page loads. {% if form.instance.user_title == None %} {{ form.user_title }} {% endif %} The problem is that when form.instance.user_title != None and the user makes changes to the rest of the fields on the form and then saves the form, the title field is set to None automatically. Is there a was to prevent this without using form validation on def clean()? Thanks! -
Django Custom User Model - Form Tuple Problems
I'm creating a Custom User Model, based on AbstractUser, which has several extra fields added. I've read through the documentation and assorted examples, but I'm having a couple of frustrating (and probably simple) issues I'm adding some extra fields to the user and the admin, for later group validation. I'm trying to add the custom fields to the Custom UserCreationForm and UserChangeForm, and I'm using Class Meta: to try and add my new fields in while including the existing ones using the form class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ('character_name' ,'ritual_points', 'contribute_points',) class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm): model = CustomUser fields = UserChangeForm.Meta.fields + ('character_name', 'ritual_points', 'contribute_points',) Which according to all the examples I've seen should just work. However, every time i try and make the migrations, it throws a strop TypeError: Can't convert 'tuple' object to str implicitly Everything I've read suggests this should work without any issues. -
Django misunderstands NamedTuple
We have a NamedTuple in the code like: from typing import NamedTuple class StandardParameters(NamedTuple): offset: int limit: int locale: str This works fine on our local machines using Python 3.6.6 importing this file under ./manage shell, and works fine on the local server (macOS) using ./manage runserver. This also works fine on the Ubuntu production server, using ./manage shell and importing this file. But if we use the production server's Django HTTP server, it fails on this class definition with: function() argument 1 must be code, not str The Django error response indicates it's the same version of Python we're using locally, and via ./manage shell, 3.6.6. But it's unable to evaluate NamedTuple as a class. Sure enough, if I add raise Exception(str(NamedTuple)), then on our local systems, it logs "class NamedTuple" but on the Ubuntu HTTP server it logs "function NamedTuple". This makes us feel that we're using an older version of Python, but again, the returned DEBUG response indicates 3.6.6. We only have one other NamedTuple anywhere in the code, and it is working on the Ubuntu server. It's being used in the "backward compatibility" form: from typing import NamedTuple ClientInfo = NamedTuple('ClientInfo', [ ('client', Client), ('clientVersion', str), … -
toggle_paused() missing 1 required positional argument: 'self' when view runs models method
I am getting the error TypeError: toggle_paused() missing 1 required positional argument: 'self' when I trigger ToggleView(). I am still pretty new to Django and im not sure how to resolve the issue. I tried using @classmethod on the method but that just moved the error to another method. Any help would be much appreciated! class Entry(models.Model): @property def is_paused(self): """ Determine whether or not this entry is paused """ return bool(self.pause_time) def pause(self): pass def unpause(self, date=None): pass def toggle_paused(self): if self.is_paused: self.unpause() else: self.pause() def save(self, *args, **kwargs): self.hours = Decimal('%.5f' % round(self.total_hours, 5)) super(Entry, self).save(*args, **kwargs) def ToggleView(request): Entry.toggle_paused() Entry.save() -
Google App Engine not finding the static files for a django project, and also a .txt file that my website depends upon
So I made a website on Django and wish to deploy it to Google App Engine, the website itself is deployed but without all the static files. Also, there's a dataset in a .txt file that my website depends upon to run (It's a machine learning project.), but it's not able to find it and the browser just throws a file not found error. it would be super cool if someone could help me out. here's the app.yaml file. enter image description here -
Django signup page won't display - Produces ImproperlyConfigured at /accounts/signup/ instead
I'm working through Django For Beginners by William S. Vincent. I get this error when I try to access http://localhost:8000/accounts/signup/: Internal Server Error: /accounts/signup/ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/edit.py", line 168, in get return super().get(request, *args, **kwargs) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/edit.py", line 32, in get_form form_class = self.get_form_class() File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/edit.py", line 93, in get_form_class model = self.get_queryset().model File "/Users/me/.local/share/virtualenvs/blog-dFYK_SP1/lib/python3.7/site-packages/django/views/generic/detail.py", line 73, in get_queryset 'cls': self.__class__.__name__ django.core.exceptions.ImproperlyConfigured: SignUpView is missing a QuerySet. Define SignUpView.model, SignUpView.queryset, or override SignUpView.get_queryset(). [19/Mar/2019 21:12:04] "GET /accounts/signup/ HTTP/1.1" 500 94136 This is the source code for the particular chapter I'm looking at. As far as I can see, I've copied it exactly. I've even checked for proper indentation and can't see any issues. Is there anything I should check in relation to this? -
Django - Charts Pygal
I'm trying to include charts in my django application. Have tried to install Highcharts and Fusioncharts, but all very complex in my opinion. I stumbled upon Pygal which is much easier (maybe a bit less nicer but anyway ! ) Thanks to a tutorial on https://hackernoon.com/server-rendered-charts-in-django-2604f903389d I have managed to render my first chart ! (hurray!!). Though, the author of the above article uses a Class Based View. and it is a separate function. How can I fit his into a regular, already existing, view function that renders - next to the graph - as well other stuff.? Thanks !!! class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) # Instantiate our chart. We'll keep the size/style/etc. # config here in the view instead of `charts.py`. cht_vintages = VintagePieChart( height=300, width=300, explicit_size=True, style=LightGreenStyle ) # Call the `.generate()` method on our chart object # and pass it to template context. context['cht_vintages'] = cht_vintages.generate() return context