Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resend account activation email
so I created a template where users can register on my site. After filling the registration form an activation email is sent to the users email address. In case the user didn't receive an email I want to make it possible to resend the activation email. How do I do this? Here is my code: views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMessage from django.conf import settings from .forms import UserSignUpForm from .token_generator import account_activation_token def signup_view(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('accounts/email_templates/account_activation.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() # TODO: resend activation email return HttpResponse('We have sent you an email, please confirm your email address to complete registration') else: form = UserSignUpForm() return render(request, 'accounts/signup.html', {'form': form, 'project_name': settings.PROJECT_NAME}) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models … -
error when pip install mysqlclient in mac
when I try to pip install mysqlclient for python show this error ERROR: Command errored out with exit status 1: command: /Users/als/Desktop/Projects/sin/venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/pip-egg-info cwd: /private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/ Complete output (12 lines): /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup.py", line 16, in <module> metadata, options = get_config() File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup_posix.py", line 61, in get_config libs = mysql_config("libs") File "/private/var/folders/30/y2trygfx15x0v9h9v8dt9dsc0000gn/T/pip-install-s44a4z2o/mysqlclient/setup_posix.py", line 29, in mysql_config raise EnvironmentError("%s not found" % (_mysql_config_path,)) OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django queryset with aggregation and filtered LEFT JOIN multiple levels deep
Simplified models are below. Basically think of this as: you have a bunch of Recipes and you have Users who can upload all the ingredients they have in their pantry. You can then tell them which Recipes they have ingredients for (and if they have ALL ingredients for a Recipe). Models class Recipe(models.Model): name = models.CharField(max_length=255) ingredients = models.ManyToManyField( 'Ingredient', blank=True, through='RecipeIngredient') class Ingredient(models.Model): name = models.CharField(max_length=255) type = models.CharField(max_length=255, blank=True) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe) ingredient = models.ForeignKey(Ingredient) amount = models.FloatField(_('amount'), null=True, blank=True) unit = models.ForeignKey(Unit, blank=True, null=True) class UserIngredient(models.Model): LIST_TYPE_CHOICES = [ ('PANTRY', 'My Pantry'), ('SHOPPING_LIST', 'My Shopping List'), ] user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=RELATED_NAME) ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, related_name=RELATED_NAME) list_type = models.CharField(max_length=255, choices=LIST_TYPE_CHOICES) SQL / Queryset SELECT r.id, r.name, COUNT(1) AS num_ingredients, COUNT(ui.ingredient_id) AS num_matched FROM core_recipe AS r INNER JOIN core_recipeingredient AS ri ON r.id = ri.recipe_id LEFT JOIN users_useringredient AS ui ON ( ri.ingredient_id = ui.ingredient_id ) AND ui.user_id = '<user_id>' AND ui.list_type = 'PANTRY' GROUP BY r.id, r.name HAVING COUNT(1) = COUNT(ui.ingredient_id) # Or, if we want Recipes the user has ANY ingredients for: # COUNT(ui.ingredient_id) > 0 What I have right now for the queryset to try to reproduce this: user_filter … -
Serialize ManyToManyFields with different serializers in ViewSets
I have a model with ManyToMany relations which I call containers. In my API I want to get the entry that match a certain ID in this container. For example, I want to have the container with the ID "2" in the beer_container. But of course only the container which is available in the TotalOrder. My model looks like this: class TotalOrder(models.Model): beer_container = models.ManyToManyField(BeerContainer, blank=True) foreign_beer_container = models.ManyToManyField(ForeignBeerContainer, blank=True) ..... My serializer: class TotalOrderSerializer(serializers.ModelSerializer): beer_container = BeerContainerSerializer(many=True) soft_drink_container = SoftDrinkContainerSerializer(many=True) .... class Meta: model = TotalOrder fields = '__all__' In the views.py I have my TotalOrderListCreate class, which returns the whole total order with its containers. And this works very well. class TotalOrderList(generics.ListAPIView): serializer_class = TotalOrderSerializer def get_queryset(self): table_number = 'table_number' try: table = Table.objects.filter(number=self.kwargs.get(table_number)) queryset = TotalOrder.objects.filter(table__in=table) except (Table.DoesNotExist, TotalOrder.DoesNotExist): return [] return queryset But now, I want to get one container with its ID from that TotalOrder. For example: api/total-order/1/beer_container/2. I have tried this way, but I don't know how to return my queryset into the TotalOrderSerializer because now I have for example the data of an BeerContainerSerializer. I've tried this, but without any luck. class TotalOrderDetail(generics.ListAPIView): serializer_class = TotalOrderSerializer def get_queryset(self): table_number = self.kwargs.get('table_number') order_id = … -
How to render a template from a new app on django-cookiecutter
I am having trouble with rendering a template from an app using Django-cookiecutter! I am using Django-cookiecutter for my project and I am trying to create a new blog app in my project and I have kinda done everything following this tutorial: Creating a blog part but I am stuck at the part where I am trying to render the template from my new app called algo_explained. I tried following the user app inside the sample project but no luck. Here's the link to my project on github Here's what I have so far: App views explain_algorithms/explain_algorithms/algo_explained/views.py from django.shortcuts import render from explain_algorithms.algo_explained.models import Post, Comment from explain_algorithms.algo_explained.forms import CommentForm #blog_index will display a list of all your posts. def blog_index(request): posts = Post.objects.all().order_by("-created_on") context = { "posts" : posts, } return render(request, "blog_index.html", context) app-specific URL explain_algorithms/explain_algorithms/algo_explained/urls.py from django.urls import path from . import views app_name = "algo_explained" urlpatterns = [ path("blog", views.blog_index, name="blog_index"), ] main project URL explain_algorithms/config/urls.py I do have admin and all other routes I just wanted to share what's important! urlpatterns = [ path("users/", include("explain_algorithms.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path("algo_explained/", include("explain_algorithms.algo_explained.urls", namespace = "algo_explained")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
testing django forms with pytest failing
I am not sure why the assertion below is failing. Can someone please give me a feedback, I am new to pytest with django. test.forms @pytest.fixture def product(): month = Month.objects.create(name="november", slug="november") month.save() user = User.objects.create(username="james", password="password") user.save() obj = Product.objects.create( user=user, name="broom", price=19.99, quantity=1, month=month, ) obj.save() data = { 'user':user, 'name':obj.name, 'price':obj.price, 'quantity':obj.quantity, 'month':month } form = ProductForm(data=data) yield form def test_product_form_with_data(product): assert True is not None assert True == product.is_valid() Below is what is am getting from the terminal. Traceback error. _______________________________________________________________________________________ test_product_form_with_data ________________________________________________________________________________________ product = <ProductForm bound=True, valid=False, fields=(name;price;quantity;month)> def test_product_form_with_data(product): assert True is not None > assert True == product.is_valid() E assert True == False E -True E +False tests/test_forms.py:42: AssertionError I would really appreciate a feedback to help me understand what I am doing wrong trying to test this form with data while using fixture. Looking at the data returned, I suspect that the user may be the problem because it is not returned but i tried different alternative and still same outcome. -
Detect URLs and #tags in Django CharField and add style to it
For now on I have in my template a paragraph like this <p class="...">{{ post.content }}</p> and if this Post's content contains a link or #hashtag it is rendered as a normal text with the rest of the post. How can I customize it? For example change text-color and add tag around it? -
Django - Annotate with count across ManytoMany relationships (refrase)
Django - Annotate with count across ManytoMany relationships I am not able to find the way to annotate a queryset with a count of how many times an element is used in a many-to-many relationship. class Profile(models.Model): [...] # Profile can have multiple roles roles = models.ManyToManyField('Role', blank=True) [...] class Role(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(blank=True, max_length=30) description = models.CharField(blank=True, max_length=300) [...] For example I would have 5 roles: Role1 Role2 Role3 Role4 Role5 And 2 profiles with following roles assigned: Profile1 Role 1 Role 2 Profile2 Role 1 Role 3 Role 4 I need to have the oposite than @ha-duy: Profile: name, role_count=2 Profile: name, role_count=3 Any ideas? Thanks! -
Django request.body always printing nonsense result (b'')
I am new to django , I started working on an existing Vuejs/Django project to easily understand how things are working . I wrote a new specific view in views.js def hello(request): print(req.body) return HttpResponse('hello') Then in urls.py I added the following: path('hello/',views.hello,name='hello') At first I tried sending a plain/text , but the print function shows the following b'' I tried printing request.data but it says WSGIRequest' object has no attribute 'data' I tried sending a JSON and using the following : body_string = request.body.decode("utf-8", "ignore") data = json.loads(body_string) Result : Expecting value: line 1 column 1 (char 0)Expecting value: or: data = json.loads(request.data.get('_content')) Result: 'WSGIRequest' object has no attribute 'data' none of that seems to be working . The app I am working on seems to be working fine but it has no specific URL that's way I am stuck as I have no example , even here I couldn't find anything that helps. -
Django DRF: How to make a todo item dependent to another item
Hi I am building an todo app according to a tutorial and I want to improve it a bit. I want a todo item dependent to another. For example if todo1 has dependency to todo2, it shouldn't allow me to check todo1 before complete todo2. Here is my models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User class TodoList(models.Model): name = models.CharField(max_length=200, default="blank title") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name = "Todo List" verbose_name_plural = "Todo Lists" ordering = ["name","created_at", "is_completed", ] def __str__(self): return self.name class TodoItem(models.Model): name = models.CharField(max_length=200, default="blank title") todo_list = models.ForeignKey(TodoList, on_delete=models.CASCADE, null=False) description = models.TextField(max_length=200, default="Blank text") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField(default=datetime.now(), null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) previous_item = models.IntegerField(default=0) class Meta: verbose_name = "Todo Item" verbose_name_plural = "Todo Item" ordering = ["id","created_at", "is_completed","deadline","name" ] def __str__(self): return self.name Views.py from django.shortcuts import render from rest_framework.views import APIView from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from rest_framework import viewsets, permissions, status from rest_framework.decorators import action, api_view from rest_framework.response import Response from … -
How to retrieve excluded form fields in ModelAdmin?
I have a simple CategoryForm which has a hidden field that automatically gets added during save on the front-end. In the Admin panel I would like is_staff users to be able to add a Category while the field is hidden there as well. To superusers I would like the field to be shown. How do I get the excluded fields back in my Admin form? Forms.py: class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('category', 'company',) exclude = ['company'] widgets = {'company': forms.HiddenInput()} Admin.py: class CustomCategoryAdmin(admin.ModelAdmin): form = CategoryForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not request.user.is_superuser: self.fields = ('category',) else: self.fields = ('category', 'company',) # this throws a key error because company is excluded return form def get_queryset(self, request): qs = super(CustomCategoryAdmin, self).get_queryset(request) if not request.user.is_superuser: return qs.filter(company=request.user.company) return qs.all() # To add company to company field while saving def save_related(self, request, form, formsets, change): super(CustomCategoryAdmin, self).save_related(request, form, formsets, change) company = request.user.company form.instance.company.add(company) -
Legacy Rails database in Django - Generic Relations - Object queries
I'm migrating a rails app to django. I am currently having some chalanges with relations and filters. There is a Posts table and a Articles table. They have categories trough a Categorizations table. The Categorizations table has categorizable_type,categorizable_id and category fields. So I can see in a existing Categorizations instance that the categorizable_type=Post and categorizable_type=Article and with the categorizable_id set to a eighter or... I've found the documentation for Django Generic Relations and it seems like thats basically whats in use. But I am not able to run any migrations on the database at this time. So I am wondering how I could make this work so I could do standard object filtration queries. Here is a example of the setup: class Articles(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=1000) class Posts(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=1000) class Categorizations(models.Model): id = models.BigAutoField(primary_key=True) category = models.ForeignKey(Categories, models.DO_NOTHING, blank=True, null=True) categorizable_type = models.CharField(max_length=1000, blank=True, null=True) categorizable_id = models.BigIntegerField(blank=True, null=True) So I would like to be able to do something like this: acticles_in_category_2 = Articles.objects.filter(categorization__catogory.id=2) The constrait is that I cant do any structural changes or migrations on the existing database. For now it looks like I might have to get around this … -
Why this Django Views decorators running reverse order?
there are 3 decorators: def a(view): def wrapper(request, *args, **kwargs): import time print("a") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper def b(view): def wrapper(request, *args, **kwargs): import time print("b") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper def c(view): def wrapper(request, *args, **kwargs): import time print("c") print(int(time.time())) time.sleep(1) return view(request, *args, **kwargs) return wrapper and decorated view: @c @b @a def hello(request): return HTTPResponse("hello\n") normally, it means below: c(b(a(hello()))) but it running below: a(b(c(hello())) it is OK for my task. i just using reverse. but so funny... do you know why it's mistaken? -
How can I draw a pigeon pedigree using HTML and CSS? Are there other ways to do that like jQuery or something else?
I develop a web app using python and django for managing pigeons and I want to draw their pedigrees. How can I do that? Which technologies I should use? -
How do i add HTML classes to built-in 'User' model? (Python Django)
I want to add some HTML classes to set of built-in Django model User that imports from from django.contrib.auth.models import User. I searched this information about 1 day, and found nothing. All answers only applicable to self created models, not User model. -
Django newbie's tragedy
Ok, first thing- I'm awful in programming (in all aspects) but I've to do this till monday so I'm trying my very best. My target is creating a website, that takes text (fragment of lyrics or title of song) and search for it in database (I'm using a .csv one). But no matter what I try I will end with "403 Forbidden". I'll be really frateful for any help html template forms views -
How to create an instance of a model through foreign key
I'm trying to find a way how to create or update an instance of a model through a foreign key. I have two models: Podcast and Guest which are connected via foreign key on guest_name. I'm using Youtube API to pull data from videos and regex to extract data needed for a set of fields in both models. I'm wondering if there to pass guest_name from Podcast model (which would be extracted via calculated filed in Podcast model) to Guest model and create or update (search via 'WHERE LIKE '%guest_name%') its instance on the creation of Podcast instance? Thank you for all the help class Guest(models.Model): guest_name = models.CharField(max_length=30) #full name occupation = models.CharField(max_length=20) short_bio = models.TextField() def __str__(self): return self.guest_name def get_absolute_url(self): return reverse("roll:guest_detail", kwargs={'pk':self.pk}) class Podcast(models.Model): category = models.CharField(max_length=255) # Needs to be a Dropdown date = models.DateTimeField(blank=True, null=True) #published date guest_name = models.ForeignKey(Guest, on_delete=models.CASCADE) # https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/ synopsis = models.TextField() index = models.IntegerField(blank=True,null=True,unique=True) video = EmbedVideoField(help_text="Remove anything after the Video ID",blank=False) # same like models.URLField() thumbnail_url = models.URLField(help_text="URL to the image",blank=True) # slug = models.SlugField(max_length=140, unique=True) # video_id = re.search('(\?v=)(.*)', self.video) # thumbnail = models.CharField(max_length=100,default="https://img.youtube.com/vi/{}/0.jpg".format(str(save(video)))) @property def thumbnail(self): video_id = re.search('(\?v=)(.*)', self.video) return 'https://img.youtube.com/vi/{}/0.jpg'.format(video_id.group(2)) @property def publishedAt(self): api_key … -
Am I overriding the save method on the model in a wrong way in django?
I am have a Profile model that extends the user model like so, class Profile(User): user = models.OneToOneField(User, parent_link=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=True) def save(self, *args, **kwargs): print('self.username') print(self.username) self.slug = self.username super(Profile, self).save(*args, **kwargs) I am trying to create a slug field for my model , so I override the save method to include the slug as the username of the user, the thing is when I create a new user with the command createsuperuser and print out the username of the user as you can see in the code .. it doesn't show anything , it doesn't show the provided username could this be the reason why I am having this problem ? of so how can I fix it ? -
How to render custom column on django-datatable-view
I'm having trouble finding the correct way of rendering HTML <h6> tags within django-datatable-view columns to use material.io icons as the content of the said column. I've referred to numerous resources including this, which seems outdated and unfortunately the closest I could get to having rendering some custom columns. Here's how my datatable definition looks like: class LeaveDatatable(Datatable): class Meta: columns = [ 'status' ] def render_colum(self, row, column): if column=='status': if row.status == 'Verified': #render-some-icons else: #render-another-icon class LeaveReview(DatatableView): model = Leave datatable_class = LeaveDatatable def get_queryset(self): return Leave.objects.filter(employee__id=self.request.user.id) Technically, what im trying to achieve is, if status == 'Verified', render <h6 class="material-icons col-sm text-center" style="color:green;" id='fulfilled-icon'>check_circle</h6> in the status column. Appreciate any help. Thanks! -
Django rest framework - how to use different model only for listView
I'm using Djano 2.1.5 with Django rest framework 3.7.7. I'm using ModelViewSet, i.e the relation between the view and the model is by routing with base_name and the serializer_class in the view. Now, for some reason, I want to create a database view for retrieving some calculated fields on 'list'. This view should be connected to a new model that is not managed (managed=False). My question is how can I connect between the new model and the listView specifically (and not other views of that model). my urls.py: router.register( r'container/(?P<container_id>[^/]+)/item/?', views.ItemViewSet, base_name='items') the item view: class ItemViewSet(viewsets.ModelViewSet): serializer_class = ItemSerializer I want to create a new unmanaged model that will look something like: class ListItemModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) calc_field = models.IntegerField(default=0) class Meta: managed = False db_table = 'list_item' So the question is how can I connect between the new model and the item listview? -
Django : Create custom object list in the view and pass it to template to loop over
I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information. My models are class CustomUser(AbstractUser): def __str__(self): return self.email class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_url = models.URLField(max_length = 200, blank = True) slug = models.SlugField(unique=True, blank=True) class subscription(models.Model): creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',) booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster') sub_value = models.FloatField(blank = True) sub_id = models.TextField(blank = True) status = models.BooleanField(default=False) dateSubscribed = models.DateTimeField(default=timezone.now) dateSubscriptionEnded = models.DateTimeField(default=timezone.now) paymentCount = models.FloatField(default= 0) I want to filter objects from subscription model like below subs = subscription.objects.filter(booster = request.user) Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks! -
How to set up the base language for a Django project i18n?
I have a Django project in spanish and I want that language to be the base language for localization. The Django documentation shows that it is possible, here. But doesn't explain how. -
Django Rest Framework many-to-many relation create the link
Since there are a few questions about m2m and DRF I'll try narrow down what specifically I'm interested in. Let's call the two models 'article' and 'publication'. Assume that: The 'publication' object already exists. The 'article' object may or may not exist. specifically: a) If a previous publication contained the article, then it will already be there. b) If not, then the article will need to be created. I want to send a post http request with the article data in the body and the publication id available from the url which will: a) if the article already exists, link it to the publication b) if the article does not exist, create it, and then link it to the publication Going for the 'default' strategy below did not work out. I can think of two ways to approach this problem: Overriding the create method on the article serializer. However I'm scepticle of doing that since this seems like a problem that should be common and have a non-custom solution. Creating an endpoint to directly work with the 'through' model. I could then split up the process into two steps (and 2 requests) where I first get_or_create the article, and then … -
Django TypeError unsupported operand type(s) for %: 'tuple' and 'dict'
I made a base model. And I want to inherit it and makemigrations model. But I catch an error. I don't understand the cause. I want you to tell me if you understand. from django.db import models from apps.models.commons import User from django.utils import timezone from django.utils.translation import gettext_lazy as _ import uuid class AbstractModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_user = models.ForeignKey(User, _('created_user'), related_name=('created_user',), editable=False) updated_user = models.ForeignKey(User, _('updated_user'), related_name=('updated_user',)) created_at = models.DateTimeField(_('created_at'), default=timezone.now, editable=False) updated_at = models.DateTimeField(_('updated_at'), default=timezone.now) class Meta: abstract = True from django.db import models from apps.models.commons.accounts import User from apps.utils.models.abstract import AbstractModel from apps.utils.models.region import CityModel from django.utils.translation import gettext_lazy as _ class Cast(AbstractModel): """Cast Model""" class Meta: db_table = 'Cast' image = models.ImageField(upload_to='aaa', default='profile/default.png') name = models.CharField(_('name'), max_length=30, blank=True) introduction = models.CharField(_('self introduction'), max_length=150, blank=True) establishment = models.DateField(_('establishment'), blank=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name -
UserCreationForm VS AbstractForm
What is the difference between AbstractForm and UserCreationForm ? Do I still need to code more to override make my custom form. Why do mention in class Meta that the model I use is User Model when using UserCreationForm ?