Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix the No Reverse Match in django?
I'm having this error and I don't know why, here's my code. from django.urls import path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('relative/', views.relative, name = 'relative'), path('other/',views.other,name='other') ] <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>WELCOME TO RELATIVE URL TEMPLATES</h1> <a href="{% url 'basic_app: other' %}">Link</a> </body> </html> I'm not sure why I have this error because im putting the format as it is, or is there any updates in it? -
Image from database is not displayed in django template
I am trying to store images in database via form ImageField of model which gets uploaded to media folder that i have created and render the same in template. This is my folder structure- folder structure This is my settings.py file- """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '9q5awt($2rn+iwvku6p!r59st5a@g^%oqcc16=*v9s&-q_7=+n' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'userAuth', 'groups', 'posts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { … -
Error R14 (Memory quota exceeded) Django Heroku
I create a Django website for deep learning classification and I am continuously getting this error. I have no idea, how to resolve these errors. ? Please help me 2020-07-16T18:24:29.776217+00:00 heroku[router]: at=info method=HEAD path="/" host=skin-lesion-diagnosis.herokuapp.com request_id=864c01c5-1fdc-4d56-bde5-dc6bfa1cb778 fwd="3.88.42.194" dyno=web.1 connect=1ms service=20626ms status=200 bytes=3265 protocol=https 2020-07-16T18:24:30.250801+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:24:30.259515+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) 2020-07-16T18:24:29.785002+00:00 app[web.1]: 10.168.89.215 - - [16/Jul/2020:18:24:29 +0000] "HEAD / HTTP/1.1" 200 2866 "-" "Ruby" 2020-07-16T18:24:49.795030+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:24:49.797135+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) 2020-07-16T18:25:09.009352+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:25:09.012588+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) 2020-07-16T18:25:29.026785+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:25:29.029713+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) 2020-07-16T18:25:49.109325+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:25:49.111295+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) 2020-07-16T18:26:10.199039+00:00 heroku[web.1]: Process running mem=844M(164.9%) 2020-07-16T18:26:10.201077+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) -
access value in a model in Django
i'm started to learn django a week ago and I'm trying get the bid_value from a model in django but it return this error: AttributeError at /item/2 'QuerySet' object has no attribute 'bid_value' I tried a few ways, but it didn't work models.py: class Auction_listings(models.Model): product_image = models.CharField(max_length=500) product_title = models.CharField(max_length=40) product_description = models.CharField(max_length=200) product_category = models.CharField(max_length=20, default="others") product_price = models.FloatField() is_closed = models.BooleanField(default=False) username = models.CharField(max_length=64) post_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.product_title}" class Bids(models.Model): auction = models.ForeignKey(Auction_listings, on_delete=models.CASCADE) username = models.CharField(max_length=64) bid_value = models.FloatField() views.py: def add_bid(request, item_id): username = None if request.user.is_authenticated: username = request.user.username if request.method == "POST": bid = Bids.objects.filter(auction=item_id).bid_value new_bid_value = float(request.POST.get("bid")) if new_bid_value > float(bid): new_bid = Bids(auction=item_id, username=username, bid_value=new_bid_value) new_bid.save() else: return render(request, "auctions/error.html", { "error": "your bid is lower than the current bid..." }) def view_item(request, id): item_id = Auction_listings.objects.get(pk=id) add_bid(request, item_id) try: bid = Bids.objects.get(auction=item_id) return render(request, "auctions/item.html", { "auctions": item_id, "bid": bid }) except: return render(request, "auctions/item.html", { "auctions": item_id, }) thank you in advanced -
Django NoReverseMatch Error with Stripe Payment
I am unable to resolve this error. Please advise. I have the base app, fundraiser app, and donation app (which has Stripe installed). Donations was working fine before I tried to append donations onto fundraiser since a donation should be tied to a specific fundraiser. Landing on homepage shows you an index of all fundraisers as well as login/logout functionality. Clicking a fundraiser will take you to the fundraiser show page as /show/id. The show page has a button that will take you to a form for payment /show/id/donate. Entering the donation info (name/credit card info) and clicking donate button should initialize the charge view functionality for stripe to operate. Instead I get NoReverseMatch at /show/9/donate Reverse for 'charge' with no arguments not found. 1 pattern(s) tried: ['show/(?P[0-9]+)/donate/charge/$'] Request Method: GET Request URL: http://127.0.0.1:8000/show/9/donate Base App URLs urlpatterns = [ path('', include('fundraisers.urls')), path('show/<int:id>/donate/', include('donations.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')) ] Fundraisers App URLs urlpatterns = [ path('' , views.index, name='index'), path('create', views.create, name='create'), path('show/<int:id>', views.show, name='show'), path('show/<int:id>/donate', views.donate, name='donate') ] Donations App URLs urlpatterns = [ path('', views.index, name="index"), path('charge/', views.charge, name="charge"), path('success/<str:args>/', views.successMsg, name="success"), ] Fundraisers App Views def index(request): fundraisers = Fundraiser.objects.all() return render(request, 'fundraisers/index.html', { 'fundraisers': … -
Local.py and prod.py settings files in .gitignore for Django
I have set up two settings.py files, local.py and production.py. In my __init__.py, I have this: from .base import * from .production import * try: from .local import * except: pass The idea is that local.py is in the .gitignore file, so that when I push it to my web server on AWS Elastic Beanstalk, the try except fails because the local.py file is not pushed. However, I want the local.py file in GitHub so that other can collaborate. How can I achieve this? Thanks! -
How do I get Django connecting to SQL Server working with AWS Lambda Layers?
I am trying to use Django connected to SQL Server 2019 in an AWS Lambda function using Lambda Layers. I found an example using pyodbc to connect to SQL Server here: https://medium.com/@kuharan/aws-lambda-python-ms-sql-server-the-easy-way-e7667d371cc5. I downloaded the example Lambda Layer and Lambda function and was able to get that working. However, now I am trying to install Django and django-mssql-backend in the layer in order to use Django to connect to SQL Server 2019. Here is a screenshot of how the directory structure is setup with Django and django-mssql-backend installed: I zipped up the pyodbc-layers folder and uploaded that into Layers. Here is a screenshot of that: Then when I run my lambda function, I get the error: Response: { "errorMessage": "Unable to import module 'lambda_function': No module named 'django'", "errorType": "Runtime.ImportModuleError" } Here is a screenshot of my function and the error message: How do I resolve this? Thanks! -
I want to add django form with html specific input
<div class="form-group"><input class="form-control" type="email" name="email" placeholder="Email"></div> <div class="form-group"><input class="form-control" type="password" name="password" placeholder="Password" ></div> I want to add {{ form.email }} and {{ form.password }} to the email and password field. This is the django default login view. -
Page not working shoing 405 error on form submission?
My url View: urlpatterns = [ re_path(r'^$', views.Tweet_List_view.as_view(), name='list'), # re_path(r'^$',views.listview, name='list'), re_path(r'^(?P<pk>\d+)/$', views.Tweet_Detail_View.as_view(), name='detail'), re_path(r'^(?P<pk>\d+)/delete$', views.Tweet_Delete_View.as_view(), name='delete'), re_path(r'^(?P<pk>\d+)/edit/$', views.Tweet_Update_View.as_view(), name='update'), re_path(r'^create/$', views.Tweet_Create_View.as_view(), name='create'), ] My views.py: class Tweet_List_view(ListView): # template_name = 'tweet/tweet_list.html' model = Tweet def get_queryset(self, *args, **kwargs): querryset = Tweet.objects.all() # print(self.request.GET) if self.request.GET: q = self.request.GET.get('q') querryset = Tweet.objects.filter( Q(content__icontains=q) | Q(user__username__icontains=q) ) return querryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) # print(self.kwargs) context['tweet_form'] = TweetModelForm context['create_url'] = reverse('list') return context My html file: {% block content %} <br/> <div class="row"> <div class="col-sm-3 col-xs--12" style="background-color: red; height: 200px; border-radius: 30;"> {{request.user}} </div> <div class="col-sm-9" > {% if not request.GET.q %} <div> <form method="POST" action={{create_url}} > {% csrf_token %} {{ tweet_form.as_p }} <input type="submit" value="tweet" class="btn btn-primary" > </form> </div> <hr/> {% endif %} I have a form in my tweet list view on submitting that it redirects to the current tweet list view so but on going to that page it shows http 405 error. I have seen that having the same url shows such error but i have different url patterns. -
How to obtain 'refresh_token' for an existing (expired) authentication token (django-oauth-toolkit)?
django-oauth-toolkit documentation (tutorial) shows how to obtain Bearer authentication token (access_token) and use it, and how to renew expired token using refresh_token. Question is: when long time is passed since access_token (and corresponding refresh_token) is obtained, user may no longer know what refresh_token value is... How exactly refresh_token can be obtained in that case? -
Django: How to make one-to-one link work in a serializer REST API setting?
I have made a UserSerializer from Django's default User and also a UserProfileSerializer from a custom model I made one-to-one linking to the Django default User. What the UserProfileSerializer have right now in addition to the Django default User is a "nickname" attribute. Now, I am making a RegisterSerializer to take in the "nickname" attribute from my front-end. However, I do not know how to correctly take in the "nickname" input from my front-end and encode that into my UserProfile database table. This is what I have so far: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('nickname') class UserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(source='userprofile') class Meta: model = User fields = ('id', 'username', 'email', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) user.profile = UserProfile.objects.create(user=user, **profile_data) profile = user.get_profile() profile.save() user.save() return user class Meta: model = User fields = ('id', 'username', 'email', 'password', 'nickname') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password'], validated_data['nickname'] ) profile = user.get_profile() profile.save() user.save() return user However, I can't seem to do this because "nickname" is not a field from model User. -
How to bypass default file storage for testing purposes?
Hi we have a production server that uses a cloud to get some files. It's configured through DEFAULT_FILE_STORAGE in the settings.py. Our model is very simple, something like: def generate_filename(instance, filename): now = datetime.now(UTC) return f"generic_forwarder_import/" \ f"{instance.platform_customer.name}/" \ f"{now.year}/{now.month:02d}/{now.day:02d}/" \ f"{now.hour:02d}h{now.minute:02d}m-{filename}" class CompanyImport(models.Model): data = models.FileField(upload_to=generate_filename) In my unit test file, I'm trying to bypass default file storage like this (it's only a method from a class of type TestCase): def test_import_csv(self, file_name): base_name = file_name.split('/')[-1] platform_c_name = base_name.split('.')[0] # Using FileSystemStorage with TemporaryDirectory() as tmp_dir: fs = FileSystemStorage(location=tmp_dir) with NamedTemporaryFile(mode='w+', encoding='utf-8', dir=tmp_dir) as tmp_file: test = fs.save(tmp_file.name, open(file_name, 'r')) c_i = CompanyImport.objects.create(data=test) c_i.save() c_i.delete() But the CompanyImport still uses de default file storage, whereas the test is actually specifying the whole saved file (the code works). How to bypass default file storage to use FileSystemStorage with my model? -
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post\\/(?P<pk>[0-9]+)\\/$']
i wanted to update the django project but, I am having problem in detail post , update post and delete post My code goes here : I tried lots of thing , none worked. I posted all my project files below. you can have look. I would be glad if you guys helps me. home.html {% for droplet in droplets %} <tr> <td>{{ droplet.id }} </td> <td>{{ droplet.name}}</td> <td>{{ droplet.identifier }}</td> <td>{{ droplet.description}}</td> <td>{{ droplet.visibility}}</td> <td>{{ droplet.name_with_namespace }}</td> <td>{{ droplet.name_customer}}</td> <td>{{ droplet.status}}</td> <td>{{ droplet.created_at }}</td> <td> {% if user.is_authenticated %} <a class="btn btn-primary badge-pill" href="{% url 'post-detail' post.id %}"> <i class="fa fa-eye"></i></span> <a class="btn btn-secondary badge-pill" href="{% url 'post-update' post.id %}"><i class='far fa-edit'></i></a> <a class="btn btn-danger badge-pill" href ="{% url 'post-delete' post.id %}"> <i class='far fa-trash-alt'></i></a></td>{% endif %} </tr> </tbody> {% endfor %} urls.py urlpatterns = [ path('project/', GetDroplets.as_view(template_name='blog/home.html'), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), ] views.py class GetDroplets(TemplateView): template_name = 'blog/home.html' def get_context_data(self, *args, **kwargs): context = { 'droplets' : get_droplets(), } return context -
Pytorch Import Error when deploying django on AWS
My django app works locally. When i try to deploy it and then open it on AWS, i get the following error: I included torch==1.5.1 in my requirements.txt Requirements.txt: When I comment out the parts of the application that require torch and remove it from requirements.txt, it works fine. What can I do to ensure that torch is installed like the other modules in requirements.txt? -
Real time chat (Kotlin client , Python server)
I have to do a real time chat using Django framework (back-end) and Kotlin android (front-end). After reading tons of tutorials from internet, I used channels redis in django framework, where I describe it in consumers.py From the cmd, it shows server has no problem. For front-end, IO.socket is used to connect to server. However, socket is always null. It does not even show anything from the server's cmd. May I know what did I do wrong? Thanks a LOT if you can help with this T.T try { mSocket = IO.socket("http://127.0.0.1:8000/chat/c40484d0afda43b/") Log.d("success", mSocket.id()) println("connected: " + mSocket.connected()) } catch (e: Exception) { e.printStackTrace() Log.d("fail", "Failed to connect" + e) } From my consumer.py, I will take the param(c40484d0afda43b) as my roomName. server cmd(runserver) -
Import module that depends on module with same name
My project is based on django and in one app I want to import another module. I installed the module with pip and I'm importing it: from django.conf import settings from problematic_package.app.templatetags import test The issue is that problematic_package is also django based and in test.py they have: from django.conf import settings ... Here python will think settings is actually the object from my django project, instead of the imported one. I can't change the project installed with pip. What other solutions do I have? -
how to get list of users that have posts in django?
I'm trying to get a list of Users that have created at least one Post object. I want to do something like users = User.objects.filter(posts__not_null) How can I do this? models.py class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) Thanks! -
DETAIL: Key (user_id)=(1) is not present in table "auth_user". )
I'm trying to use Django AbstractBaseUser for my member area. When I try to add a new super user, I get this error : The above exception (insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". ) I don't know where is my mistake. I think this is about the app rest_framework.authtoken which doesn't work correctly... This is my code : settings.py INSTALLED_APPS = [ 'users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } AUTH_USER_MODEL = 'users.Account' models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import RegexValidator from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token ... class MyAccountManager(BaseUserManager): def create_user(self, name, username, email, phone, password=None): if not name: raise ValueError("User must have a name") if not username: raise ValueError("User must have an unique username") if not email: raise ValueError("User must have an unique email address") if not phone: raise ValueError("User must have a phone number") user = self.model( name = name, username = username, email = self.normalize_email(email), phone = phone, ) user.set_password(password) user.save(using = self._db) return user def … -
Jupyter notebook hanging due to Django runserver
Some time ago I made a simple Django application. Recently, I started using Jupyter notebooks for Python and was wondering if I could run my application from such a notebook. To test that, I opened a new notebook and navigated to the top directory of the application: %cd d:\adressen To see if the application could be run from the notebook, I first tried: !py manage.py makemigrations It returned, as it should: No changes detected So far so good. Now starting the server: !py manage.py runserver In a sense nothing happend. No output, the cell label still showing as In[*]. Nevertheless, the server was running, for if I opened in my webbrowser the page http:\\localhost:8000, my application turned up and all features were working. I fail to see why in the notebook makemigrations is handled correctly and runserver makes it hanging. The Jupyter console did not show anything that could have gone wrong. Having looked at some other questions and answers about Jupyter and Django, I installed django-extensions and included it in the installed apps. That did not help. When I start Jupyter with python manage.py shell_plus --notebook, open a new notebook and use the same commands, the same happens. Any … -
How to get dynamic choices field in admin panel of django- category sub-category
I have tried this a lot and searched about it too but not found any solution, I want that in admin panel when admin selects the category choice field and the subcategory choice field changes according to it, like I have a category called 'Shoes' and 'watches' and sub-category accordingly for shoes - 'puma', 'Adidas' and watches-'titan', 'G-shock'. when admin selects category 'shoes' subcategory choices should be 'puma' and 'Adidas' and if he/she selects category 'watches' subcategory choices should be 'titan' and 'G-shock'. here is my models.py from django.db import models from django.db import connection # Create your models here. class categorie(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class sub_categorie(models.Model): sub_name = models.CharField(max_length=100) catagory_name = models.ForeignKey(categorie, on_delete=models.CASCADE, default=1) def __str__(self): return self.sub_name class Products(models.Model): Product_Name = models.CharField(max_length=100) price = models.FloatField() Description = models.TextField() ctg = models.ForeignKey(categorie, on_delete=models.CASCADE,blank = False, default=1) sub_category = models.ForeignKey(sub_categorie, on_delete=models.CASCADE,blank = False) -
geodjango gdal 3 coordinates order changes
Ive been setting an existing geodjango project in ubuntu 20.04, and the existing databases, fixture created, are all read backwards, (lat, long) (long,lat), I finally found the change and its the gdal verison, I was working with the 2.4 version, in ubuntu 20 I have the gdal version 3, and the change seems to be intended: GDAL 3.0 Coordinate transformation (backwards compatibility (?)) as a workaround there is a SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER) method my question is, how do I setup my project for existing and new models being read correctly?, since the backwards reading exist in the admin, pages, serializers, etc thanks -
Parse data from ajax call to Django view
I was coding a super simple chat app on Django, and using an Ajax load() function to query all messages on a database based on the user and the printing them on the screen, but now I was wondering if there's a way of handling the data that Ajax receives with a Django view itself. This is the current views.py: def app(request): if request.method == 'POST': form = NewMessage(request.POST) if form.is_valid(): msg = form.cleaned_data.get("message") to = form.cleaned_data.get("to") sender = form.cleaned_data.get("sender") sent = form.cleaned_data.get("sent") print(msg, to, sender, sent) form.save() return render(request, 'app/app.html') def messages(request): messages = Message.objects.filter(to=request.user.address) messages_json = [{'message':message.message, 'sender':message.sender, 'receiver':message.to, 'sent':str(message.sent)} for message in messages] data = json.dumps(messages_json) #return render(request, 'app/app.html', context={'messages':data}) return HttpResponse(data, content_type='application/json') And this is the current ajax call on app.html: setInterval(function(){ $.ajax({ url: 'http://127.0.0.1:8000/messages/', dataType:'json', success: function(data) { var div = document.getElementById('mydiv').innerHTML = JSON.stringfy(data) } }, error: function(data) { console.log(data) } }); }, 3000); This actually works without any issues, but I just want to know if there would be somehow to set this on Django views.py: def messages(request): messages = Message.objects.filter(to=request.user.address) messages_json = [{'message':message.message, 'sender':message.sender, 'receiver':message.to, 'sent':str(message.sent)} for message in messages] data = json.dumps(messages_json) return render(request, 'app/app.html', context={'messages':data}) So that everytime the ajax call … -
Python manage.py runserver keeps loading
Im using Atom ide for django project. It runs the python maange.py runserver command but can't established connection ....server keeps loading ....please help -
Django Custom User Admin field_sets not showing in admin portal
I am creating a custom user class for my data base but I can't get my custom fields to show in the admin portal when adding a new user or changing an existing user. I have registered the app in my settings, migrated the data base, and set the AUTH_USER_MODEL in my settings.py. Thank you! My admin portal looks like this: And my files look like this: models.py from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ import secrets from api_keys.managers import * class User(AbstractBaseUser, PermissionsMixin): FULL = 4 MAJOR = 3 MINOR = 2 CONTROLLED = 1 access_groups = [(FULL, 4), (MAJOR, 3), (MINOR, 2), (CONTROLLED, 1)] username = models.CharField(_('user name'), max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=50, blank=True) last_name = models.CharField(_('last name'), max_length=50, blank=True) account_name = models.TextField(_('account'), max_length=500, blank=True) purpose = models.TextField(_('purpose'), max_length=5000, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff'), default=False) access_group = models.IntegerField(_('permission group'), choices=access_groups, default=CONTROLLED) api_key = models.CharField(_('api key'), max_length=100) delete_on = models.DateField(_('deletion date'), blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'access_group'] def save(self, *args, **kwargs): if not … -
Django ChoiceField. How to pass initial value to the form
Sorry, I am a beginner. How to pass the variable / value x = "ABCDE" to the form? #views.py ... x = "ABCDE" form1 = KSS_Form1(initial={'x':x}) context = {'form':form1, **context} return render(request, 'af/size/01_kss_size2.html', context) #forms.py class KSS_Form1(forms.Form): mat_geh_innen = forms.ChoiceField(choices=[], widget=forms.Select()) def __init__(self, *args, **kwargs): super(KSS_Form1, self).__init__(*args, **kwargs) self.initial['mat_geh_innen'] = x self.fields['mat_geh_innen'].choices = \ [(i.id, "Housing: " + i.mat_housing.descr) \ for i in afc_select_housing_innenteile.objects.filter(Q(series__valuefg__exact=x) & Q(anw_01=True))] as for now I get an error message Exception Value: name 'x' is not defined How shall I pass 2, 3, or more values if I have a number of different ChoiceFields in the Form? Thank you