Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-storges support for CloudFront signed URL
I want to use CloudFront's signed URLs rather than plain unsigned URLs. django-storages gives the option of AWS_S3_CUSTOM_DOMAIN but then it generates unsigned URLs from CloudFront's subdomain. By default AWS_QUERYSTRING_AUTH is True and it does generate signed URLs for S3. Any way to generate signed URLs for CloudFront. This is the setting I am looking to turn on, but due to unsigned URLs I disabled it. Settings I am looking to turn on for My distribution -
Getting this name error whilst using django-taggit: name 'Tag' is not defined
For my website, I want users to be able to add tags to their posts. But I get this error: python name 'Tag' is not defined Here is some code Relevant code in models.py from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) Here is the relevant code in views.py class TagMixin(object): def get_context_data(self,**kwargs): context = super(TagMixin,self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class PostListView(TagMixin,ListView): template_name = 'mainapp/post_list.html' model = Post context_object_name = 'posts' queryset = Post.objects.all() def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class TagIndexView(TagMixin,ListView): template_name = 'mainapp/post_list.html' context_object_name = 'posts' model = Post def get_queryset(self): return Posts.objects.filter(tags__slug=self.kwargs.get('slug')) And here is the form. class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','image','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False I am getting the error in the Mixin, on this line python context['tags'] = Tag.objects.all() Can anyone tell me why I am getting an error of python name 'Tag' is not defined So far I have changed the … -
Access JavaScript variable from Django template
I have an HTML combobox which needs to be dynamically constructed upon page loading, and I need to do something like this: <select id='sort-combobox'> <option value='1' {% if sesionStorage.getItem('sortFilter') == 1 %} selected {% endif %}>Newest</option> <option value='2' {% if sesionStorage.getItem('sortFilter') == 2 %} selected {% endif %}>>Price ASC</option> <option value='3' {% if sesionStorage.getItem('sortFilter') == 3 %} selected {% endif %}>Price DESC</option> </select> How can I access sessionStorage.getItem('sortFilter') from Django template? -
Django model for seat booking
I am trying to design Django model for booking website. Anyone can book any seats My Logic is simple, if a seat booked already, it can't be booked later, user can unbook. i stuck here: from django.db import models from enum import Enum class Seat(Enum): AA = 1 AB = 2 BA = 3 BB = 4 CA = 5 CB = 6 class Hall(models.Model): """ there 6 seats in a hall """ seat = models.CharField(choices=Seat, max_length=2) class Booking(models.Model): I hope you got my problem. I can handle in frontend like, all the 6 seats will be presented, if user click on a seart, it will be booked and if they clicked on booked seat, it will be unbooked, this is not a big deal to handle. My problem is only backend, i am stuck in writing the models like if a seats booked already, it cant be booked again but it can be unbooked only Can anyone please help me to write this models? -
Sign in required when accessing gcloud API
I am building an app that uses the dialogflow API, and I am having the following issue, the API requires my Gcloud user credentials (login and password) when calling a specific method Which is weird because, I am using the same API to have different kind of data and I don't need to enter my user credentials for other requests. def get_training_phrases(project_id, intent_id): client = dialogflow.IntentsClient() intent = client.get_intent("projects/agent-mikael-gtjdma/agent/intents/{}".format(intent_id), intent_view=dialogflow.enums.IntentView.INTENT_VIEW_FULL) new_intent = json.loads(MessageToJson(intent)) intent_name = new_intent['displayName'] training_phrases = [] for training_phrases_part in new_intent['trainingPhrases']: txt = training_phrases_part['parts'][0]['text'] training_phrases.append(txt) print(training_phrases) return training_phrases, intent_name ```settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' PROJECT_DIR = BASE_DIR.replace(str(Path('server/django/Assistant_configuration')), '') os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = PROJECT_DIR + str(Path('/agent-mikael-gtjdma-b21243f72b48.json')) I need to enter once my user credentials and the login is not longer required dring the whole session. -
File, Folder and Directory traversing of linux folers in Django and display in HTML
I am beginner in django and want to display linux server files and folders in html and want to traverse and come back to previous location when a 'back' button is clicked. Can anyone help me out with this? -
Bootstrap table - numbers in accounting format
How can I write numbers in a cell inside Bootstrap table in accounting format? For example: one million should be shown as 1,000,000 and not 1000000 (notice commas ',' between digits). Please note that data data is getting filled by Django app. Example: <tbody> {% for row in tbl_list %} <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.investment_amount}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> +{{row.weekly_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td>{{row.percentage}}</td> <td>{{row.percentage_of_portfolio}}</td> </tr> {% endfor %} </tbody> -
How to pass # in url as a parameter in django 2
I am trying to pass a code "Req-2019#000001" Django URL. I want to pass this code as well as normal string and number also in URL as arguments. path('generateBomForSingleProduct/<requisition_no>/' , views.generateBomForSingleProduct, name='generateBomForSingleProduct'), Its work properly but the problem is its add extra / before # My URL is now this http://127.0.0.1:8000/production/generateBomForSingleProduct/Req-2019/#000001 But I want to like this http://127.0.0.1:8000/production/generateBomForSingleProduct/Req-2019#000001 Not an extra "/" before my "#" -
Whats the best rest pattern for tradeable items in django?
I want to create a website where users can buy virtual items with virtual money. I would also like to use django_restframework with a proper design pattern. The Items should be able to be created for money under certain circumstances, bought and sold (in effect switch users) and liquidated (destroyed for money). So in total the owner can create, sell, buy and destroy his items. Since in essence rest is supposed to create, post,put, patch and delete objects, how can I most elegantly feat the these four features into this pattern? Do I just allow the user to create and delete objects and override the ModelViewSet methods accordingly? Do I create 4 different post views that execute these operations? Do I allow the User to set the new owner of an item in a post request? Whats the most elegant solution here? -
How to submit post/put request to Django rest API via React front end?
I'm new to Django, this is hopefully an easy question for the advanced users. I'm trying to submit a post/put request to a nested object in Django rest API using a React form (front end). Below is how the nested object looks like, the table is called person. It's joins to the address table to get information such as street, suburb etc.. { "id": 3, "last_name": "Kidd", "first_name": "Jason", "address": [ { "id": 5, "street": "13 Sunrise Road", "suburb": "Greenhithe", "town": "Christchurch", "postcode": "2234", "address_type": "w" } ], "group": "Customer" } I used a package called drf_writable_nested to write to the nested object. This is the code for person serializer. from drf_writable_nested import WritableNestedModelSerializer class PersonSerializer(WritableNestedModelSerializer): last_name = serializers.CharField(required=True, max_length=100) first_name = serializers.CharField(required=True, max_length=100) address = AddressSerializer(many=True) class Meta: model = Person fields = ('id', 'last_name', 'first_name', 'address', 'group') Below is the front end code for handling the submit request, such pattern works fine if the object it submits to is flat (not nested). class ClientForm extends React.Component { handleFormSubmit = (event, requestType, id) => { event.preventDefault(); const last_name = event.target.elements.last_name.value; const first_name = event.target.elements.first_name.value; console.log(last_name, first_name); switch ( requestType ) { case 'post': return axios.post('http://127.0.0.1:8000/api/person/', { last_name: last_name, first_name: … -
Is there a way to register new users with Django registration templates that would prevent them from logging in until admin has manually reviewed?
I'm working on login/registration views in Django in a project that requires that the admin manually reviews the application before the user can actually login...while saving the information they provided at the registration page. In the past I didn't have projects that required the users be reviewed manually by the admins. def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) return index(request) else: form = UserCreationForm() return render(request, "registration/register.html", {"form": form}) This is what I would normally write...but even if I don't include the login(request, new_user), the new_user would be able to do so himself after the new_user is created... I need to make sure they still can't login until the admin has manually reviewed his application to join. -
Dockerfile Django not opening in browser
I'm using Django 2.x and dockerizing the application. I have the following Dockerfile content. FROM python:3.7-alpine # Install Rabbit-mq server RUN echo @testing http://nl.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories RUN apk --update add \ libxml2-dev \ libxslt-dev \ libffi-dev \ gcc \ musl-dev \ libgcc curl \ jpeg-dev \ zlib-dev \ freetype-dev \ lcms2-dev \ openjpeg-dev \ tiff-dev \ tk-dev \ tcl-dev \ mariadb-connector-c-dev \ supervisor \ nginx \ --no-cache bash # Set environment variable ENV PYTHONUNBUFFERED 1 # Set locale variables ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 # -- Install Application into container: RUN set -ex && mkdir /app # -- Adding dependencies: ADD . /app/ # Copy environment variable file ADD src/production.env /app/src/.env COPY scripts/docker/entrypoint.sh /app/ # Switch to the working directory WORKDIR /app RUN chmod ug+x /app/entrypoint.sh # Install Pipenv first to use pipenv module RUN pip install pipenv # -- Adding Pipfiles ONBUILD COPY Pipfile Pipfile ONBUILD COPY Pipfile.lock Pipfile.lock RUN pipenv install --system --deploy RUN mkdir -p /etc/supervisor.d COPY configs/docker/supervisor/supervisor.conf /etc/supervisor.d/supervisord.ini EXPOSE 80 8000 CMD ["/app/entrypoint.sh"] and the entrypoint.sh hash #!/usr/bin/env bash exec gunicorn --pythonpath src qcg.wsgi:application -w 3 -b 0.0.0.0:8000 -t 300 --max-requests=100 I use the command to build the image docker build . -t qcg_new and … -
How to literally get the `get_change_message` in `django.contrib.admin.models.LogEntry` in django 2.2
I've added a code in my view to log every add action in my add_new_staff page. Here's the code: message = f'New user added. Added staff profile for {user.first_name} {user.last_name}' log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(user).pk, object_id=repr(user.id), # or any field you wish to represent here object_repr=repr(user.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() In here, I only made a custom get message thru message string. And I think, for this add_staff_view it is ok to do this. But now, I'm working on my update_staff_profile_view and also, I need to log this action. I saw how the change/update form in django admin page inserts the change_message in LogEntry model and I can't think of ways to do it inside my own update_staff_profile_view. Any help would be really appreciated, thank you! -
Having a pull request conflict issue
I am trying to merge a branch with the master branch but my conflict is hard to resolve as it says use cmd line and with the cmd line options give it doesnt resolve the issue. Github is giving me this... Step 1: From your project repository, bring in the changes and test. git fetch origin git checkout -b static origin/static git merge master Step 2: Merge the changes and update on GitHub. git checkout master git merge --no-ff static git push origin master Then when i try it i get this output (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git fetch origin (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git checkout -b static origin/static fatal: A branch named 'static' already exists. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git merge master Already up to date. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git checkout master Switched to branch 'master' Your branch and 'origin/master' have diverged, and have 2 and 2 different commits each, respectively. (use "git pull" to merge the remote branch into yours) (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git merge --no-ff static Already up to date. (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT>git push origin master To fortress-sefa.git ! [rejected] master -> master (non-fast-forward) The conflicting files are DEMOPROJECT/__pycache__/__init__.cpython-37.pyc DEMOPROJECT/__pycache__/settings.cpython-37.pyc DEMOPROJECT/__pycache__/urls.cpython-37.pyc DEMOPROJECT/__pycache__/wsgi.cpython-37.pyc Is there a significance in the fact it is cache files? -
How do you render form from views in template without model?
I have a problem with my Django Code.I'm trying to render a form from views to template and it is not working. I noticed that we can use forms dynamically by introducing it like this {{ form }}, but it's not working. I join my four files: views.py, home.html, forms.py and urls.py Thank you in advance **home.html** {% csrf_token %} <fieldset> <legend class="border-bottom mb-4">Home</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> **views.py** def inputHome(request): form = InputHomeForm() if request.method == 'POST': form = InputHomeForm(request.POST) if form.is_valid(): mk = form.cleaned_data['mk'] return HttpResponseRedirect('blog-config') else: form = InputHomeForm() return render(request, 'blog/home.html', {'form': form}) **forms.py** class InputHomeForm(forms.Form): mk = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) **urls.py** urlpatterns = [ path('home/', blog_views.home, name='blog-home'), ] I don't have an error message so i don't have an idea of the problem -
how to upload large files in django temp directory location?
def handle_uploaded_file(f): with open('/home/arvind/Desktop/newupload/documents/'+f.name, 'wb') as destination: filepath = destination.name for chunk in f.chunks(): #time.sleep(1) destination.write(chunk) # def fileupload(request): if request.method == 'POST': files = request.FILES.getlist('uploadfile') for f in files: handle_uploaded_file(f) return HttpResponse('add') return HttpResponse("done") -
Getting Error in middleware for the mobileesp While porting python2 project to python3
I'm getting the error in the dependencies while porting python2 project with Django 1.1.11 to python 3.7 and Django 2.2.5 I'm using Django-mobileesp in the python2, when I have update the code to python3 it gives the error for the Middleware for the UserAgent. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/jarvis/Desktop/law3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/jarvis/Desktop/law3/src/lawersify/wsgi.py", line 5, in <module> application = get_wsgi_application() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 135, in __init__ self.load_middleware() File "/home/jarvis/Desktop/law3/lib/python3.7/site-packages/django/core/handlers/base.py", line … -
Django admin inline - show only when changing object
I have a UserProfile which has many required fields and I'm trying not to show it when adding user. I tried multiple things, for example: def get_formsets_with_inlines(self, request, obj=None): if not obj: return [] return super().get_formsets_with_inlines(request, obj) But after saving User, django raises error which says that fields from UserProfile can't be null. Do you know how to make it work? -
Djnago - getting two entries in the database, one with null and other with all data captured
I have a form and am updating the database with the form entries. I see that there are two rows getting updated one with NULL entries and other with all data. There is something wrong in my view but I don't know what, please help. models.py class Metadataform(models.Model): Models = models.CharField(max_length=5000, blank=True) Device = models.CharField(max_length=500, blank=True) Document = models.FileField(upload_to='') views.py def submission(request): Models = request.POST["Models"] Device = request.POST["Device"] Error_Estimation = request.POST["Error_Estimation"] if request.method == 'POST': form = Fileuploadform(request.POST, request.FILES) if form.is_valid(): form.save() newdoc = Metadataform(Document = request.FILES['Document']) newdoc.save() return render(request, "home.html") else: form = Fileuploadform() There are two-row entries in the database. 1 row with NULL entries and the uploaded file link, another row with all the data and the file link -
Change Session Table Name and Customize Django Session Table
My problem: I'm trying to change the Django session table name from "django_session" to some other name as "User_session" What I tried: from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" I placed the above code in Project's __init__.py file. But I'm getting error as calling session before the Session middleware has been initialized. What I want: I need to change the django_session table name to some other table name and add few columns to that table. NOTE: I'm using Django 2.1.11 and Python 3.7 Kindly help me to get rid off this problem. -
gunicorn not starting (code=exited, status=1/FAILURE) error
not able to start gunicorn in my server sock file is not creating in my project directry Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2019-09-16 09:35:37 UTC; 2s ago Main PID: 22932 (code=exited, status=1/FAILURE) Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [INFO] Starting gunicorn 19.9.0 Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:32 django gunicorn[22932]: [2019-09-16 09:35:32 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:33 django gunicorn[22932]: [2019-09-16 09:35:33 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:34 django gunicorn[22932]: [2019-09-16 09:35:34 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:35 django gunicorn[22932]: [2019-09-16 09:35:35 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:36 django gunicorn[22932]: [2019-09-16 09:35:36 +0000] [22932] [ERROR] Can't connect to Sep 16 09:35:37 django systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 16 09:35:37 django systemd[1]: gunicorn.service: Unit entered failed state. Sep 16 09:35:37 django systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
I am trying to install django in my windows system with the command "conda install django" , anaconda python3 is already installed and working fine
while installing the django I am getting this error "TypeError: LoadLibrary() argument 1 must be str, not None" and a very long exception, how can I solve this as it comes even when I am creating a virtual environment. I am learning Django and it was my first step so please answer accordingly. -
How to write a mixin in this case in order not to repeat the code
Django==2.2.5 There are three levels logically nested one inside another. The problem here is the repeating code in save method. Could you help me create a mixin not to repeat myself. class Level_1(PhraseMixin, ArchivedMixin, models.Model): def save(self, *args, **kwargs): """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_2_set = self.level_2_set.all() for level_2_obj in level_2_set: level_2_obj.archived = True level_2_obj.save() super(Level_1, self).save(*args, **kwargs) class Level_2(ArchivedMixin, PhraseMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_1, verbose_name="Level 1", on_delete=models.CASCADE) """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_3_set = self.level_3_set.all() for level_3_obj in level_3_set: level_3_obj.archived = True level_3_obj.save() super(Level_2, self).save(*args, **kwargs) class Level_3(PhraseMixin, ArchivedMixin, WhereMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_2, verbose_name="Level 2", on_delete=models.CASCADE) -
Django vs Flask. Which one should I use?
So I have recently decided to learn Django, and so far I am going pretty well. However, I have also heard Flask is good. Which one is better for a beginner like myself, who is only making small sites at the moment? Thank you for any help -
Redirection and edge case handling
I am trying to run some compute engine and google cloud dns functions when a form is submitted. I want to know how to do following things: 1) If every thing has been done properly then redirect to newly created sub domain. 2) If some error arises then redirect visitor to a default page stating your instance cannot be created.Please try again. I do not know how to redirect to a url which itself is being created during form save. class Company(models.Model): registrant = models.CharField("Name of the Registrant",max_length=120,null=True,blank=False) company = models.CharField("Name of the company",max_length=120, null=False) email = models.EmailField("Official Email Id of registrant",null=True,blank=False) designation = models.CharField("Designation at the company",max_length=120,null=True,blank=False) size = models.PositiveIntegerField("No. of employees",validators=[MinValueValidator(1)]) subdomain = models.CharField(max_length=120,null=True) registration_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company class CompanySignupForm(forms.ModelForm): class Meta: model = Company fields = ('company','registrant','email','designation','size') def clean_email(self): email = self.cleaned_data.get("email") qs = User.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError("Cannot use this email. It's already registered") return email def clean_company(self): company = self.cleaned_data.get("company") qs = Company.objects.filter(company__iexact=company) if qs.exists(): raise forms.ValidationError("This company is already registered") return company def save(self,commit=True): company = super(CompanySignupForm,self).save(commit=False) email = self.clean_email() company.company = self.clean_company() company.registrant = self.cleaned_data.get('registrant') company.designation = self.cleaned_data.get('designation') company.size = self.cleaned_data.get('size') company.save() name = company.company.lower() + str(generate_random()) company.subdomain = name+".mysite.com" …