Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep user logged in django
I made my login in the application. Then I go to the screen that list all the users in my database. When I select an especified user I lost my user that is logged. So, how can I keep my user in all the application? My views.py that list all the users. In this time, the url shows my user (http://localhost:8000/os/acesso/consultausuario/9) def acesso_consultausuario(request, id=None): instance = get_object_or_404(usuario, id=id) queryset = usuario.objects.all().order_by('dat_criacao_usuario') instancia_usuario_filter = usuariofilter(request.GET, queryset=queryset) table = usuariotable(instancia_usuario_filter.qs) RequestConfig(request, paginate={'per_page': 25}).configure(table) paginator = Paginator(instancia_usuario_filter.qs, 5) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: # if page is not an integer, deliver first page response = paginator.page(1) except EmptyPage: # if page is out of range, deliver last pages of results response = paginator.page(paginator.num_pages) context = { "instance": instance, "filter": instancia_usuario_filter, "response": response, "table": table, } return render(request, 'consulta/consulta_usuario.html', context) # Show an especified user that I selected before. def acesso_consultausuariodetalhe(request, id=None): # Instância do usuário que foi selecionado na consulta instance = get_object_or_404(usuario, id=id) form = statususuarioForm(request.POST or None) if form.is_valid(): # All validation rules pass instance_status = form.save(commit=False) var_status = form.cleaned_data['statususuario'] instance_status = statususuario.objects.get(desc_statususuario=var_status) # Salva o status atual na tabela logstatususuario instance_log = logstatususuario.objects.create(usuario = instance, statususuario … -
Django ORM returning timezone unaware datetime
I have an expensive query that I'd like to cache, but I keep getting the following error: query = MyModel.objects.all().annotate( max_time=Max(Case(When(m2mthrough__somebool=True, then=F('m2mthrough__rel1__rel2__sometime')), output_field=models.DateTimeField())), for obj in query: obj.cached_max_time = obj.max_time obj.save() ... RuntimeWarning: DateTimeField MyModel.cached_max_time received a naive datetime (2017-01-01 01:23:45) while time zone support is active. I thought datetime fields pulled from the database were always timezone aware. Is this related to the use of Case(When(...)) or do I really have some timezone unaware dates stored in the database? -
Reading in specific fields from related model
Once again, I find myself struggling with Django's ORM to get what would be a simple SQL query. Its me, that much I know. I just don't find it as simple and intuitive as it claims to be, although it probably is if I could just get it to click for me. Anyway, I've this simple relationship setup and working, but now I need to modify it and am running into an issue. It was "get the names of products related to the current user," but now it is "get the names, start dates, and ending dates of products related to the current user." For the former, I was getting it with the following: # models.py class Products(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=16) name = models.CharField(max_length=255, blank=True, null=True) short_name = models.CharField(max_length=128) start_date= models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) users = models.ManyToManyField(User, through='UserToProduct') stage = models.CharField(max_length=32, blank=True, null=True) def __str__(self): return self.name class Meta: db_table = 'Products' class UserToProduct(models.Model): user = models.ForeignKey(User, related_name='user_product', db_column='user_id', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='product', db_column='product_id', null=True, on_delete=models.CASCADE) stamp = models.DateTimeField(blank=True, null=True) def __str__(self): return u'%s' % self.product class Meta: db_table = 'User_to_Product' unique_together = ('user', 'product') ordering = ['-product'] And with the following … -
link parameter shows up as HTML instead of just the value
When I construct the URL for a link with parameters, parameter value in link address shows up as HTML form instead of value. This is how I am generating the link in my template: <a class="btn btn-success btn-block" href="{% url 'facility_page' facility_id=facility.id %} " role="button">Edit</a> This is how link address shows up: http://127.0.0.1:8000/facility/(%3FP%3Cinput%20type=%22hidden%22%20name=%22facility-0-id%22%20value=%221%22%20id=%22id_facility-0-id%22%3E%5B0-9%5D+)/ I was expecting the link to look like this: http://127.0.0.1:8000/facility/1 What am I doing wrong here? -
deleting objects, going from ListView to DeleteView
I have a ListView and from this I want to delete some objects using DeleteView. What I have so far: views.py class BlockListView(ListView): model= Classroom def get_context_data(self, **kwargs): context = super(BlockListView, self).get_context_data(**kwargs) classroom_blocks = Classroom.objects.all() context = {'classroom_blocks': classroom_blocks} return context list_classroom_view = BlockListView.as_view() class BlockDeleteView(DeleteView): model = Classroom success_url = reverse_lazy('classroom:blocklist') delete_classroom_view = BlockDeleteView.as_view() urls.py urlpatterns = [ path(r'^$', views.index, name='index'), path('submitted', views.submitted, name='submitted'), path('classup/', create_classroom_view, name='classroom'), path('block/', views.block, name='block'), path('blocklist/', list_classroom_view, name='blocklist'), path(r'^(?P<pk>\d+)/blockDelete/$', delete_classroom_view, name='blockDelete'), ] template for listview: {% for block in classroom_blocks %} <li>{{ block.get_course_block_display }}<a href ="{% url 'classroom:blockDelete' block.id %}" class="button" style="color:#999999">DELETE</a></li> {% empty %} <li>No classes set up yet.</li> {% endfor %} template for confirm delete: {% block body %} <h1>Confirm Delete</h1> <form action="." method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ object.course_block }}"?</p> <input type="submit" value="Confirm" /> </form> {% endblock %} After I click the delete button from the listview, the url generated is http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/$ and this directs to the confirm delete page. After confirming delete, I get a 404 error with Request URL: http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/ -
How can I put a 'Clock-in' button/form at the top of a navbar with CBVs?
I'm using CBVs and need to put a 'clock-in' and 'clock-out' button at the top of one of my navbars. I'm kind of a noob and so far I've only put forms in their own separate pages. I basically want users to be able to click 'clock-in' when they get to work, and 'clock-out' when they leave, the only thing is since its at the top of my navbar it will be part of the layout.html that all other pages extend from. Is there a good way to do this? Thanks -
django channels authentication over script
I have a Django Channel project and i want to connect to a Websocket over a script. I am useing the code from the example as a python websocket-client I use this I get the cookies from login in over script this is the result 'csrftoken': 'NGl4QuroPpp41zzsxODqdNv7UoaOmrNdbYc5H7AwzHajvLsUrHVJmwj7K1fdwBcC', 'sessionid': '5ccdsjby3g65xtltdppcdi0h8mmlr7h0 and I am using it the webclient like this ws = websocket.WebSocketApp("ws://127.0.0.1:8000/chat/stream/", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, cookie=cookies) ws.on_open = self.on_open ws.run_forever() I don't know if the cookies are somehow wrong or I need to use anothe websocket client. -
Django shopping cart - items added to basket (database), but can't display them
This is my models.py (I took out irrelevant classes). One model for a product, one for an order and one for an item in an order. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Producto(models.Model): nombre = models.CharField(max_length=250) productor = models.ForeignKey(Productor, on_delete=models.CASCADE) tipo = models.CharField(max_length=250) foto = models.CharField(max_length=1000, default="https://i.ebayimg.com/00/s/MTAyNFg4Mjg=/$(KGrHqNHJCME63(5DhVhBO0CQKUU)!~~60_10.JPG?set_id=880000500F") precio = models.IntegerField(default=0) def __str__(self): return self.nombre class OrderItem(models.Model): producto = models.OneToOneField(Producto, on_delete=models.SET_NULL, null = True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now = True) date_ordered = models.DateTimeField(null=True) def __str__(self): return self.producto.nombre class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(null=True) def get_cart_items(self): return self.items.all() def get_cart_total(self): return sum([item.producto.price for item in self.items.all()]) def __str__(self): return '{0} - {1}'.format(self.owner, self.ref_code) This is my views.py (also took irrelevant classes out) def add_to_cart(request, **kwargs): #get the user profile user_profile = get_object_or_404(UserProfile, user=request.user) #filter products by id producto = Producto.objects.filter(id=kwargs.get("pk", "")).first() #create OrderItem, of the selected product order_item = OrderItem.objects.get_or_create(producto=producto) #WORKS #create order associated with the user user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False) #works, aparently user_order.items.add(order_item[0]) new_object = OrderItem(producto=Producto.objects.filter(id=kwargs.get("pk", "")).first()) user_order.ref_code =random.randint(0,100000) user_order.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) And my relevant url urlpatterns = [ path('add_to_cart/<pk>', add_to_cart, name="add_to_cart") ] So when someone clicks on the following button, the item gets added … -
DRF ViewSet Returns QuerySet With Empty Values
I have a DRF ViewSet called "QueryCriteriaViewSet" which I'm using in a query builder which allows users to select a field and then select from related criteria. So, for example, a user can select the "reg_status" field and then select from the related criteria of "Active" and "Inactive". This works totally fine when I select a field from the main "person" model. But I'm running into problems when I select a field from a related model like the "lookup_party" model. The weird thing though, is that when I print the queryset to the console it works perfectly, but when I get call the API it returns a list of empty objects. As a further example, here's what happens when I make the calls: api/querycriteria/?fields=reg_status returns: [ {"reg_status": "Active"}, {"reg_status": "Inactive"} ] while api/querycriteria/?fields=party__party_name returns: [ {}, {}, {}, {}, {} ] even though when I print(queryset) prior to returning the queryset, the following is printed: <QuerySet [{'party__party_name': None}, {'party__party_name': 'Democratic'}, {'party__party_name': 'Non-Partisan'}, {'party__party_name': 'Registered Independent'}, {'party__party_name': 'Republican'}]> Here's the full ViewSet: class QueryCriteriaViewSet(DefaultsMixin, viewsets.ModelViewSet): serializer_class = QueryCriteriaSerializer def get_queryset(self): fields = self.request.GET.get('fields', None) queryset = Person.objects.values(fields).distinct() print(queryset) return queryset def get_fields_to_display(self): fields = self.request.GET.get('fields', None) return fields.split(',') if fields else … -
UpdateView template only displays pk of a related model, How can a get it to display other fields?
I'm a beginner in django and my problem is rather aesthetic... Right now my template looks like this: editSubcategory template the first option in the select tag is the category foreign key previously selected in the CreateView... it would be nice if instead of just showing the foreign key i could also show the name field of the category model to look like the other options in the select tag. Here is my code: models.py class Categories(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Subcategories(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey( 'Categories', on_delete=models.CASCADE, ) def __str__(self): return self.name views.py from django.views.generic import UpdateView from django.urls import reverse_lazy from .models import Subcategories from .forms import SubcategoriesForm class EditSubcategory(UpdateView): model = Subcategories form_class = SubcategoriesForm template_name = 'inventory/edit/editSubcategory.html' success_url = reverse_lazy('inventory:subcategoriesList') def get_context_data(self, **kwargs): context = super(EditSubcategory, self).get_context_data(**kwargs) context['categories'] = Categories.objects.all() return context forms.py from .models import Categories from .models import Subcategories class CategoriesForm(forms.ModelForm): class Meta: model = Categories fields = ('name',) class SubcategoriesForm(forms.ModelForm): class Meta: model = Subcategories category = forms.ModelMultipleChoiceField(queryset=Categories.objects.all()) fields = ('name', 'category') urls.py path('subcategories/<int:pk>/edit', views.EditSubcategory.as_view(), name='editSubcategory'), editSubcategory.html <form enctype="multipart/form-data" action="" method="POST" id="editSubcategoryForm"> {% csrf_token %} <div> <fieldset class="module aligned"> <div class="form-row field-name"> <div> <label class="lead">Name: </label> <input … -
Invalid HTTP_HOST header: 'www.mysite.com' in Django
i have a problem with my localhost on Django Invalid HTTP_HOST header: 'www.mysite.com'. You may need to add 'www.mysite.com' to ALLOWED_HOSTS. in my settings i write ALLOWED_HOSTS = ['127.0.0.1', 'www.mysite.com'] but the error continue to appear :s -
Does Django's reverse() function take in a list as a parameter?
I need to invoke Django's reverse() method to construct a URL for a certain view function style_specific. Its entry in urls.py is below: Figure 1 url(r'^(?P<jewelry_type>[A-Za-z0-9]+)/(?P<jewelry_style_user>[A-Za-z0-9]+)/(?P<jewelry_id>[0-9]+)/$',views.style_specific,name="style_specific"), I'm also using Algolia, (a search engine) that plugs its own parameters into the constructed URLS, so I need to use reverse() to insert placeholders that can then be manipulated by Algolia. This previously worked when I called reverse twice -- Figure 2 specific_url = (reverse('jewelry:specific_method',args=[model_name,177013,1337]).replace('1337','{{objectID}}')).replace('177013','{{jewelry_style}}') where model_name is a parameter passed into the view function constructing style_specific's URLs, and 177013 and 1337 are placeholders that get replaced eventually. However, this approach is a hackish one that will get hard to maintain later. To that end, I wanted to replace this solution with something more flexible, along the lines of this SO answer. Ideally, the placeholders/replacements would be determined by a dictionary replace_parameters defined like Figure 3 replace_parameters={'placeholder_1':'replacement_1','placeholder_2':replcement_2} #and so on Unfortunately this is where my problem comes in. In Figure 2, the parameters is passed into args a hard-coded list. (Or at least that's what the syntax appears as) The solution I attempted to overcome this obstacle was to call replace_parameters's keys as a list -- that is, list(replace_parameters.keys()) par this SO answer. … -
Saving Google credentials in Django: use a ForeignKey or a OneToOneField to the User?
I'm working on implementing a Google OAuth2 authorization flow in a Django web app, following the Flask example given at https://developers.google.com/api-client-library/python/auth/web-app. I'm at the point where I'd like to implement the action item (mentioned in the comments) of saving the credentials to a persistent database instead of to the session. I've noticed that there are some sample Django projects which use Google's deprecated oauth2client. One example, from https://github.com/google/google-api-python-client/blob/master/samples/django_sample/plus/models.py, is: from django.contrib.auth.models import User from django.db import models from oauth2client.contrib.django_util.models import CredentialsField class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True) credential = CredentialsField() I'm questioning whether id should be a ForeignKey, or whether a OneToOneField would be more apt? Here is my adaptation so far: from django.db import models from django.contrib.postgres.fields import ArrayField from .timestamped_model import TimeStampedModel from .user import User class GoogleCredentials(TimeStampedModel): """ Model for saving Google credentials to a persistent database (cf. https://developers.google.com/api-client-library/python/auth/web-app) The user's ID is used as the primary key, following https://github.com/google/google-api-python-client/blob/master/samples/django_sample/plus/models.py. (Note that we don't use oauth2client's CredentialsField as that library is deprecated). """ id = models.ForeignKey( User, primary_key=True, limit_choices_to={'is_staff': True}, # Deleting a user will automatically delete his/her Google credentials on_delete=models.CASCADE) token = models.CharField(max_length=255) refresh_token = models.CharField(max_length=255) token_uri = models.CharField(max_length=255) client_id = models.CharField(max_length=255) client_secret = models.CharField(max_length=255) scopes … -
unable to get id field
I am having trouble getting id or pk field of the model. The reason I want to get that field is so that I can generate a custom URL for users to go to and edit their profile. What am I missing here? This is how my ModalForm looks like: forms.py class ProfileForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=True, help_text='Please enter your first name.', label="First Name") last_name = forms.CharField(max_length=30, required=True, help_text='Please enter your last name.', label="Last Name") def clean(self): super(ProfileForm, self).clean() class Meta: model = DoctorProfile fields = ( 'first_name', 'last_name') This is how my Model looks like: models.py class DoctorProfile(models.Model): user = models.OneToOneField(MMUser, related_name='xxx', on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) This is how my template looks like: template.html <p> {{ userprofile.first_name }} </p> <p> {{ userprofile.last_name }} </p> <p> {{ userprofile.id }} </p> <a class="btn btn-success btn-block" href="{% url 'details_page' userprofile.id %} " role="button">View Details</a> This is how my view looks like: views.py def showlittledetails(request): userprofile = ProfileForm(instance=request.user.xxx, prefix='userprofile') return render(request, template_name="user/profile.html", context={'user': user, 'userprofile': userprofile}) -
"ManagementForm data is missing or has been tampered with" error returned when trying to save a form on Admin
I have an ArrayModelField on my Document model but when I tried to save the values on the Admin, it returned with a ['ManagementForm data is missing or has been tampered with'] error. I've been googling this error and it only shows up when formsets are used, but I haven't even used formsets here. I think my syntax is correct with files having both model_container and model_form_class. Am I missing something? Or should I rewrite my code and use formsets instead? class Document(TimestampedModel): files = models.ArrayModelField( model_container=DocumentFile, model_form_class=DocumentFileForm, default=[], blank=True, null=True, ) class Meta: abstract = True class DocumentFile(TimestampedModel): filename = models.CharField(max_length=250) file = models.FileField( _('File'), null=True, blank=True, default=None ) -
django csrf_token inside html in python file
In my models.py I have a helper function with passes some html into a list. I then use that list in views.py. I have been getting a CSRF verification failed, error. Relevant code in models.py below f = """<form action="/solutions/" method="post"> <input type="submit"> </form>""" I have tried many things to correct the error including the code below f = """<form action="/solutions/" method="post"> {j} <input type="submit"> </form>""".format(j=django.middleware.csrf.get_token(request)) When I do this however I get a 'function' object has no attribute 'META'error. Inside my templates I use {% csrf_token %} but I haven't had success using this inside my helper function. I have tried doing something like the code below. But have not got it to work either f = """<form action="/solutions/" method="post"> {% csrf_token %} <input type="submit"> </form>""" -
How to structure Django models for pages and rich text
I am working on a Django app and I'm having some issues with the structuring of my models. What I have is 3 models Topic, Video, and Document, and the video and document models are in many to many relationship with the Topic model, like so: class Topic(models.Model): name = models.Charfield(max_length=20) videos = models.manytomanyfield('Video', blank=True) docs = models.manytomanyfield('Document', blank=True) class Video(models.Model): title = models.Charfield(max_length=20) videourl = models.Charfield() class Document(models.Model): title = models.Charfield(max_length=20) doc = models.Textfield() So I'm having two problems; -First, I want to have the document Model to be a rich text document, like in Google Docs where a user on the site can write a document and put images in the document. How do I create a model that can support this? -Second, I want to have multiple Video and Document objects for each Topic object and have each Video and Document have there own page and have those pages have a specific order (ie. video1, video2, document1, video3, document4, etc...). How can I keep track of what page number each document or video is? Thank you for the help! -
How to access current user in admin.py
In my admin.py file I am trying to display a time as the logged in users timezone. If I have something like below how can I pass in the request also to access the request.user.userprofile so I can dynamically set the timezone? def time_clicked(self, instance): local_tz = pytz.timezone('America/Chicago') local_dt = instance.click_time.replace(tzinfo=pytz.utc).astimezone(local_tz) return mark_safe("{0}").format(local_tz.normalize(local_dt).strftime('%b %d, %Y, %I:%M %p')) -
Django - Upload PDF and Excel file to mysql database
I have written a code to upload an excel sheet and save the contents to mysql database. Below is the code to upload the file in memory. form = UploadFileForm(request.POST,request.FILES) if form.is_valid(): file_in_memory = request.FILES['file'].read() wb = load_workbook(filename=BytesIO(file_in_memory), data_only=True) Now, I want to upload a PDF file and save the path to mysql database using the same function. For instance, If excel has record A then there is an associated PDF file which I have to link. How do I handle this situation? I am aware of multi-file upload but I assume that will save the file path to the database directly. -
Django: Accessing ForeignKey fields and creating new relations based on them
I'm fairly new to Django I'm trying to build a multichat app using Django 2.0.5 and my models are the following: class DateTimeModel(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Room(DateTimeModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False ) members = models.ManyToManyField(User) def __str__(self): ... class Message(DateTimeModel): sender = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) text = models.TextField() def __str__(self): ... What I want to do: I want to set the database scheme such that each message knows who its recipients are in the room that it belongs to and somehow stores whether each member in that room has 'seen' the message. I am having a tough time trying to see how I could make it work. Thanks in advance! Ahmed -
Mount host system /app as read only inside docker container
How would you mount the host systems /app directory as read only within the docker container? Use case: developing a Django application running inside a docker container, and you want Django to reload each time changes are made to /app code on the host system. -
Django-Tables2 add extra columns from dictionary
I apologize if this question has been asked before but I couldn't find my specific use case answered. I have a table that displays basic product information. Product details such as price, number of sales, and number of sellers are scraped periodically and stored in a separate database table. Now I want to display both the basic product information and scraped details in one table on the frontend using tables2. To do this, I wrote a function in my Product model to fetch the latest details and return them as a dictionary this way I can use a single Accessor call. # models.py class Product(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=256) brand = models.ForeignKey(Brand) category = models.CharField(max_length=128, choices=CATEGORY_CHOICES) def __unicode__(self): return self.name def currentState(self): currentDetailState = ProductDetailsState.objects.filter( product=self ).latest('created_at').rank # return current details as a dictionary return { price: currentDetailState.price, num_sellers: currentDetailState.num_sellers, num_sales: currentDetailState.num_sales } class ProductDetailsState(models.Model): product = models.ForeignKey(Product) created_at = models.DateTimeField(auto_now_add=True) price = models.DecimalField(max_digits=6, decimal_places=2, null=True) num_sellers = models.IntegerField(null=True) num_sales = models.IntegerField(null=True) def __unicode__(self): return self.created_at # tables.py class ProductTable(tables.Table): productBrand = tables.Column( accessor=Accessor('brand.name'), verbose_name='Brand' ) currentRank = tables.Column( accessor=Accessor('currentRank') ) class Meta: model = Product ... How do I now use this returned dictionary and split it … -
Customize template tags in Django to filter featured_posts in a blog
I have taken a hint from this post Customising tags in Django to filter posts in Post model I have created the template tag but I am not sure how to use it in my html. I have a home.html where I want to show three featured post. I am looking for something like {% for post in featured_post %} and then show the post detail. Also, do I necessarily need to create a featured_posts.html as in the above post because I don't want any extra page for the featured post. I just want them to add on my home page in addition to other stuff. -
How to delete products from inventory in Django
What I want: I have the model classes named Book and Issue. In Book there is a field named quantity that defines how many books are there. When the Admin issue a book to a student, there will be a -1 in quantity. how may I implement this. N.B: I want to implement this is Django Admin Dashboard -
NOT NULL constraint failed: accounts_user.password while updating data
I got error NOT NULL constraint failed: accounts_user.password while updating the data from Form. I this program i'm creating Custom User Model. Everything works fine but, while updating data from admin form I got this error. modles.py from phonenumber_field.modelfields import PhoneNumberField from django.db import models from django.utils import timezone from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def _create_user(self, username, email, password, first_name, last_name, **extra_fields): now = timezone.now() if not username: raise ValueError('User must have a username.') else: username = username.lower() if not password: raise ValueError('Password required!') email = self.normalize_email(email) user_obj = self.model( username = username, email = email, first_name = first_name, last_name = last_name, #is_staff = is_staff, #is_active = is_active, #is_admin = is_admin, #date_of_birth = date_of_birth, ) user_obj.set_password(password) user_obj.save(using = self._db) return user_obj def create_superuser(self, username, email, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_admin',True) return self._create_user( username = username, email = email, password = password, first_name = first_name, last_name = last_name, **extra_fields ) def create_user(self, username, email, password, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_admin',False) return self._create_user( username = username, email = email, password = password, first_name = first_name, last_name = last_name, **extra_fields ) def create_webuser(self, username, email, password, firstname, first_name, last_name, **extra_fields): extra_fields.setdefault('is_staff',False) extra_fields.setdefault('is_admin',False) return self._create_user( username = username, email …