Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have configured my uwsgi.ini file and its working fine with nohup. How can auto start uwsgi on boot?
Here is my uesgi.conf code description "uWSGI" start on runlevel [2345] stop on runlevel [06] respawn env UWSGI=/usr/local/bin/uwsgi env LOGTO=/var/log/uwsgi.log exec $UWSGI --master --emperor /home/ubuntu/socialtalks/config --die-on-term --uid socialtalks --gid www-data --logto $LOGTO Here is the ini file configuration. uwsgi.ini [uwsgi] # variables #projectname = thesocialtalks #base = /home/ubuntu/thesocialtalks # configuration #master = true env = /home/ubuntu/socialtalks #pythonpath = %(base) #chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.production #module = thesocialtalks.wsgi:application #socket = /tmp/%(projectname).sock # mysite_uwsgi.ini file [uwsgi] projectname = socialtalks pcre = true base = /home/ubuntu/socialtalks # Django-related settings # the base directory (full path) #chdir = /home/ubuntu/socialtalks chdir = %(base) # Django's wsgi file #module = socialtalks.wsgi module = %(projectname).wsgi # the virtualenv (full path) #home = /home/admin5/test/thesocialtalks_final/thesocialtalks plugin = python37 # process-related settings # master master = true enable-threads = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe #socket = /home/ubuntu/socialtalks/mysite.sock socket = /tmp/%(projectname).sock # ... with appropriate permissions - may be needed chmod-socket = 666 uid = www-data gid = www-data # clear environment on exit vacuum = true I am ruuning the script using the command nohup uwsgi --ini config/uwsgi.ini &. I want to automate my … -
How to handling timezones in django DRF without repeating myself too much?
Intro: My project TIME_ZONE is equal to 'UTC' while I have users from too many time zones. So, when I user make POST or PUT with date or time or dateTime fields I convert these fields to UTC before serializer.save(). Then, when a user make a GET request I convert the same fields back to the timezone of the user which is request.user.timezone # simplified functions def localize(usertimzone, date, type): date = parser.parse(date) current_user_tz = pytz.timezone(usertimzone) date = paris_tz.localize(date) date = date.astimezone(pytz.utc) #... this is not all the function there are more condition but don't care about the rest return date def normalize(usertimzone, date, type): current_user_tz = pytz.timezone(usertimzone) date = current_user_tz.localize(date) return date #usages example def post(self, request, *args, **kwargs): alert_date = request.data.get('alert_date') if alert_date: request.data['alert_date'] = localize(request.user.timezone, alert_date, 'datetime') Problem: I used these function in too many views and every time I create a new view I use it again. Goal: I need to find a way to do that in one function that generalize this conversion for all dateField, timeField and datetimeField fields. I tried: to make a class view and use these functions inside it then override that class for each new app. But, each model have … -
how to solve SMTPSenderRefused Error in Django
In setting.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_PASSWORD = '****' EMAIL_USE_TLS = True In views.py admin_info = User.objects.get(is_superuser = True) admin_email = admin_info.email ` send_mail( 'New car inquiry on your website', 'you have a new inwuiry for the car' + car_title + 'Login to your admin panel for more details', 'xyz@gmail.com', [admin_email], fail_silently=False, )` I've disabled two-factor authentication in my gmail, and I've also turned on less secure app access then also I'm getting this error.SMTPSenderRefused error -
How can I do a redirect from the backend Django
I have an application served with React Js for the frontend and Django for the backend. Upon sending some informations to the server, I would like to make a redirect that would occur on the frontend, is it possible ? If so how ? I tried redirecting but it didn't work The front-end (reactJs) async function PaymentHandler(e) { e.preventDefault(); const data = { command_id: order._id, price: order.TotalPrice }; try { const res = await axios.post("/api/orders/Details/", data); } catch (error) { console.log("THERES AN ERROR : ", error); } } return loading ? ( <Loader /> ) : error ? ( <Message variant="danger">{error}</Message> ) : ( <div> <Button variant="outline-primary" className="mt-3" onClick={PaymentHandler} > PAY NOW </Button> </div> ) Model.py class Stuff(models.Model): paymentDetails = models.JSONField() Model serializer class PaymentSerializer(serializers.ModelSerializer): paymentDetails = serializers.JSONField() class Meta: model = Stuff fields = '__all__' views.py from rest_framework.decorators import api_view from django.shortcuts import redirect from base.models import Stuff from base.serializers import PaymentSerializer import requests import json @api_view(['POST']) def getPaymentDetails(request): data = request.data payment = Stuff.objects.create( paymentDetails = data ) serializer = PaymentSerializer(payment, many=False) last = Stuff.objects.last() details = (last.paymentDetails) print('cmd id value :', details['command_id']) print('price id value :', details['price']) headers = {"Content-Type": "application/json","Authorization": "Bearer eyJ0exxxxxxxxxxxx"} url = "https://apps.somewebsite.com/" payload … -
Converting bytes to file in Django / Python
In my Django app, I have a PDF in bytes: print(myPDF) > b'%PDF-1.3\n1 0 obj\n<<\n/Type /Pages\n/Count 2.... I want to save it in my database: obj.document = myPDF obj.save() However I keep getting an 'bytes' object has no attribute '_committed' error on save. How can I convert my bytes string to a file-like object that can be saved? -
What is the difference between . and __ in Django?
Can someone help me to understand the actual difference between . and __ with proper example. -
I want to create a form form by inputting a form and a form form using ModelChoiceField
Currently, Django is creating a soccer game player information site. I would like to add a search function that combines pull-down and input form. As a search method, select the player name category (models.py: player_style) from the pull-down menu, enter the player name (models.py: player_name), and search for the player name. I used "ModelChoiceField" as the code and entered form.py and views.py, but it stopped due to an error. Since I'm new to Django, I have a lot of questions, so can you tell me what kind of code to write? Since the questioner is Japanese, It will be poor English, but thank you. models.py class Player(models.Model): player_style = models.CharField('player_style', max_length=20) player_name = models.CharField('player_name', max_length=50) def __str__(self): return self.player_name form.py from django import forms from django.forms import ModelChoiceField from .models import Player class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "%i" % obj.player_style + " %s" % obj.player_name views.py from .forms import MyModelChoiceField def filters(request): form = MyModelChoiceField(queryset=Player.objects.all()) if(request.method == 'POST'): form = form() player = request.POST['form'] data = Player.objects.filter(player_name=player) msg = 'results:'+str(data.count()) else: msg = 'search words...' form = form() data = Player.objects.all() params = { 'title': 'Player results', 'form': form, 'message':msg, 'data':data, } return render(request, 'filters.html', params) filters.html <h3 class="display-4 … -
How can we pass element ID as a variable in an AJAX request?
I am trying to write a template that will create a blog feed, like blogging websites with multiple instances of the same kind. Now, each instance (each blog post) needs its own like button. For implementing this feature, I am using AJAX. I am able to make changes in the database by clicking the 'follow' button but not able to make changes in the template with the success function. Here is the template, {% for question, count, is_follow in zipp %} <div class="border rounded my-2 px-3 py-1" style="box-shadow: 2px 2px 5px #2b6dad;"> <p class="fst-normal"> <small>Tags: </small> {% for tag in question.tags.all %} <small><a href="{% url 'tag' tag.slug %}" style="text-decoration:none; color:black"><i>{{tag.name}} |</i></a></small> {% endfor %} </p> <p><a href="{{question.get_absolute_url}}" style="text-decoration: none; color: black"><h5>{{ question.question }}</h5> <small>Arguments added: {{ count }}</small></a></p> <div class="blank" id="{{question.question_id}}"> {% include 'snippets/follow_question.html' %} </div> <button type="button" class="btn btn-secondary btn-sm mt-1"><i class="fa fa-share-alt" style="padding-right: 3px;"></i>Share</button> </div> {% endfor%} Script <script type='text/javascript'> $(document).ready(function(event){ $(document).on('click', '#follow', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url 'follow_question' %}', data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, datatype: 'json', success: function(response){ var id = $(this).closest('.blank').data('id'); $(id).html(response['form']); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> As far as I understand, … -
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
I am trying to implement bulk_create my inserting multiple objects in a relation, not sure whether i am doing it right my view skill_name = request.POST.getlist('skill_name') skill_level = request.POST.getlist('skill_level') print(f'skill name-> {skill_name} skill level ->{skill_level}') seeker_skll = [] # testing destructing for skill_nme, skill_lvl in zip(skill_name, skill_level): skill_set = Skillset.objects.get(skill_name=skill_nme) seeker_skll.append(Seekerskillset( skill_set=skill_set, skill_level=skill_lvl, seeker=user)) seeker_skll = Skillset.objects.bulk_create(seeker_skll) print(seeker_skll) return redirect('/users/dashboard') Model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' error i am getting AttributeError: 'Seekerskillset' object has no attribute 'skill_name' -
Is Foreign Key Constraint mandatory? Why not just keep the key and not the constraint?
Is Foreign Key Constraint mandatory? Why not just keep the key and not the constraint? For Eg: class SalesOrderSummary(models.Model): id = models.BigAutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False) # Order Status values could : CONFIRMED, DISPATCHED, DELIVERED order_status = models.CharField(max_length=255, blank=False, default='') class SalesOrderItem(models.Model): """ Line item details of the particular sales order, mostly they are grouped by seller, for easy processing """ id = models.BigAutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False) # Here I don't keep the ForeignKey Constraint, but I understand the constraint # and manage it myself, like whenever Order is deleted, these items are also # getting deleted sales_order_id = models.BigIntegerField() seller_sku = models.CharField(max_length=255, blank=False, default='') product_title = models.CharField( max_length=255, blank=False, default='') quantity = models.BigIntegerField() unit_price = models.DecimalField( max_digits=10, decimal_places=2, default='0.00') I totally agree that these FK Constraints, are here to make our life easy by making it to do our jobs. like automatically deleted when the associated main entity gets deleted. If I can manage that myself, then where is the problem. So let me know if I would encounter any dead end or something or some feature that's not at all possible. -
Data changing when multiple users are logged in with Discord OAuth2
I'm making a Django app with Discord OAuth2 so users can log in. When 2 users log in, the data appears on both screens. So if you log in, it'll show your data but if you reload the page, it'll show another user's data. Does anyone know why this happens? I know it's a lot of code but any help would be immensely appreciated. Views.py client_id = "client_id_here" @login_required(login_url="app/oauth2/login") def main(request: HttpRequest): username = user['username'] guild = [guild for guild in guilds if int(guild["permissions"]) & 0x00000020 == 32] connection = connection db = connection.cursor() query = db.execute("select server_count from info") servers = db.fetchone() servers = servers[0] query = db.execute("select user_count from info") users = db.fetchone() print(f"users: {users}") users = users[0] db.close() connection.close() return render(request, "home/index.html", { "username": username , "guilds": guilds, "guilds": guild, "servers": servers, "users": users }) def discord_login(request: HttpRequest): return redirect('https://discord.com/api/oauth2/authorize?client_id=707641033210593351&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fapp%2Foauth2%2Flogin%2Fredirect&response_type=code&scope=identify%20guilds') def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") def exchange_code(code: str): data = { "client_id": client_id, "client_secret": "secret", "grant_type": "authorization_code", "code": code, "redirect_uri": "http://localhost:8000/app/oauth2/login/redirect", "scope": "identify guilds" } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } validate_token = requests.post("https://discord.com/api/oauth2/token", data=data, headers=headers) credentials = validate_token.json() access_token = … -
Search and display one row from Django Rest Api
after followed many tutorials about how to integrate Django rest in React I succeeded to fetch data from my API like this, but when I try to fetch just one row by the ID it becomes difficult to do, so in my project, I can add employees and display them all, but the problem is when I try to search for a specific employee by his ID, this is the code which can display all the employees import React from "react"; class List extends React.Component { constructor() { super(); this.state = { data: [], Matricule: "", }; this.changeHandler = this.changeHandler.bind(this); } changeHandler(event) { this.setState({ [event.target.name]: event.target.value, }); // console.log(event.target.name); // console.log(this.state.Matricule); } fetchData() { fetch("http://127.0.0.1:8000/employee/") .then((response) => response.json()) .then((data) => { this.setState({ data: data, }); console.log(data); }); } componentDidMount() { this.fetchData(); } render() { const emp = this.state.data; const rows = ( <tr key={emp.id}> <td>{emp.Matricule}</td> <td>{emp.Nom}</td> <td>{emp.Prenom}</td> <td>{emp.Terminal}</td> <td>{emp.Fonction}</td> <td>{emp.Statut}</td> </tr> ); console.log(this.state.Matricule); return ( <div> <h1>Liste des employes</h1> <input value={this.state.Matricule} name="Matricule" onChange={this.changeHandler} type="number" className="form-control" /> <table className="table table-bordered"> <thead> <tr> <th> Matricule</th> <th>Nom</th> <th>Prenom</th> <th>Terminal</th> <th>Fonction</th> <th>Statut</th> </tr> </thead> <tbody>{rows}</tbody> <button className="btn btn-danger px-1 ">chercher</button> </table> </div> ); } } export default List; -
Saving user registration data from DRF to Postgresql database?
i am building an app with an user registration with the help of django rest framework, i want to store my user's data in my postgresql database, i can see my model on my pgAdmin but after made a post request to register my user i cant retrieve my data on the database. So how can i save those data on the database ? models.py from django.db import models # Create your models here. class User(models.Model): username = models.TextField() email = models.TextField() password = models.TextField() serializers.py from rest_framework import generics, permissions from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ( 'username', 'email', 'password') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user views.py from rest_framework import generics from rest_framework.permissions import AllowAny from .models import User from .serializers import UserSerializer class UserCreateAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) -
Creating Django model fields dynamically from method variables during migration
One of my app's models has a few pre-defined fields, let's say: class Data(models.Model) user = models.CharField(max_length=50) date = models.DateTimeField() It also has a few fields that are based on variables passed in to the methods of a class which I would like to name "method_variable". Below is a sample class from which I would like to add meth0_var0 and meth0_var1 as CharFields in the Data model. class A: def meth0(self, var0, var1) ... I would like to dynamically add those variables to my model whenever I migrate the database (basically just saving myself the labor of writing out all the fields as there are many). So far I have tried adding this to my models.py after defining the model: methods = {k: v for k, v in dict(A.__dict__).items() if '__' not in k} # get rid of __init__ and such for key in methods: args = [arg for arg in getfullargspec(methods[key]).args if arg != 'self'] # get rid of self / methods that don't have any input variables [setattr(Data, f'var_{key}_{arg}', models.CharField(max_length=50, default='Unrecorded')) for arg in args] # use what's left to create attributes in the class for migration When I try to run makemigrations it finds no new fields … -
How to implement auth0 loging, register, authorization, permission in Django?
I am looking for learning auth0 with Django. but not getting any resources for register, login, authorization, and permission. Can anyone help me with that? -
How to receive data from user Django Rest Framework
I want to receive data from users and pass the processed version. For example user passed JSON: {"first number": 3, "second number": 4}, and the web API should response addition of numbers like {"result": 7}. How to do it without writing to the database? My serializer.py looks like: class AdditionSerializer(serializers.Serializer): first = serializers.CharField() second = serializers.CharField() views.py: class AdditionView(APIView): @action(detail=False) def get_addition(self, request): try: serializer = AdditionSerializer(data=request.data) if serializer.is_valid(): first = serializer.validated_data(['first']) second = serializer.validated_data(['second']) response = {'result': first+second} return Response(response, status=status.HTTP_200_OK) else: return Response({"message":"error"}) except: None""" but it's doesn't work -
How to serialize a Join query set from several tables in Django Rest Framework
Sometimes, frameworks make things more complicated instead of simplify them. I would like to serialize a join like this one queryset = Cities.objects.raw("SELECT 1 as id, cities.name as ci, states.name as s, countries.name as co FROM cities JOIN states ON states.id = cities.state_id LEFT OUTER JOIN countries ON countries.id = states.country_id WHERE cities.name = %s", [city]) or like this one, if raw queries are not recommended city = self.request.query_params.get("cityname") As you can see this is a reverse join. The idea is to serialize a result set like this one 0: name: "Guadalajara" state: "Castilla La Mancha" country: "Spain" 1: name: "Guadalajara" state: "Jalisco" coutry: "Mexico" Two cities having the same name, but belonging to different states and countries. I need this to implement a sort of autocomplete feature. This is actually a pseudocode but it gives an idea about the kind of JSON result I would like to get. I read the documentation and I searched the internet, I found nothing clear about how to do this. I'm new to Django and I'm completely lost, this is a simple task that would be easy to do manually, but I have no idea about how to achieve this using Django Rest … -
rest framework gotten Request has no attr user
I have a problem when I using delete_product_view with api in post man I got this error: AttributeError: 'Request' object has no attribute 'uesr' [16/Jul/2021 22:25:33] "DELETE but actually when I using creat_product_view that have same code user = request.user ( after debugging i realized that problem comes from this piece of code) this is my urls.py from django.urls import re_path from .views import * app_name = 'product' UUID_REGEX = '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}' urlpatterns = [ re_path(r'product/(?P<slug>[0-9a-zA-Z-_]+)/', product_view, name='product api'), re_path(r'product/create/', product_view, name='product create api'), re_path(r'category/',category_view, name='category api') ] serializer : from rest_framework import serializers from product.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'title', 'cost', 'description' ] class ProductGetterSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='email' ) category = serializers.SlugRelatedField( read_only=True, slug_field='slug' ) class Meta: model = Product fields = [ 'title', 'cost', 'description', 'user', 'category', 'slug', ] viwes.py from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from product.api.serializer import * @api_view(['PUT', 'DELETE', 'GET', 'POST']) @permission_classes([IsAuthenticated, ]) def product_view(request, slug=None): method = request.method if method == 'PUT': return update_product_view(request, slug) elif method == 'DELETE': return delete_product_view(request, slug) elif method == 'GET': return get_product_view(request, slug) elif method == 'POST': return … -
Form field for a foreign key in ModelForm with too many choices for ModelChoiceField?
I have a simple foreign key relationship I want to use in a ModelForm, but without a ModelChoiceField. class Sample(models.Model): alt = IntegerField(db_index=True, unique=True) class Assignment(models.Model): sample = models.ForeignKey(Sample, on_delete=models.CASCADE) I want to have the AssignmentForm select the sample based on the contents of the sample's alt field. With a ModelChoiceField it would be like this: class SampleSelect(ModelChoiceField): def label_from_instance(self, obj): return obj.alt class AssignmentForm(ModelForm): sample = SampleSelect(queryset=Sample.objects.all()) class Meta: model = Assignment fields = ['sample'] The ModelChoiceField documentation says to use something else if the number of choices is large. Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items. I think I need a custom form field, but I cannot figure out how to do this. class SampleBAltField(IntegerField): def clean(self, value): try: return Sample.objects.get(alt=value) except Sample.DoesNotExist: raise ValidationError(f'Sample with alt {value} does not exist') This existing code should take an integer from the form and map it back to a foreign key, but I cannot figure out what to override to populate the field for a bound form from … -
Wagtail initDateChooser is defined for one app but not the other app?
I'm creating a portfolio site and I've deployed my code to an Ubuntu server on DigitalOcean. I have two apps within my project: a blog app and a portfolio app. For the page models I created in the blog app, the DateField works fine and the little calendar picker shows up when the page is created. For the portfolio app, however, the calendar picker doesn't activate. The error in the console reads: Uncaught ReferenceError: initDateChooser is not defined <anonymous> http://MYIPADDRESS/admin/pages/14/edit/:759 I checked the Network tab to see if all the stylesheets were loading. I don't see any 400 or 500 errors. Just 200 and 304. I've tried changing the field models to DateTimeField and the same problem occurs. Deleting and re-adding the models and re-migrating also does not fix the issue. So I'm not sure what else to check at this point. Could something have gone wrong during collectstatic? Should I run that again to see if that makes a differences? Any tips you can offer would be very much appreciated. -
How to add new line inside a <p> tag in html when using Django to pass data?
I have model of Players in Django which looks like this: class Player(models.Model): name = models.CharField(max_length=200, null=False, blank=False, default='') description = models.TextField(max_length=1000, null=True, blank=True) I pass the Player objects in the context: class playerView(request): players = Player.objects.all() context = {'players':players} return render(request, 'base/players.html', context) Now, I render the description in p tag of html using below code: players.html {% for player in players %} <p>{{player.name}}</p> <p>{{player.description}}</p> {% endfor %} But when I try to add description with newlines in it like: This is line one. This is line two. It renders data like this: This is line one.This is line two. I tried adding &#13 &#10 which I found in one of the answers is a new line character, but it doesn't work. I also tried adding \n and also tried adding br tag, but that also didn't work. Please help me with a solution. -
how filter posts for django-modeltranslation
I used Django ModelTranslation how can I filter language model.py class post(models.Model): title = models.CharField(max_length=255) text = models.TextField() views.py def home(request): all_posts = Post.objects.filter( ) -
Django form ignore validations on save vs submit
I am trying to create a Django form in which the user will have two options Save the form (temporarily) Submit the form What I am trying to do is to allow the users to save the form temporarily and after they have all the data they can come back, edit the form and make the final submission. The problem is that the form validation will not allow partially filled form to be saved. Is there any way I can ignore validations when "Save" is pressed whereas perform all the validations when "Submit" is pressed? I do not want to have 2 views. I want the same view with two buttons "Save" and "Submit" if Save is pressed some of the validations will be ignored (i.e. required field left empty due to the fact that the user might not currently have the information). But if the "Submit" is pressed, all the date should be validated. Please note that all the validations takes place backend with Django. Thanks -
How to save data to multiple models with one form?
a pretty noob here. I am trying to create a user profile at the time when the account is created using signals. I want all the fields of the user profile to be filled in sign up page. This is the user profile that I am trying to populate: class UserProfile(models.Model): user = models.ForeignKey(get_user_model(), verbose_name='user', on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) contact_number = models.CharField(max_length=11, default="0331232132") def __str__(self): return self.name This is my custom user model here: class CustomUserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): kwargs.setdefault("is_staff", False) kwargs.setdefault("is_superuser", False) return self._create_user(email, password, **kwargs) def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault("is_staff", True) kwargs.setdefault("is_superuser", True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **kwargs) class User(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() This is my user creation form that I am sending to template: class CustomUserCreationForm(UserCreationForm): password2 = forms.CharField( label=_("Confirm Password"), widget=forms.PasswordInput, ) name = forms.CharField() contact_number = forms.CharField( max_length=11 ) class Meta: model … -
cant save to a datebaseby use createview
cant save to a datebaseby use createview also del is not working too and url want it make all in one page It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. view.py from django.shortcuts import render , redirect from main_app.models import Widget from django.views.generic import ListView from django.views.generic.edit import CreateView, DeleteView from .forms import ADDForm def home(request): widget = Widget.objects.all() print(widget) count = Widget.objects.values('quantity') total = [{"quantity":0},] quantity =0 for c in count: quantity += c['quantity'] total[0] = quantity ADD_Form = ADDForm() return render(request,'main_app/widget_list.html', {'widget':widget,'ADD_Form': ADD_Form,'total':total}) class WidgetList(ListView): model = Widget class WidgetCreate(CreateView): model = Widget fields = '__all__' success_url = '/' def form_valid(self, form): form.instance.user …