Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python gets 'permission denied' to a file in Linux
I have a method to log actions on a json file: def log(self, action, data): import json import os current_directory = os.path.dirname(os.path.realpath(__file__)) try: with open(current_directory+'/logs/log_'+str(data['id'])+'.json', 'a+') as outfile: log_data = { str(datetime.today()): { 'action': action, 'data': data } } json.dump(log_data, outfile, indent=2) except Exception as e: print('\033[91m'+"Couldn't access log file to log changes in Reservation model: [{}]".format(str(e))+'\033[0m') print('Current directory is {}'.format(os.path.dirname(os.path.realpath(__file__)))) It works locally on my mac, but it always returns permission denied in Linux server. The logs directory permissions is set to 755 with chmod, but I still get the same error: [Wed Nov 28 16:27:23.551207 2018] [wsgi:error] [pid 18955:tid 139905951835904] [remote 189.149.229.31:63243] \x1b[91mCouldn't access log file to log changes in Reservation model: [[Errno 13] Permission denied: '/home/axel/IntellibookProject/Intellibook/ReservationsManagerApp/logs/log_43.json']\x1b[0m [Wed Nov 28 16:27:23.551346 2018] [wsgi:error] [pid 18955:tid 139905951835904] [remote 189.149.229.31:63243] Current directory is /home/axel/IntellibookProject/Intellibook/ReservationsManagerApp -
Django background task - Object of type 'WSGIRequest' is not JSON serializable
I'm in need of running a background task using the django module. I have succesfully created my script and when I try to load my views with the background task, I receive the following exception value Object of type 'WSGIRequest' is not JSON serializable. My code looks like the following. from django.shortcuts import render import uuid import subprocess import sys import os import time from callgolem.models import Usertasks from background_task import background from django.contrib.admin.views.decorators import staff_member_required # Create your views here. @background(schedule=60) @staff_member_required def index(request): os.chdir("C:/Users/kr85m/Google Drive/gitlab/renderwithgolemnew/var/taskqueries") logfilnavn = str(uuid.uuid4()) logfile = open(logfilnavn, 'w') proc=subprocess.Popen(['golemcli', 'tasks', 'show'], universal_newlines=True, stdout=logfile, stderr=logfile) print(proc) outfile = "clean.txt" findstatus = ['Waiting', 'Finished', 'Timeout'] delete_list = ["id ETA subtasks status completion", "------------------------------------ ------- ---------- -------- ------------", " 100.00 %", " 0.00 %", " ??? 1 ", "0:00:00 1 "] fin = open(logfilnavn) fout = open(outfile, "w+") proc.wait() for line in fin: for word in delete_list: line = line.replace(word, "") fout.write(line) fin.close() fout.close() with open(outfile, 'r') as f: for lines in f: taskidlinjer = (lines[:36]) print(taskidlinjer) printstatus = lines for taskstatus in printstatus.split(r"\r\n"): # split here by _literal_ \\r\\n if any(word in taskstatus for word in findstatus): removebloat = str(*set( taskstatus.split() ) & set(findstatus)) print(removebloat) Usertasks.objects.filter(TaskID=taskidlinjer).update(TaskStatus=removebloat) … -
Integrating datetime picker into Django Crispy forms
I have the following code (HTML/JavaScript) which is a form input for a datetime picker. main.html <div class="form-group"> <div class='input-group date' id='datetimepicker1'> <input type='text' class="form-control"/> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> forms.py class MainForm(forms.Form): gender = forms.CharField(label='Template', widget=forms.Select(choices=GENDER)) first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') address = forms.CharField(label='Address') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('gender'), Field('first_name'), Field('last_name'), Field('address'), Submit('submit', 'Submit', css_class='btn-success') ) My question is how do I integrate/add/use the above datepicker HTML in my DJango Crispy form? Ideally I would like to add "date of birth" to my forms.py MainForm and use the datepicker. Please could someone suggest how I can do this? -
what's the advantage of using react+django rather than using only django?
I'm studying to develop a website. As I searched, Django can develop a whole website itself. What I wonder is why some people use React and Django together. What's the advantage of using those both programs, rather than just using one? And I also want to know the difference between Django and Django Rest. I want to make a website for selling something, then which do you recommend? -
duplicate model instance with all related objects
Hi there !! As stated in the title I'm trying to clone a model instance with all the related objects I have two models : class VersionContrat(models.Model): nom_version = models.CharField(max_length=25, blank=True, null=True) version = models.IntegerField() and : class Vacation (models.Model): poste_travail = models.CharField(max_length=50, default='') version_contrat = models.ForeignKey(VersionContrat, on_delete=models.CASCADE, default=9) date_debut = models.DateField(blank=True, null=True) date_fin = models.DateField(blank=True, null=True) I tried this method in VersionContrat to copy a VersionContrat object and all the Vacation objects related with the foreign key: def duplicate(self): vacations = Vacation.objects.filter(version_contrat=self) self.pk = None self.version = int(self.version)+1 self.save() for vacation in vacations: vacation.pk = None vacation.version_contrat = self vacation.save() return print('clone to {}'.format(self)) But it doesn't work and I can't find out why, anyone has an idea why ? -
django Multiple form submit in UpdateView
I want to update the built-in User model along with the Profile (user extended) model. this is forms.py: class UserUpdateForm(forms.ModelForm): class Meta: model = auth_models.User fields = ['first_name', 'last_name', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['date_of_birth'] this is my view.py: class ProfileUpdateView(LoginRequiredMixin, generic.UpdateView, MultiModelForm): model = Profile fields = '__all__' def get_object(self, *args, **kwargs): username = self.request.user return get_object_or_404(Profile, user__username__iexact=username) def get_success_url(self): return reverse('accounts:profile') This just edits Profile fields. I also tested django-betterforms but couldn't make it work. I could show 2 forms with get_context_data() but I couldn't save to model and that was just HTML. I just want to know how get_object for the second form? -
How to point django to put a template in the front page
I am trying to learn python in the django framework, I took a course, but it was based on an earlier version of django while I am using Django 2.1.3 and python 3.7.0, so I've got errors.My question is how can I point urls.py to take an html template and put it in the main page in this version of Django? Thank you!! -
How to save form input in database for multiple inputs at the same time in django?
I am learning django and am creating an application that can register the students in a particular class based on their name and registration number. So, I created an application where the user can add form elements from where the user can add options to add different students directly into the form at the same time. Thus, the user can decide the number of student he wants to add at the same time, and add the students by their name and registration number. I have created the following form: <form method="post" action="/add_rules/"> {% csrf_token %} <div class="field_wrapper"> <div> <label>Enter Name</label> <input type="text" name="personname"> <label>Enter registration number</label> <input type="text" name="personregnumber"> <a href="javascript:void(0)" class="addPerson">Add</a> <br><br> </div> </div> <button type="submit">Submit</button> </form> The corresponding javascript to add and remove the input fields is: $(document).ready(function () { var addButton = $('.addPerson'); var wrapper = $('.field_wrapper'); var field_html = '<div><label>Enter name</label><input type="text" name="personname"><label>Enter registration number</label><input type="text" name="personregnumber"><a href="javascript:void(0)" class="remove_button">Remove</a><br><br></div>' $(addButton).click(function() { $(wrapper).append(field_html); }) $(wrapper).on('click', '.remove_button', function(e) { e.preventDefault(); $(this).parent('div').remove(); }) }) I am stuck at how to add multiple student data fields to the data base at the same time? It will be great if someone could help -
django-allauth with Django v2+ custom user model and custom user manager
Note: As of writing this there are 197 questions when searching for "django-allauth custom user". I have not read all of them, but of the several I have read, these were notable: How to customize user profile when using django-allauth Django allauth custom login form not rendering all fields in custom user model Saving custom user model with django-allauth where the questions' authors have implemented custom user models, with no difficulty, but want to modify things like the login form. In addition, I have read and completed the official Django tutorial, the mozilla Django tutorial, and this very great post by Will Vincent (which introduced me to the django-allauth. Lastly, I also consulted the django-allauth docs. I would like to focus on the tutorial by Will Vincent, as I find it the most extensive of the several out there; notably it bothers to make a custom user model. For those who have not read the entire tutorial, at [this point]]Will Vincent User Model an app was created named users and in the file <project>/users/models.py we have a custom user model: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() Is this the most sophisticated custom user … -
Image uploaded increases size in Django-CMS
I've got a django-cms plugin with a image field and I've noticed that the size of the images I upload using this plugins is bigger than the originals one. This can't happen, do you have any idea what could be causing this? Could it be some kind of configuration? The definition of the field in the models.py: image = models.ImageField(db_column='IMAGE', verbose_name=_(u'Image (1280x600)'), upload_to='Destaques') This is a snippet of the template where I render the image: {% load cms_tags staticfiles i18n %} {% load thumbnail %} {% thumbnail instance.imagem '1660' as im %} <div class="item" id="item_{{ instance.id }}" style="background: url('{{ im.url }}') no-repeat center / cover;"> Could it be because of the thumbnail generation? Thank you :) {% endthumbnail %} -
Generic Class-Based Models for MySQL, works like Django's Migration System
Recently I have been using Django, and one of the features I like the best are the class-based models ( table definitions ) and the related "migration" system. This comes in super handy when working between the development and production environments. I have a legacy system which I work on which uses PHP but isn't created within any fixed framework. There is a MySQL database. I currently just create the database tables manually. The issue that I am running into is when going between development and production environment, I don't have any complete system to manage the database table definitions. I would like to have something like Django's models and migrations system, so I could make changes to the database model and propagate changes to development and production environments independently. I am looking for a system that works like the Django system, but it doesn't need to be in any specific programming language, PHP would be nice. Also it would be helpful that I could create the initial classes automatically to match what I have already, since I have hundreds of tables. I know this isn't a specific question, but the SO community always helps me so much I wanted … -
Docker&Celery - ERROR: Pidfile (celerybeat.pid) already exists
Application consists of: - Django - Redis - Celery - Docker - Postgres Before merging the project into docker, everything was working smooth and fine, but once it has been moved into containers, something wrong started to happen. At first it starts perfectly fine, but after a while I do receive folowing error: celery-beat_1 | ERROR: Pidfile (celerybeat.pid) already exists. I've been struggling with it for a while, but right now I literally give up. I've no idea of what is wrong with it. Dockerfile: FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/djangoapp/src COPY /scripts/startup/entrypoint.sh entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/ WORKDIR /opt/services/djangoapp/src RUN pip install pipenv && pipenv install --system COPY . /opt/services/djangoapp/src RUN find . -type f -name "celerybeat.pid" -exec rm -f {} \; RUN sed -i "s|django.core.urlresolvers|django.urls |g" /usr/local/lib/python3.7/site-packages/vanilla/views.py RUN cp /usr/local/lib/python3.7/site-packages/celery/backends/async.py /usr/local/lib/python3.7/site-packages/celery/backends/asynchronous.py RUN rm /usr/local/lib/python3.7/site-packages/celery/backends/async.py RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/redis.py RUN sed -i "s|async|asynchronous|g" /usr/local/lib/python3.7/site-packages/celery/backends/rpc.py RUN cd app && python manage.py collectstatic --no-input EXPOSE 8000 CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app", "example.wsgi:application", "--reload"] docker-compose.yml: version: '3' services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static # <-- bind the static volume - media_volume:/opt/services/djangoapp/media # <-- bind the media … -
Foreign key in the database
I have a problem, I have a Pessoa table and a Veiculo table, and a MovRotativo table, but when I register in MovRotativo I need to select Pessoa X only the Veiculo of Pessoa X is listed. How are you now I'm selecting Pessoa X and I can put person's Veiculo Y and wanted to solve this by model.py I'm using sqllite 3 that comes in django model.py class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7) placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False) cor = models.CharField(max_length=15, blank=False) observacoes = models.TextField(blank=False) def __str__(self): return self.modelo + ' - ' + self.placa class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) email = models.ForeignKey(Pessoa, on_delete=models.CASCADE, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) -
ModuleNotFoundError Django
This is my "views.py" code : from .models import Post from .forms import postForm #the problem is in here !! def post_create(request): #list items form = postForm() #creation of a variable form context = { "form":form, #form is the name of the variable we are going to call } return render(request,'post_form.html', context) On "forms.py" I have : from django.db import models from django import forms from .models import Post class postForm(forms.Form):#forms.ModelForm): class Meta: #this is an inner class, we do this to make our project more orientated model = Post fields = [ #Here, I can add all of the fields that are in my model Post to the Form "title", "text" ] enter code here the problem is when I run the server I get this error : from . import views File "C:\Users\fatiha\djangoSite\blog\views.py", line 5, in from .forms import postForm #the problem is in here !! ModuleNotFoundError: No module named 'blog.forms' I tried to replace the from .forms import postForm with blog.forms ... but it didnt work, when I comment the #from .forms import postForm I dont get no error, any help please -
Multiple forms in forms.py
This is a Django project. forms.py class BigForm(forms.Form): template = forms.CharField(label='Template', widget=forms.Select(choices=CHOICES)) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('template'), Submit('submit', 'Submit', css_class='btn-success') ) class DateForm(forms.Form): start_date = forms.CharField(label='Start date') end_date = forms.CharField(label='End date') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('start_date', css_class='form-control'), Field('end_date', css_class='form-control') ) views.py def myForm(request): main_form = BigForm() date_form = DateForm() return render(request, 'polls/main.html', {'main_form': main_form, 'date_form': date_form}) Is there something wrong with this? I keep getting KeyError: "Key 'end_date' not found in 'BigForm'. Choices are: template." I just want two separate form classes (for two separate forms) -
How to know some object's order in django queryset
qs1 = QueryModel.objects.all().order_by('?') obj1 = QueryModel.objects.get(pk=123) def order_stuff(queryset, obj) return print(#obj_order_from_queryset) order_stuff(qs1, obj1) >>> some ordering number How to know some object's order on some queryset? For example, if queryset are like: print(qs1) >>> {'pk': 1}, {'pk': 3}, {'pk': 4}, {'pk': 123} ... So that: order_stuff(qs1, obj1) >>> 4 if queryset are like: print(qs1) >>> {'pk': 123}, {'pk': 3}, {'pk': 4}, {'pk': 13} ... So that: order_stuff(qs1, obj1) >>> 1 if queryset are like: print(qs1) >>> {'pk': 13}, {'pk': 123}, {'pk': 4}, {'pk': 13} ... So that: order_stuff(qs1, obj1) >>> 2 How to do this? -
Difference between range and lte/gte django filters
I am using filters for a model with following two ways: Model.objects.filter(created_date__gt=datetime(2018, 1, 11, 00, 00, 00), created_date__lte=datetime(2018, 11, 11, 23, 59, 59), user_id=135) And Model.objects.filter(user_id=135, created_date__range=["2018-11-1 00:00:00", "2018-11-11 23:59:59"]) When i check the count of the both filters there is huge difference of count. The main question is what is difference between range and gte/lte in filters ? -
Django : CommandError: You appear not to have the 'mysql' program installed or on your path
I'm trying to setup a django project with mysql backend . I have my environment variable set , so i'm able to run mysql command from the command prompt. Following settings have been done in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'anprgatedcommunity', 'USER': 'root', 'PASSWORD': 'root123', 'HOST': 'localhost', 'PORT': '3306', } } when i try to run python manage.py dbshell it throws me CommandError: You appear not to have the 'mysql' program installed or on your path. error. -
groups.Groups.created_by: (fields.E303) Reverse query name for 'Groups.created_by' clashes withfield name 'User.groups'
I am trying to migrate these two models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. # Groups Model class Groups(models.Model): grp_name = models.CharField(max_length=100) grp_status = models.CharField(max_length=100) grp_description = models.TextField() created_on = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) members = models.ManyToManyField(User, through='UserGroup') def __str__(self): return self.grp_name #user groups class UserGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Groups, on_delete=models.CASCADE) date_joined = models.DateTimeField(default=timezone.now) But I have got this error: ERRORS: groups.Groups.created_by: (fields.E303) Reverse query name for 'Groups.created_by' clashes withfield name 'User.groups'. HINT: Rename field 'User.groups', or add/change a related_name argument to the definition for field 'Groups.created_by'. groups.Groups.created_by: (fields.E304) Reverse accessor for 'Groups.created_by' clashes with reverse accessor for 'Groups.members'. HINT: Add or change a related_name argument to the definition for 'Groups.created_by' or 'Groups.members'. groups.Groups.members: (fields.E303) Reverse query name for 'Groups.members' clashes with fieldname 'User.groups'. HINT: Rename field 'User.groups', or add/change a related_name argument to the definition for field 'Groups.members'. groups.Groups.members: (fields.E304) Reverse accessor for 'Groups.members' clashes with reverseaccessor for 'Groups.created_by'. HINT: Add or change a related_name argument to the definition for 'Groups.members' or 'Groups.created_by'. I want to make many-to-many relationship between the users and groups. That is the users can be in … -
django_otp custom OTP Middleware does not detect an already authenticated user
I want to add OTP verification by using the django_otp library. Per each request I want to verify if the user has been initially authenticated and in that case check whether it has any OTP device associated. I have manually implemented the API endpoint for the OTP device creation and it successfully creates the device and associates to the user used for the creation. This is my simplified MIDDLEWARE stack MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'otp.middleware.FMSOTPMiddleware', ) First the AuthenticationMiddleware would add the user object to the request, and then the OAuth2TokenMiddleware would authenticate() the user against the backend. The code for the FMSOTPMiddleware middleware is: class FMSOTPMiddleware(OTPMiddleware): def process_request(self, request, *args, **kwargs): super().process_request(request, *args, **kwargs) user = request.user print(user) print(user.is_authenticated) The OTPMiddleware from django_otp adds the user.otp_device attr and user.is_verified() method. After manually adding the OTP device and calling this methods it works properly, but from within the middleware user always returns AnonymousUser. -
Django: Manage execution of same script by different users
I have a script that is generating some excel reports from my django database. Currently the script is scheduled in cron and runs every 15 minutes and it backs up the reports from previous run and puts in into our backup dump. What I need to do is instead of it running every 15 minutes, provide a button that executes the script so the users can run it as and when required. But the problem would be if multiple users try to generate the report around the same time because the same script will run one after the other on the same server. Is it possible to somehow manage this? Like if the script is already running, block the other user from running it again or lock the script? I read somewhere that celery and rabbitmq can be used for this but that looks like an overhead. Any help is appreciated! Thanks. -
Django tests display traceback of expected exception in assertRaises
I'm testing a django view with APIClient. One of the test cases checks whether an exception is raised: self.assertRaises( IntegrityError, self.client.post, path='/some/url/to/view/', data={ 'test': 'data' }, format='json' ) Although the test passes, the client call raises the expected exception with printing the full traceback. Can I somehow change this behaviour? I don't want to see numbers of tracebacks in my test run as this is a common test case. -
django chaning filter continuously
I'm trying to make continuous django filtering. Let's assume that I have some model: class TextModel(models.Model): text = models.TextField(max_length=1000, null=True, blank=True, default=None) created = models.DateTimeField(auto_now_add=True) And now, I'll make TextModel's objects like it: {'text': '1'}, {'text': '2'} ... {'text': '99'}, {'text': '100'} Here starts what I want to do. I'll find objects that text field include '1' by 4 Querysets. As you know final result will be this: {'text': '1'}, {'text':'10'}, {'text':'11'} ... {'text':'91'}, {'text':'100'} Maybe it's length will be 20? maybe 20 result. I want to make this result divided by 4 Querysets that has 5 results individually. And I want to make results be ordered by their text length, not pk or created. But if text length is the same, then it is good to be ordered by 'pk' or 'created'. Most urgent ordering standard is text length I tried: from django.db.models import TextField from django.db.models.functions import Length TextField.register_lookup(Length) qs1 = TextModel.objects.filter(Q(text__icontains='1')).order_by( Length('text').asc(), 'pk')[:5] qs2 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs1.last().text)).order_by( Length('text').asc(), 'pk')[:5] qs3 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs2.last().text)).order_by( Length('text').asc(), 'pk')[:5] qs4 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs3.last().text)).order_by( Length('text').asc(), 'pk')[:5] This has failed. Because qs2 also has the result that is also in qs1. To prevent this, I thought this way: qs1 = … -
How to relate fields in Django Admin?
In a model, I have a DecimalField "first_arg", and a multiple choice CharField "second_arg". I'd like to achieve the following: In the admin panel, if a particular option (let's say "B") is selected for "second_arg" field, increment any value that is inserted to "first_arg" form field by 2. What's the right way to go about it? Since it's part of the admin UI, modifying the model should be wrong. On the other hand, I couldn't find anything about it in the documentation. I thought about simply using some JS in a static file, but that's kinda hacky. Is there an elegant way to do these things in Django Admin? Model code: class MyModel(models.Model): first_arg = models.DecimalField( max_digits=4, decimal_places=2, blank=True, null=True ) second_arg = MultipleChoicesField( models.CharField( choices=constants.RELEVANT_OPTIONS, max_length=20 ), blank=True, null=True ) class Meta: abstract = True # The following is irrelevant for the question, just to prevent any confusion: class MultipleChoicesField(ArrayField): def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) return super(ArrayField, self).formfield(**defaults) a = "a" b = "b" etc = "etc" RELEVANT_OPTIONS = ( (a, "A"), (b, "B"), (etc, "etc") ) -
Cleaning up CBV
I've got this class which works as intended class UpdateView(TemplateView): def get(self, request, username): id = User.objects.get(username = username).id user = get_object_or_404(User, id = id) employee = get_object_or_404(Employee, user_id = id) form_user = UserForm(instance=user) form_employee = EmployeeForm(instance=employee) args = {'form_user': form_user,'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) def post(self, request, username): id = User.objects.get(username = username).id user = get_object_or_404(User, id = id) employee = get_object_or_404(Employee, user_id = id) form_user = UserForm(request.POST, instance=user) form_employee = EmployeeForm(request.POST, instance=employee) if form_user.is_valid() and form_employee.is_valid(): form_user.save() form_employee.save() return redirect('user:list') args = {'form_user': form_user, 'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) My issue is that both the get and post methods use the same id, user and employee variables. How can I clean this up? I know I can create a render method like def render(self, request, username): args = {'form_user': form_user, 'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) and then call return self.render(request) at the end of the get and post methods, so I don't have to define the args twice either, but currently this conflicts with the username. That's why I want to tackle the problem with the 3 variables first.