Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IF logic for rating of bookstores django python
I want to make a program, if I haven't chosen a rating, I can't write a review. Here is the program code in views.py if request.method == 'POST': if request.user.is_authenticated: if form.is_valid(): temp = form.save(commit=False) temp.reviewer = User.objects.get(id=request.user.id) temp.buku = buku temp = Buku.objects.get(id_buku=id) temp.totalreview += 1 temp.totalrating += int(request.POST.get('review_star')) form.save() temp.save() messages.success(request, "Review Added Successfully") form = ReviewForm() else: messages.error(request, "You need login first.") -
Django TypeError: 'NoneType' object is not subscriptable
I have some trouble with one of my functions in my projects view file. I have tested with removing this function and then things work. Here is the view, This is my view file def createPurchaseOrder(request): form = PurchaseOrderForm() if request.method == 'POST': form = PurchaseOrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'order_form.html', context) Here is the hmtl file with the link which tries to access the view {% for order in orders %} <tr> <td>{{order.po_number}}</td> <td>{{order.product}}</td> <td>{{order.status}}</td> <td><a href="{% url 'update_order' update_order.id %}">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} I also have attached the urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('supplier/<str:pk>/', views.supplier, name="supplier"), path('products/', views.products, name="products"), path('purchase_order/', views.purchase_order, name="purchase_order"), path('order_form/', views.createPurchaseOrder, name="create_purchase_order"), path('update_order/<str:pk>/', views.updatePurchaseOrder, name="update_order"), ] I expect there to be a simple mistake, but can't seem to find it. -
AttributeError at /user/ 'CommentSection' object has no attribute 'post' django
When i try uploading a comment to a post i get this error The post model is a foriegnKeyfield of the post the comment is posted on I tried changing the model name but it did nothing i get the same error again Here is the models code : class Comment(models.Model): post = models.ForeignKey(Meme, on_delete=models.CASCADE) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) and here is the view : def user_home(request): comment = CommentSection() id = request.POST.get('id') if request.method == 'POST': comment = CommentSection(request.POST) if comment.is_valid(): comment.save(commit=False) comment.op = request.user comment.not_post_method_ok.id = id comment.save() comments = Comment.objects.all() imgs = Meme.objects.all() ctx = { 'imgs': imgs, 'comment': comment, 'comments': comments, } return render(request, 'User_Home.html', ctx) the id i get works but for some reason i keep getting this error please help and thanks a lot -
How to Implement 4-way Dependent Dropdown List with Django?
i am trying to make a 4 Dependent dropdown list using Django. I am following this example of code with 3 dropdowns https://github.com/masbhanoman/django_3way_chained_dropdown_list but i am getting an error. This is my code: models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Vanue(models.Model): name = models.CharField(max_length=10) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return self.name class Area(models.Model): name = models.CharField(max_length=10) vanue = models.ForeignKey(Vanue, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) vanue = models.ForeignKey(Vanue, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, City, Vanue, Area class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city', 'vanue', 'area') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() #city if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') #vanue self.fields['vanue'].queryset = City.objects.none() if 'city' in self.data: try: city_id = int(self.data.get('city')) self.fields['vanue'].queryset = Vanue.objects.filter(city_id=city_id).order_by('name') except … -
Linear regression prediction
I have source code to predict heart diseases, but it shows 1-if disease is exist, and 0-if none disease. I need to make precent of disease. Here is an example with logistic regression, but i have 4 algorithms, so i need to show precentege of risk. Actually, i am new in AI, so this is not my code at all but i need to improve it if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True #### logistic regression #fitting LR to training set from sklearn.linear_model import LogisticRegression classifier =LogisticRegression() classifier.fit(X_train,Y_train) #Saving the model to disk #from sklearn.externals import joblib #filename = 'Logistic_regression_model.pkl' #joblib.dump(classifier,filename) #Predict the test set results y_Class_pred=classifier.predict(X_test) #checking the accuracy for predicted results from sklearn.metrics import accuracy_score accuracy_score(Y_test,y_Class_pred) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, y_Class_pred) #Interpretation: from sklearn.metrics import classification_report print(classification_report(Y_test, y_Class_pred)) #ROC from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test)) fpr, … -
Django logger file created but no content for django or gunicorn
I am using Django 3.2 and gunicorn 20.1 I am trying to provide useful log tracing in my models, views etc. Typically, I am using named loggers as follows: /path/to/myproject/myapp/somemodule.py import logging logger = logging.getLogger(__name__) logger.warn('Blah blah ...') /path/to/myproject/mypoject/settings.py # https://stackoverflow.com/questions/27696154/logging-in-django-and-gunicorn # https://stackoverflow.com/questions/33990693/django-log-to-file-by-date-or-hour LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'logfile': { 'level':'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/site.logs'), 'maxBytes': 1024 * 1024 * 15, # 15MB 'when': 'D', # this specifies the interval 'interval': 1, # defaults to 1, only necessary for other values 'backupCount': 10, # how many backup file to keep, 10 days 'formatter': 'verbose', }, }, 'loggers': { 'gunicorn': { # this was what I was missing, I kept using django and not seeing any server logs 'level': 'INFO', 'handlers': ['logfile'], 'propagate': True, }, 'root': { 'level': 'INFO', 'handlers': ['console', 'logfile'] }, }, } As my title says, the logfile is created, however, there is no content. What is causing this, and how do I fix it? -
I am trying to use search on my object in 3 fields name, category, and tags, so now similar item three time
views.py if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)) Html code <form method="GET" action="/" class="d-flex"> <input class="form-control me-2" name="search" id="search" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> n class="btn btn-outline-success" type="submit">Search -
Why I am getting 'no file chosen' error while uploading image in django
Here is my codes and I tried all methods but none of them work :( models.py file ''' from django.db import models class Review(models.Model): name = models.CharField(max_length=50) job = models.CharField(max_length=200) body = models.TextField() image = models.ImageField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + ' | ' + self.job[:50] class Meta(): ordering = ('-created',) ''' forms.py file ''' from django import forms from .models import Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = '__all__' ''' views.py file ''' from django.shortcuts import render from django.views.generic import ListView from .forms import ReviewForm from .models import Review class ReviewView(ListView): model = Review template_name = 'testimonals/home.html' def WriteReview(request): if request.method == 'POST': form = ReviewForm(request.POST, request.FILES) if form.is_valid(): form.save() form = ReviewForm() context = {'form': form} return render(request, "testimonals/create_post.html", context) ''' html file ''' <form action = "" method = "POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> ''' Here is problem but I fill all fields Here is result which I added by admin panel -
How to loop through the multiple items in Django Template
How can I loop through items in django template. {% for brand in categories%} <div class="brand-col"> <figure class="brand-wrapper"> <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> </figure> <figure class="brand-wrapper"> <img src="imgsrc" alt="Brand" width="410" height="186" /> </figure> </div> {% endfor %} Here, first I want to loop item 1 and item 2 on figure tag and again I want to loop entire div and loop item 3 and 4 inside the div on figure tag. I tried to do with cycle, but no luck. Any help will be highly appreciated. -
I deployed an Django app on heroku as hobbyist. Why does admin changes i make disapear after a while [closed]
https://marcelinoacademy.herokuapp.com/ The admin page is programmed to help me add information to the site. Unfortunately all the information I add keep disapearing after a while. -
How do I return the url back to details page once the comment is deleted - Django?
So at the moment once the comment is deleted, the URL takes back to the post list page. As probably you could tell that I am not very experienced with Django yet so if someone could explain that how do I figure out what key is to be passed and where, that would be a great help. Please find the codes below: MODELS: class Post(models.Model): CHOICES = ( ('celebrate', 'celebrate'), ('planning', 'planning'), ('outdoor', 'outdoor'), ('holidays', 'holidays'), ('festivals', 'festivals'), ('movies', 'movies'), ('shopping', 'shopping'), ('laptop', 'laptop'), ('data', 'data'), ('sciance', 'science'), ('summers', 'summers'), ('medical', 'medical'), ('art', 'art'), ) author = models.ForeignKey(User, on_delete=models.CASCADE, default="") title = models.CharField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) text = models.TextField() category = models.CharField(max_length=100, null=True, choices=CHOICES) tags = models.ManyToManyField(Tag) class Meta: """ Meta class to change the configuration, ordering by the name""" ordering = ['-date_posted'] def get_absolute_url(self): """ Reverse the Post object to the url once action has been taken with primary key to direct back to the same post """ return reverse('posts:post_list') def __str__(self): return self.title class Comment(models.Model): """ comments for Post model """ comment_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comment_for_post', null=True, default='') comment_text = models.TextField(null=True) date_posted = models.DateTimeField(auto_now=True) def get_absolute_url(self): """ Reverse the Post object to the url once action has been … -
TypeError: argument must be int or float in Django 3.0
Here i guess i am getting this error when trying to print the item_name let us consider my models.py as class Wastage(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) item_name = models.ForeignKey(Items,on_delete=models.CASCADE) class JobItems(models.Model): item_name = models.CharField(max_length=512) here is my views.py class WastageView(ListView): template_name = 'wastage_list.django.html' model = Wastage context_object_name = "stock_wastage" def get_context_data(self, **kwargs): context = super(WastageView, self).get_context_data(**kwargs) context["faulty_reasons"] = FaultyReason.objects.filter(client=self.request.user.client,is_deleted=False) return context def get_queryset(self): user = self.request.user client = user.client query = self.request.GET.get('query') if query: return self.model.objects.filter(client=client, name__icontains=query).order_by('-date') return self.model.objects.filter(client=client).order_by('-date') Now let us consider my template wastage_list.django.html as {% for item in stock_wastage %} <tr> <td>{{ item.date|date }}</td> <td>{{ item.item_name }} </td> </tr> {% endfor %} Here my issue is with the item_name here is an example of my database record id client_id date item_name_id 1 3 2021-06-24 103 2 3 2021-11-23 21 3 3 2022-01-02 53 Please help me to display item_name -
iframe inside electron app (django backend) returns CSRF verification failed on form submit
I have the following stack: Django backend. electron (React) frontend. I'm rewriting an old server side rendering frontend with React but for the meanwhile we want to still be able to use it. So we're trying to use an iframe , but when I try to the login form we have, I'm getting 403 CSRF verification failed. -
Django error: no such table: main.auth_user__old
I am trying to add a product in the admin part of my website. However, when I press save, I get this error: OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 4.0 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\timotrocks\PycharmProjects\Django project\venv\lib\site-packages\django\db\backends\sqlite3\base.py, line 416, in execute Python Executable: C:\Users\timotrocks\PycharmProjects\Django project\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\Users\timotrocks\PycharmProjects\Django project', 'C:\Users\timotrocks 'pek\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\timotrocks\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\timotrocks\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\timotrocks\AppData\Local\Programs\Python\Python39', 'C:\Users\timotrocks\PycharmProjects\Django project\venv', 'C:\Users\timotrocks\PycharmProjects\Django ' 'project\venv\lib\site-packages'] -
Authentication to my app does not work when I deploy on heroku
Here is my code def connexion(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password"] matricule = form.cleaned_data["matricule"] user = authenticate(email=email, password=password) if user is not None: user = User.objects.get(email=email) if Agent.objects.filter(user=user, matricule=matricule).exists(): agent = get_object_or_404(Agent, user=user) profile = agent.profile if user.is_active: login(request, user) request.session["profile"] = profile return redirect(reverse("elec_meter:home")) else: messages.add_message(request,messages.WARNING,"Votre profile n'est pas " "encore activé! Veuillez contacter l'administrateur.") return render(request, "elec_meter/login.html", {"form": form}) else: messages.add_message(request,messages.ERROR,"Utilisateur non existant !") return render(request, "elec_meter/login.html", {"form": form}) else: messages.add_message(request,messages.ERROR,"Utilisateur non existant !") return render(request, "elec_meter/login.html", {"form": form}) else: form = LoginForm() return render(request, "elec_meter/login.html", {"form": form}) This is the code that allows authentication to my app. It works very well locally. But when I deploy the application on heroku it doesn't work anymore. It always sends me back to the login page without any messages. Sometimes it sends me a 403 forbidden while I have {% csrf_token%} in the form. Are there any configurations to add ? How can I solve this problem ? -
Many-to-many relationship between 3 tables in Django
I have the following models: class Project(models.Model): project_name = models.CharField(max_length=50) project_users = models.ManyToManyField('Users.UserAccount', related_name='project_users', blank=True) .... class UserAccount(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) .... class Discipline(models.Model): name = models.CharField(unique=True, max_length=27, choices=discipline_choices) The DB table for project_users looks like this: *--------*----------------*---------------------* | ID | project_id | user_account_id | *--------*----------------*---------------------* I want to have an extra relationship in project_users field/table with the Discipline model. Is that possible in Django? I have been looking at intermediary-manytomany relationships in Django, but that's not exactly what I want. In my application, there are a set amount of disciplines, and what I'm trying to achieve is to give each user multiple disciplines in a single project. So something like this: *--------*----------------*---------------------*-------------------* | ID | project_id | user_account_id | discipline_id | *--------*----------------*---------------------*-------------------* Is this possible? -
Python (Django) how to assign a default value in case of error
Hey I'm using django in a project, using a POST method, the view in Django receives data, it works fine if the data is received but if no data is received I want to assign a default value instead of getting an error here is my code. I tried to use the if assignement but it doesn't work. @api_view(['POST']) def getPacsPatients(request): data = json.loads(request.body.decode('utf-8')) if request.method == 'POST': PatientName = data["patientName"] if data["patientName"] else "*" #it works fine if data["patientName"] is present, but if not I get an error -
How can i use Exists with WHEN CASE in Django
I am trying to write ORM in Django something like this: DECLARE @vari1 INT = 2 DECLARE @vari2 INT = 0 SELECT *, CASE WHEN EXISTS (SELECT B_id FROM dbo.Subscription WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) THEN @vari1 ELSE @vari2 END) FROM dbo.Subscription; -
How to authorize IoT device on Django channels
I have a real-time API based on Django channels and IoT devices that expects commands and data from API. The IoT devices are not related to any kind of user model and have only the unique UUID as an identifer. How to implement the authorization middleware with the ability to reject some of the devices if they are compromised? -
How to create a table using raw sql but manage it using django's ORM?
I am using django for my backend, and I want to use table partitioning and composite primary key for postgresql, but, django's ORM does not support these features yet (or at least I couldn't find them). So, I have decided to use raw sql code in django, but I would like to manage it using django's ORM (only the creation would be in raw sql, and this table would have many-to-many relationships with other tables). I would like to know if this is possible and if yes, what would be the best way to do it? Thank you in advance for your time. -
Django. How to return error 500 without sending mail to admins
I am using standard error handling in production - if there are server errors I am getting mails. However, on certain APIs I want to have a response with HTTP code 500 as part of the "valid flow". (It's done for some learning purposes) So my view for that looks like this: from rest_framework.response import Response from rest_framework import status def give_me_error(request): return Response("This is expected error", status=status.HTTP_500_INTERNAL_SERVER_ERROR) And what I want is not to get email of this particular response (because I wanted it to be 500) I've also tried this way: from django.http import JsonResponse def give_me_error(request): return JsonResponse({'error': 'expected error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But it also generates mail. Is there a way to have a view returning error 500 that will not trigger e-mail send? (without disabling the e-mail functionality system-wide) -
Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag?
I'm upgrading mezzanine/django application form python 2.7/Mezzanine 4.3.1 to python 3.7/mezzanine 5.0.0. When when running the application in 3.7/mezzanine 5.0.0. I get the error django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag? I guess it must come from the file myProject/myProject/templates/admin/base_site.html: {% overextends "admin/base_site.html" %} {% block extrahead %} {{block.super}} <style type="text/css"> div.cke_chrome { margin-left: 130px; } </style> <link rel="stylesheet" href="{{ STATIC_URL }}css/statfi-editor.css" /> <script src="{{ STATIC_URL }}js/statfi_csrf.js"></script> {% endblock %} since if I remove the 1st line {% overextends "admin/base_site.html" %} the borwser shows empty admin/-page. I tried to fix by adding buildins key into TEMPLATES setting: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'builtins': ['overextends.templatetags.overextends_tags'], } }, ] but that would require installing overextends-module. When installing it I got: django-overextends 0.4.3 requires django<2.0,>=1.8, but you have django 2.2 which is incompatible. Are there any other means to solve the problem than just downgrading both mezzanine and django version in order to get that overextends module into use ? -
Django - Profile() got an unexpected keyword argument 'username'
I'm trying to make when a user access the website url / username e.g http://127.0.0.1:8000/destiny/ but it throws the Profile() got an unexpected keyword argument 'username' error. I have tried adding a username argument in my profile views. I also tried geting the username when the user signup, to use it in the profile view but it still doesnt work. i'm a django newbie that's why i don't really know where the error is coming from views.py def UserProfile(request, username): user = get_object_or_404(User, username=username) profile = Profile.objects.get(user=user) url_name = resolve(request.path).url_name context = { 'profile':profile, 'url_name':url_name, } return render(request, 'userauths/profile.html', context) #register view def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.filter(active=True) categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): new_user = form.save() username = form.cleaned_data.get('username') messages.success(request, f'Hurray your account was created!!') new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return redirect('elements:home') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) first_name = models.CharField(max_length=1000, null=True, blank=True) last_name = models.CharField(max_length=1000, null=True, blank=True) email = models.EmailField(null=True, blank=True) phone = models.IntegerField(null=True, blank=True) bio = models.CharField(max_length=1000, null=True, blank=True) aboutme = … -
richtext_filters in Mezzanine 5.0.0
I've been trying to upgrade a mezzanine/django application form python 2.7/Mezzanine 4.3.1 to python 3.7/mezzanine 5.0.0. When running my application in python 3.7/mezzanine 5.0.0 I get the error "django.template.exceptions.TemplateSyntaxError: Invalid filter: 'richtext_filter'", which didn't appear in python 2.7/Mezzanine 4.3.1. What can I do to fix this ? That filter has been used for instance in richtextpage.html: {% extends "pages/page.html" %} {% load mezzanine_tags %} {% block base %} {% editable_loader %} {% if has_site_permission %} {% include 'includes/editable_toolbar.html' %} {% endif %} {% editable page.richtextpage.content %} <div id="blankko_page"> {{ page.richtextpage.content|richtext_filters|safe }} </div> {% endeditable %} {% endblock %} below also the referenced page.html {% extends "base.html" %} {% load mezzanine_tags keyword_tags %} {% block meta_title %} {{ page.title }}{{ news.title }}{{ registerdescpage.title }} | {% if page.basicpage.lang == "en" or news.lang == "en" or page.registerdescpage.lang == "en" %} myOrg {% elif page.basicpage.lang == "sv" or news.lang == "sv" or page.registerdescpage.lang == "sv" %} myOrg {% else %} myOrg {% endif %} {% endblock %} {% block meta_keywords %}{% metablock %} {% keywords_for page as keywords %} {% for keyword in keywords %} {% if not forloop.first %}, {% endif %} {{ keyword }} {% endfor %} {% endmetablock %}{% endblock … -
django custom user filed not getting saved
I have a create user function as shown below def partner_signup(request): form = PartnerProfileForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user_qs = User.objects.filter(username=username).exists() context = { "form": form, } if not user_qs: try: user = User.objects.create_user( username=username, email=email, password=password ) user.business_partner = True, user.save() except IntegrityError as e: pass return redirect('partner_profile_create') return render(request, 'signup.html', context) and a custom user model as below class User(AbstractUser): business_partner = models.BooleanField(default=False) But business partner is always saved as false, how I can make it true.