Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django <object> is not JSON serializable
I am using https://github.com/coderholic/django-cities and i wanted to add city and country to my serializer. This is my model: from cities.models import Country, City class Location(models.Model): name = models.CharField(max_length=200, blank=True, null=True, default=None) city = models.ForeignKey(City, blank=True, null=True, default=None, related_name='city_of_location') geolocation = map_fields.GeoLocationField(max_length=100, blank=True, default='') My views: class LocationsView(generics.ListAPIView): queryset = Location.objects.order_by('-id') serializer_class = LocationsSerializer serializers.py class LocationsSerializer(serializers.ModelSerializer): number_of_rooms = serializers.SerializerMethodField() country = serializers.ReadOnlyField(source='city.country') class Meta: model = Location fields = ['id', 'name', 'geolocation', 'city', 'country'] When i'm trying to see if it works i'm getting: <Country: Austria> is not JSON serializable -
my django can't generate models from oracle database
I am building django project upon oracle database, after i set my database in django settings, i use command python manage.py inspectdb to generate oracle tables, but there is an error: > Unicode DecodeError: 'utf-8 codec can't decode bytes in position > 82-83:invalid continuation byte what can i do ? the oracle is not install in my local pc. i tried to set local env path:NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK, it doesn't work. Thank you for your help! -
How to use request.META.HTTP_HOST inside Django models?
I'm trying to improve my app's SEO by having absolute URLs to my links (link for each world city). I managed to do so in the template by doing this: <a title="{{city.name}}" href="http://{{ request.META.HTTP_HOST }}/{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> However I'm trying to implement the same from the model in a way that I can simply do this: <a title="{{city.name}}" href="{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> This is my attempt: def get_absolute_url(self): return "http://" + self.request.META.HTTP_HOST + '/city/%s/' % self.slug But I get this: name 'request' is not defined How can I import the user request to use in a model? -
ajax is not working with django
i am creating a form that add a comment to a post, it is working without ajax, because ajax send the form data as None. the ajax: <script> $(function() { $("#myform").on("submit", function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: 'POST', data: $(this).serialize(), beforeSend: function() { $("#message").html("sending..."); }, success: function(data) { confirm('worked') } }); }); }); </script> the form: <form action="{% url 'newcom' Post.id%}" id="myform"> <div class="input-group"> <input type="text" name="comment_body" class="form-control" placeholder="Leave a comment"> <div class="input-group-btn"> <button class="btn btn-success" id="message" type="submit"> <i class="glyphicon glyphicon-send"></i> </button> </div> </div> <br> </form> the view: def new_comment(request, post_id): body = request.GET.get('comment_body') post = Post.objects.get(id=post_id) Nat.objects.create(fromUser=request.user.username, toUser=post.created_by, content="commented on your post") Comment.objects.create(post=post, created_by=request.user, created_at=timezone.localtime(timezone.now()), comment=body) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Shall I rename user uploaded files?
Django==1.11.6 There are file upload attacks. But modern Django seems well guarded against them. Django security guide is here: https://docs.djangoproject.com/en/1.11/topics/security/#user-uploaded-content Concerning user uploaded files it is much shorter than other security guides. In the Internet we can find this kind of advice: The application should not use the file name supplied by the user. Instead, the uploaded file should be renamed according to a predetermined convention. Well, I think that renaming is a good idea. Shall I rename user uploaded files or it is not dangerous in case of modern Django? -
Push to heroku: no module named 'channels'
I am facing this error when I add 'channels' into INSTALLED_APPS Writing objects: 100% (4/4), 351 bytes | 0 bytes/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with latest Pipenv… remote: Installing dependencies from Pipfile.lock (36121f)… remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/__init__.py", line 27, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 978, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 961, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'channels' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. … -
mod_wsgi-express: error: no such option: --url-alias
I'm deploying an application with mod_wsgi-express, and I've a new error when launching the service : oct. 12 09:15:29 Angara mod_wsgi-express[12284]: Usage: mod_wsgi-express start-server script [options] oct. 12 09:15:29 Angara mod_wsgi-express[12284]: mod_wsgi-express: error: no such option: --url-alias /static /var/www/agenda-v3.example.tld/static --url-alias /media /var/www/agenda-v3.example.tld/media The mod_wsgi-express application fails to launch... I've added the --log-directory directive to route logs to the ${SERVER_PATH}/log, which works great (I can read the log files now), I've checked the /var/www/agenda-v3.example.tld/media and /var/www/agenda-v3.example.tld/static directories, they exist for now. Service file: https://gist.github.com/frague59/a7701073d50e77e4b5492c72157ebfab Service environment file: https://gist.github.com/frague59/2992e3b02e5d40a1b5a6f0a508a73f4a Have you any idea ? It worked before... Thanks for your help ! -
Django test: how to compare result of resolve() with view function when login_required is specified for that view
In urls.py i have my view detail annotated with login_required to forward unauthorised users to login page: url(r'^(?P<id>[0-9]+)/$', login_required(views.detail), name = 'detail') And i'm trying to write a test to check which view are selected on querying target url. I've a class to log in before tests start off: class LoggedInTestCase(TestCase): def setUp(self): user = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') class ProductDetailTest(LoggedInTestCase): def setUp(self): super(ProductDetailTest, self).setUp() def test_product_detail_url_resolves_product_detail_view(self): view = resolve('/products/1/') self.assertEquals(view.func, detail) and when i run tests i got: FAIL: test_product_detail_url_resolves_product_detail_view (products.tests.ProductDetailTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\heroku\django\products\tests.py", line 46, in test_product_detail_url_resolves_product_detail_view self.assertEquals(view.func, detail) AssertionError: <function detail at 0x05CC3780> != <function detail at 0x053B38A0> ---------------------------------------------------------------------- When i remove login_required all tests pass well. -
Use the template of another django app in an another app
I have two django apps. One which belongs to core code and one contrib app. What I need to do is to display a template in my contrib app, which actually exists already in the core app. This is more or less the folder structure: django project core app templates ... contrib app templates -template_from_core_app The template renders data from views and forms which exist in the core app. I am wondering what is the best way to do something like this. -
Connect to remote ElasticSearch Server using Haystack
I am using to django-Haystack to connect to remote elasticsearch, but the haystack is looking for local installation of the elastic-server. How to use haystack with remote elastic server These are my config HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://xx.xx.xx.xx:9200', 'INDEX_NAME': 'my-index', } } -
how to pass {% csrf_token %} in javascript which is returning a html form
function GetDynamicTextBox(value){ return '<form id="addtextbox" name="addtextbox" method="post">'+ '<div class="col-xs-4">'+ '<label for="ex3">Enter Alertname</label>'+ '<input class="form-control" id="userInput" type="text" name="alertname1" placeholder="Enter the alerts..">'+ '<br>'+ '<i class="fa fa-cloud" aria-hidden= "true"></i>'+ ' <input type="submit" class="btn btn-success" value="Save">'+ '</div>'+ '</form>' } It is throwing an error csrf token missing but even I include ''+'{% csrf_token %}' it is throwning an error.Please guide me in this -
python django restful api - can't always catch a specific post request
I am using python Django restful api framework. I am trying to catch all the userPreference post requests in views.py. For some reason I can catch all the post request with my code. Here is my views.py class aUserViewSet(aAPIViewSet): def get_queryset(self): ''' This function limits the queryset to User's data ''' queryset = super(aUserViewSet, self).get_queryset() qs1 = queryset.filter(user=self.request.user) if qs1.exists(): if "userpreference" in qs1.model._meta.db_table: tp = self.ws_userPreference(qs1, self.request.user.username) else : print("no handle needed") else : print("qs1 not exist") return queryset.filter(user=self.request.user) def ws_userPreference(self, qs1, username): if self.request.method == 'POST': print("get userPreference post") else : print("get userPreference non post request") return 0 class UserPreferenceViewSet(aUserViewSet): queryset = UserPreference.objects.all() print "In userPreference viewset" serializer_class = UserPreferenceSerializer filter_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) filter_backends = (URLFilter, ) ordering_fields = ('activationResponse','startTimeForDecisionChoice', 'endTimeForDecisionChoice', 'valueScale1', 'valueScale2', 'valueScale3', 'valueScale4', 'decisionPreference', 'waypointsCompleted', 'numberOfSessionsToDecisionChoice','created', ) -
upstream prematurely closed while reading response header from upstream, reques: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:"
upstream prematurely closed connection while reading response header from upstream, client: xxx.xx.xx.xx, server: website.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///tmp/web.sock:", host: "website.com" How to solve this? -
Error Setting Up Frontend Login in django marcador tutorial
I am a newbie using django 1.11.5 installed.This a tutorial from macador app project.I have already created the view in thhe project main template.my login and logout is not working.When i run the runserver command,I get the following error. terminal Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f087adf5aa0> Traceback (most recent call last): File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/root/Desktop/bookmarksmanager/myenv/src/mysite/urls.py", line 27, in <module> name='mysite_login'), File "/root/Desktop/bookmarksmanager/myenv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view … -
save google autocomplete places data in a model which has foreign key
I have a form in django where there is a field called address where I am using https://github.com/ubilabs/geocomplete/ plugin so which when submitted should store address in fields like country, city, postal_code etc instead of giving user to fill all those fields in restaurant object along with other data. This one is working well class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) country = models.CharField(max_length=7) city = models.CharField(max_length=7) postal_code = models.CharField(max_length=7) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant widgets=({country: forms.HiddenInput(attrs={'id': country}), city: forms.HiddenInput(attrs={'id': locality}), postal_code: forms.HiddenInput(attrs={'id': postal_code})}) fields = ( "logo", "name", "cuisine", "country", "city", "postal_code", "address", "phone" ) def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() if request.user.is_authenticated(): if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) else: if request.method == "POST": user_form = MemberForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username=user_form.cleaned_data["username"], password=user_form.cleaned_data["password"] )) return redirect(restaurant_order) return render(request, "restaurant/sign_up.html", { "user_form": user_form, "restaurant_form": restaurant_form }) <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if user.is_anonymous %} {% bootstrap_form user_form %} {% bootstrap_form restaurant_form %} {% else %} Hello, {{ request.user.username }} <br>Please … -
Add filter by year in Django admin
I have a Django model with DateTimeField field as "created_at", now I want to add a filter for that field in Django admin but I need only the year field instead of default fields as (today, past 7 days, this month, this year). Here's my model: In models.py class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) I have tried to override created_at field in admin.py as: class TaggedArticle(admin.ModelAdmin): fields = ['category_fit', 'article', 'link', 'relevant_feedback', 'category', 'user', 'email', 'created_at'] list_display = ['article_id', 'link', 'user', 'created_at'] list_filter = ['user', 'email', 'created_at'] model = Tagged def created_at(self, obj): return self.Tagged.created_at.year admin.site.register(Tagged, TaggedArticle) But it doesn't work. How can I achieve that? Help me, please! Thanks in advance! -
How to Make an Non-Database Auto-Attribute to a Django Model Instance
Sometimes, we save some fields that change a lot to Redis or other backends. But in that way, we could lose the convenience of getting a value from an instance by article.count. We usually set a property function to a model, which performs the logic of querying the memory based database. class WhatEver(models.Model): @property def some_field(self): return redis.hget('what-ever-%s' % self.id) def set_some_field(self, value): return redis.hset('what-ever-%s' % self.id, value) Ugly, but useful. But, it doesn't work all the time, as it's an intrusive way to bring us the ability. Say, we want to get a user's visits, We actually want to call user.visits, But it's not good for a submodule to overwrite the base module, so we can only wrap it as a function get_user_visits(user) and again, not elegant. Do we have a way to do this kind of tricks automatically and non-intrusively? -
How to do database migration using python script?
is it possible to do migration from python script? I am trying to use django on Heliohost where there is no shell but I can use python script. something like from django import shell shell.main(['mysite/manage.py', 'migrate']) -
Foreign Key "automatic column lookup" in Django
Consider the following models: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) publisher = models.ForeignKey('Publisher') class Publisher(models.Model): id = models.AutoField(primary_key=True) publisher_name = models.CharField(max_length=255) I would like to call Book.objects.filter(id=123), but the output for this should be: { 'id':123, 'title':'ABC', 'publisher':1 } for admin users, and { 'id': 123, 'title':'ABC', 'publisher':'XYZ Books' } for normal users. My question is, can this be done with select_related() or changing the models.ForeignKey() parameters only? -
Using ModelFormMixin without the 'fields' attribute is prohibited
I'm using Django 1.11 I have created a Form and using Class based view to create a record and save to database. Business/models.py class BusinessType(models.Model): title = models.CharField(max_length=100) created = models.DateTimeField('date created', auto_now_add=True) modified = models.DateTimeField('last modified', auto_now=True) class Meta: db_table = 'business_types' def __str__(self): return self.title class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) created = models.DateTimeField('date created', auto_now_add=True) modified = models.DateTimeField('last modified', auto_now=True) class Meta: verbose_name = 'business' verbose_name_plural = 'businesses' db_table = 'businesses' def __str__(self): return self.name Business/Forms.py class BusinessForm(ModelForm): class Meta: model = Business fields = ['user'] Business/views.py class BusinessCreate(LoginRequiredMixin, CreateView): model = Business form = BusinessForm def form_valid(self, form): messages.success(self.request, 'form is valid') form.instance.user = self.request.user form.save() def get_success_url(self): messages.success(self.request, 'Business Added Successfully') return reverse('business:list') On loading template of BusinessCreate it gives error as Using ModelFormMixin (base class of BusinessCreate) without the 'fields' attribute is prohibited. My Trials After moving fields to views class, it is working fine. But I don't want to do so, as I may be using this form on multiple views and thus will require changes on multiple pages in future if needed. -
Django CMS placeholder content not showing up on page when i log out from the admin
i'm having trouble with placeholders Django-CMS.I have used placeholders all over my templates of my existing project and they seem to work just fine when i'm logged in, i can add and edit plugins but when i log out all the edits don't show up on the templates anymore.what might be causing this?considering i have followed the placeholder creation procedure and published all my changes? Considering the following scenario where i have {% placeholder "feature" %} on my template, the plugin is visible on the page and editable but the content only shows up on the website page when i'm logged in. -
Django Book tree base model
I'd like to know if is possible to do a book base model. Every category has many subcategories with the same name. For ex: Book 1 has seccion 1, seccion 2, etc. Every seccion chapter 1, chapter 2 and so on. wich is the best way to do the structure? -
Django Models - Lists vs One-to-Many
I have two models, Audience and Reports, that I want to relate. The Audience model has one set of ids that reference a particular instance of an audience while the reports have a separate set of codes that relate to a particular instance of an audience. On top of that each report is associated with multiple Audience. Am still pretty new to Django but just ashamedly rusty with setting up database models. In my current solution I create a third model AudienceReportMapping which just relates the audience_id to the report_code. I have a class method on Reports which uses the intermediate mapping table to get me the appropriate audience ids for the codes associated with each report. Everything relevant is set up like so: from django.db import models from django_mysql import ListTestField class Audience(models.Model): ... id = models.IntegerField() class AudienceReportMapping(models.Model): audience = models.ForeignKey(Audience) report_code = models.IntegerField() class Reports(models.Model): ... report_id = models.IntegerField() codes = ListTextField( base_field=models.IntegerField() ) @classmethod def audience_ids(cls, report_id): report = Reports.objects.filter(report_id=report_id).first() codes = report.codes audience_ids = [] for code in codes: audience = AudienceReportMapping.objects.filter(report_code=code).first().audience audiences_ids.append(audience.id) return audience_ids This feels like a pretty inelegant solution to something thats been solved before, just have trouble getting my head around … -
Adding functionality dynamically to Django app
I have a requirement to be able to extend a Django app dynamically. For example, the app should be able to list all .py files in a particular directory, and using a well-defined interface, call any of the functions in any of these .py files. Another requirement is that power users should be able to just drop a new .py file in the specified directory, and it should become visible to all users. I looked here, here and here, but none of the approaches allows me to load an arbitrary file - perhaps because I am using Python 3.6 (Django 1.11) and these approaches are deprecated. The following code is working fine: def show_modules(request): listOfNames = os.listdir( os.path.dirname( os.path.dirname(os.path.abspath(__file__)) + OPS_DIR)) where OPS_DIR is defined in settings.py as a relative path to the project (but could be a shared folder elsewhere). The variable listOfNames does get populated with the list of files in the particular directory. An example of the type of files would be: def do_operation(one, two): return one + two def description(): return "This just adds a couple of numbers. Provide two parameters." I want to be able to (a) list all the .py files available in the … -
save address from google autocomplete to an object
I have a form in django where there is a field like address, country, city, postal_code etc. I want to use this https://github.com/ubilabs/geocomplete/ plugin so which when submitted should store address in fields like country, city, postal_code etc instead of giving user to fill all those fields in restaurant object along with other data. Here is what I have tried class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) country = models.ForeignKey(Country, related_name='restaurant_country') city = models.ForeignKey(City, related_name='restaurant_city') postal_code = models.CharField(max_length=7) address = models.CharField(max_length=500) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant # fields = ( # "logo", "name", "cuisine", "country", "city", "postal_code", # "address", "phone" # ) #instead of above i switched to this fields = ( "logo", "name", "cuisine", "phone" ) views.py def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() if request.user.is_authenticated(): if request.method == "POST": restaurant_form = RestaurantForm(request.POST, request.FILES) if restaurant_form.is_valid(): new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = request.user new_restaurant.save() return redirect(restaurant_order) else: if request.method == "POST": user_form = MemberForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username=user_form.cleaned_data["username"], password=user_form.cleaned_data["password"] )) return redirect(restaurant_order) return render(request, "restaurant/sign_up.html", { "user_form": user_form, "restaurant_form": restaurant_form }) template <form method="POST" enctype="multipart/form-data"> …