Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ProfileForm' object has no attribute 'user'
I'm learning Django. I have a model Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.TextField() skillstoteach = models.TextField() description = models.TextField() def __str__(self): return self.user.username And a form ProfileForm: class ProfileForm(ModelForm): class Meta: model = Profile fields = ['user', 'city', 'country', 'skillstolearn', 'skillstoteach', 'description'] I'm trying to use the view below... def profileupdate(request): profile = ProfileForm(request.POST) current = Profile.objects.get(user=profile.user.username) print(current) if profile.is_valid(): print('is valid') else: print('is not valid') return redirect('/thecode/userpage') ...to figure out if a user already exists, because I want to use the same form for both creating and updating. I get the error message "'ProfileForm' object has no attribute 'user'". How do I get the result for user that has been sent in the form? -
GCP: google app engine flexible + django 4.0.1 problem on deploy
I'm trying to deploy my Django 4.0.1 application to Google App Engine. But I'm receiving an error: Could not find a version that satisfies the requirement Django==4.0.1. On a localhost the app works fine. The same error I have with asgiref==3.5.0 The full text of this error: ERROR: Could not find a version that satisfies the requirement Django==4.0.1 (from -r requirements.txt (line 6)) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1. 6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8 .2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1. 9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, … -
Can someone help? Sending notifications to all users or some users in django forms
I want to send a single notification message to multiple users or all users. I have tried many to many fields but the sent to id won't save the i.d's of the users that i have sent the message to. Models.py class Notifications(models.Model): id=models.AutoField(primary_key=True) sent_to = models.ManyToManyField(CustomUser) message = models.TextField(null=True) message_reply = models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) Views.py def add_notification(request): notifs = Notifications.objects.all() users = CustomUser.objects.filter(is_staff=True) if request.method == 'POST': form = AddNotifForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.message_reply = "none" instance.save() sent_to = form.cleaned_data.get('sent_to') messages.success(request, f'Message has been successfully sent .') return redirect('add_notif') else: form = AddNotifForm() context={ 'notifs' : notifs, 'form' : form, 'users' : users, } template_name ='main-admin/add-notif.html' return render(request, template_name, context) Forms.py class AddNotifForm(forms.ModelForm): sent_to = forms.ModelMultipleChoiceField( queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Notifications fields = ['sent_to', 'message'] -
Django - export one txt file per row to local drive
I'm stuck with this as I can't find any relevant tutorials online. I would like to export all of the data in a model to the txt file format {actually xml but I think that's besides the point} where each row in the model is a seperate file and saved to a relative local path to the database with the folder and filenames for each being derived from two fields in the model I also need these to replace any existing files of the same name Where would I start? All I can do currently is export a txt file with all records together as a downloadable attachment. I currently have this working in Excel, but I want to cut the Excel step out. Here's what the Excel macro looks like: Sub export_misc() Dim wb As Workbook, ws As Worksheet Dim tags, ar, t Dim iLastRow As Long, r As Long, n As Long Dim c As Integer, i As Integer, k As Integer Dim sFolder As String, sFile As String, s As String Dim fso, ts Set fso = CreateObject("Scripting.FilesystemObject") tags = Array("plot:78", "dateadded:79", "title:80", "year:81", _ "mpaa:83", "releasedate:85", "genre:380", "studio:86", ":87", ":88") Set wb = ThisWorkbook Set ws … -
django-import-export, importing ManyToMany from XLSX
For my current project I need to import data from excelsheets format .xlsx to the django-admin. I'm struggling with the many2many relations that I have in my models. The importing feature just doesn't recognize the many2many fields and imports only the remaining fields (normal and foreignkey). Same goes for exporting, all fields except the many2many get exported into a excelsheet, although I dont need this feature, just tested it. For better understanding the code snippets from my models.py, admin.py, resources.py and widgets.py. I tried the default many2many widget -> in the TeacherResource in resources.py and I also tired overriding the default m2m widget -> StudyfieldWidget in widgets.py models.py class Translation(models.Model): de = models.TextField(unique=True) en = models.TextField(unique=True) def __str__(self): return self.de class Studyfield(models.Model): degree = models.CharField(max_length=50) title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+") def __str__(self): return self.title class Course(models.Model): number = models.CharField(max_length=50) title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+") studyfields = models.ManyToManyField("Studyfield", related_name="course", blank=True) def __str__(self): return self.title class Teacher(models.Model): name = models.CharField(max_length=50, blank=True) studyfields = models.ManyToManyField("Studyfield", related_name="teacher", blank=True) courses = models.ManyToManyField("Course", related_name="teacher", blank=True) def __str__(self): return self.name admin.py @admin.register(Translation) class TranslationAdmin(ImportExportModelAdmin): resource_class = TranslationResource ordering = ('id',) formats = [base_formats.XLSX] @admin.register(Studyfield) class StudyfieldAdmin(ImportExportModelAdmin): resource_class = StudyfieldResource ordering = ('id',) formats = [base_formats.XLSX] @admin.register(Course) class … -
Django Many to Many - polymorphic
In a Django application, I have three models: Service Product AppliedTax I want to create a many-to-many relationship between Service and AppliedTax and between Product and AppliedTax. Normally I would have an intermediate model (i.e. AppliedTaxTaxable) with three fields (applied_tax_id, taxable_type and taxable_id) and taxable_type + taxable_id would be a composite foreign key for each related model with taxable_type having as value the name of the related model (Service or Product in my case) and the taxable_id field the id of the related record of the respective model. I understand how to make it work with raw queries, but Is there a "Django" way to do that with a ManyToMany relationship? So far I had no luck with that. I don't have much experience with Django, but I hope there is a way to do that without using raw queries. Help :) -
Django error: Cannot assign must be an instance
Complete Error: ValueError at /dashboard/user/ticket/1/ Cannot assign "1": "TicketMessages.ticket" must be a "Ticket" instance. Request Method: POST Request URL: http://localhost:8000/dashboard/user/ticket/1/ Django Version: 4.0.1 Exception Type: ValueError Exception Value: Cannot assign "1": "TicketMessages.ticket" must be a "Ticket" instance. models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) ... def __str__(self): return str(self.id) class TicketMessages(models.Model): ticket = models.ForeignKey( Ticket, default=None, null=True, on_delete=models.CASCADE, ) admin_message = models.CharField(max_length=200) user_message = models.CharField(max_length=200) views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) if request.method == 'POST': user_form = TicketMessagesForm( request.POST, instance=TicketMessages(ticket=id)) if user_form.is_valid(): form_save = user_form.save(commit=False) form_save.ticket = obj.id form_save.save() else: user_form = TicketMessagesForm() return render(request, 'ticket-system.html', {'obj': obj, 'user_form': user_form}) Sense of the code: A ticket can be created, multiple messages can be assigned to the ticket. The created message (ticket_system_view) is then assigned to the respective ticket. It says the instance= has to be Ticket but then I would create a new Ticket? ^^ -
Q: Python Django Docker - Unknown server host 'db' error when trying to make a super user
I am trying to use the command python manage.py createsuperuser and docker exec -it veganetwork-db-1 python manage.py createsuperuser to add myself as a superuser to my microservices project, however when I try to run both of these commands I get Unknown server host 'db' in my Windows Powershell, here is the entire error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'veganetwork.auth_user' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 100, in handle default_username = get_default_username() File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py", line 140, in get_default_username auth_app.User._default_manager.get(username=default_username) File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return … -
How to represent a model with some data django
I have a model and it contains a foreign key I want when I call foreign key like this Entry.customer not to give me the id but the first name and last name. So I don't want every time to concate first name and last name but by default to take that Entry.customer.first_name + ' ' + Entry.customer.last_name -> Entry.customer How can I achieve this? -
Mustn't end this function in here?
def createRoom(request): form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): ***return redirect('home')*** #In here form.save() context = {'form' : form} return render(request, 'base/room_form.html', context) To my information, when python see a return in a function, the function is ending there. But in this code piece, python entering the if statement and applying the return command but after that, whereas python saw the return, function isn't ending . After the if statement, python, applying the return in the following code too. How can it be possible? Can anyone explain this please? -
how to filter objects by a specific choice
I have model like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) is_approved = models.CharField(max_length=64, choices=(('0', 'yes'), ('1', 'no')), blank=True) is_interviewed = models.BooleanField(default=False) how can I filter this model by is_approved field which is a choicefield? I wrote this line but doesnt work approved = ScientificInfo.objects.filter(is_approved__in='0').all() -
Represent string a model in django
I have a model and it contains a foreign key I want when I call foreign key like this Entry.foreignkey not to give me the id of that but some other data. How can I achieve this? -
How to set a timer inside the get request of an APIView?
I am trying to build a timer inside a get method in a DRF View. I have created the timer method inside the GameViewController class and what I am trying to achieve is that a every minute (5 times in a row) a resource object is shown to the user through the get request and a game round object is created. My View works at the moment, however the timer doesn't seem to be doing anything. I know this isn't exactly how things are done in django but this is how I need to do it for my game API for game logic purposes. How can I make the timer work? Do I need to use something like request.time or such? Thanks in advance. views.py class GameViewController: def timer(self): """Start a new timer as soon as a gameround has been started/created""" start_time = datetime.now() elapsed_time = None if start_time is not None: elapsed_time = time.perf_counter() """Stop the timer, and return the elapsed time""" if start_time is None: elapsed_time = time.perf_counter() - start_time return elapsed_time ... class GameView(APIView): def get(self, request, *args, **kwargs): ... round_number = gametype.rounds time = controller.timer() while round_number != 0: if time >= 1: random_resource = Resource.objects.all().order_by('?').first() … -
'str' object has no attribute '_encode_json'
I've been writing a test with RequestFactory to test one of my views, with the following code: class ViewTestCase(TestCase): @classmethod def setUp(self): self.factory = RequestFactory self.user = User.objects.create_user( first_name='tester', username='test1', password='123', email='testuser@something.com' ) def test_room_creation(self): payload = {"titlePlanning": "Test1","styleCards": "Fibonnaci","deck": ["1","2","3"]} request = self.factory.post('/room', payload) request.user = self.user response = BeginRoom.as_view()(request) self.assertEqual(response.status_code, 200) This is the data that I need to send to use POST: class BeginRoom(APIView): permissions_classes = (IsAuthenticated,) def post(self, request, format=None): data= self.request.data user = request.user name = data['titlePlanning'].strip() styleCards = data['styleCards'] cards = data['deck'] My problem is that whenever I run my tests I get the following error: data = self._encode_json({} if data is None else data, content_type) AttributeError: 'str' object has no attribute '_encode_json' What should I do? I'm lost from here and can't find anything related. Any help is appreciated! -
Credit card payment in Django (Python) with RedSys
I need to implement payment with credit card in a Django Project. But, I don't know how to start, and I can't find any information about do it. What's the best module to do the integration? The module is well documented? and it has code examples about the correct implementation. Please, if you know how to do it, help me. I'm collaborating with an ONG and we need to implement this for donations payments. Thanks. Regards, -
How to show in templates if a scheduled end of project is delayed based on end date in django?
I'm kinda stuck with a logic wherein if a project that is past it's due date and it's progress value is still not in 100% completion it should show a delayed text or if it's progress is still not in 100% but in the range of date end it should show an ongoing text. Models.py class Projects(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=255) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, limit_choices_to={'is_project_manager' : True}) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) project_pic=models.ImageField(upload_to='static/website/project-images') project_start_date=models.DateField(null=True) project_end_date=models.DateField(null=True) project_description=models.TextField(null=True) project_progress = models.PositiveIntegerField(null=True, default=0, validators=[ MaxValueValidator(100), MinValueValidator(0) ]) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) objects=models.Manager() class Meta: verbose_name_plural = 'Project' def __str__(self): return f'{self.project_name}' Views.py @login_required(login_url='user-login') def project_details(request, pk): projects = Projects.objects.get(id=pk) employed = Employee.objects.filter(project_site=projects) invents = Project_Inventory.objects.filter(project_site=projects) context = { 'projects' : projects, 'employed' : employed, 'invents' : invents, } template_name ='project-admin/project-details.html' return render(request, template_name, context) Project-details template <div class="col-md-11"> <div class="card"> <div class="card-header text-white"> Project Details </div> <div class="row p-3"> <div class="col-md-8"> <table class="table table-borderless"> <thead> <span class="h4">Project Information</span class="h4"> <hr> </thead> <tbody> <tr> <th scope="row">Project Name</th> <td>{{ projects.project_name }}</td> </tr> <tr> <th scope="row">Project Manager</th> <td>{{ projects.project_manager }}</td> </tr> <tr> <th scope="row">Start Date</th> <td>{{ projects.project_start_date }}</td> </tr> <tr> <th scope="row">End Date</th> <td>{{ projects.project_end_date }}</td> </tr> <tr> <th scope="row">Description</th> <td>{{ projects.project_description }}</td> </tr> <tr> <th scope="row">Progress</th> <td><div class="progress"> <div class="progress-bar" role="progressbar" … -
How to filter objects in Django by time since last 24 hours?
Assuming there's a starting time from 00:00 to 00:00 every day, how best are Django objects filtered by time, based on the current day? I initially came up with this: from django.utils import timezone yesterday = timezone.now() - timezone.timedelta(1) qs = Foo.objects.filter(date__gte=yesterday) ## yesterday = datetime.date.today() - datetime.timedelta(1) qs = Foo.objects.filter(date__gte=yesterday) However, this is not particularly right. I would prefer time starting exactly from 00:00 to timezone.now() -so something like Foo.objects.filter(date__range=[00:00, timezone.now()]) Thank you. -
Problem with Link when I'm sharing It with friends, which I deployed in Heroku
So I am learning Django and I was watching a Django tutorial so I started copying the code and then after everything was done I deployed it in Heroku, so when I was trying to share the link to one of my friends i came across this Now Dennis Ivy is the youtuber from whom I copied the code, So all I want to ask is that how come his name is appearing in this link of the project which I wrote and deployed. I don't want to take any credit, I'm just curious. -
How can I get this form to work and save the updated information?
I was successful at getting the form to appear on the modal which was an issue I had earlier, now I'm struggling to make this work. Any way to work my way around this?? Also I wanna check if method == 'POST' before checking if the form is valid but can't seem to find a solution.. views: class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'network/profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = User.objects.get(username__iexact=self.request.user) profile = Profile.objects.get(user=user) form = ProfileModelForm(instance=profile) confirm = False rel_r = Relationship.objects.filter(sender=profile) rel_s = Relationship.objects.filter(receiver=profile) rel_receiver = [] rel_sender = [] for item in rel_r: rel_receiver.append(item.receiver.user) for item in rel_s: rel_sender.append(item.sender.user) if form.is_valid(): form.save() confirm = True context["rel_receiver"] = rel_receiver context["rel_sender"] = rel_sender context["posts"] = self.get_object().get_all_authors_posts() context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False context["form"] = form context["confirm"] = confirm context["profile"] = profile return context Form: class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'bio', 'avatar') Model: class Profile(models.Model): first_name = models.CharField(max_length=64, blank=True) last_name = models.CharField(max_length=64, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=64, blank=True) avatar = models.ImageField(upload_to='avatars', default='avatar.png') background = models.ImageField(upload_to='backgrounds', default='background.png') following = models.ManyToManyField(User, related_name='following', blank=True) bio = models.TextField(default="No Bio..") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, … -
Manipulate with value list in Django
I have a value list in Django maca = Orders.objects.all().values_list("order_date") But I want to manipulate with order date. It shows up as YYYY-MM-DD and I want to change the format. For example maca = Orders.objects.all().values_list(datetime.strftime("order_date", "%d/%m/%Y") It is not only this case. Thanks a lot -
Django 'int' object is not iterable when trying to update object
I am getting this error when trying to update objects from false to True. here is my code: class ListNoti(LoginRequiredMixin,ListView): raise_exception = True model = Notifications template_name = 'notifications/notifications.html' def get_context_data(self, **kwargs): data = super(ListNoti,self).get_context_data(**kwargs) data['noti'] = Notifications.objects.filter(receiver=self.request.user,is_seen=False).order_by('-date').update(is_seen=True) return data .update(is_seen=True) raising this error TypeError at /notification/ 'int' object is not iterable -
How to have a new html site created when a button is clicked?
I'm working on a beginner django project trying to create a forum. User should be able to create new threads when they click on a button after they wrote their question and so on. So for each thread created there has to be created a new html file with some template and the new question. How can I do this? -
Running Several Server and Clients From a Shared Local Drive?
I have devolved a web application that manages prescriptions for a pharmacy. It uses a SQLite database, Django server, GraphQL API, and React on the frontend. It takes several weeks to get elevated privileges for any task so I have installed all of this software without admin rights (nodejs, npm, py, etc). All of the software is installed into a shared drive so all of the computers may access the files. Also, please note that all of the data must be local and can not be hosted by a third party; I also doubt they will be able to host it on a server themselves. So right now I have a .bat file that starts up the Django server and runs the React production build (npm run build, serve -s build). The problem is when several users try to use the React build it gives a Server Error 500 msg. My question is: Is there a easier way to run the Django/react builds without having to make one copy of the repository in the shared drive per user? Additionally, is it okay to have several Django servers connected to the SQLite database or should I do something else? -
TypeError:ForeignKey(['app_label.model_name']) is invalid.First parameter to ForeignKey must be either a model, a model name, or the string 'self'
I am trying to create a custom model in django. but when try to migrate , i get the error : TypeError: ForeignKey(['custom_models.CustomUser']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I have tried everything mostly answers are related to foreign key but i did not use ay foreign key relation in models here is my code: models.py : from django.db import models from django.contrib.auth.models import AbstractBaseUser , BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self , email , username , password=None): if not email: raise ValueError('this is not correct email.') if not username: raise ValueError('this is not correct username.') user = self.model( email = self.normalize_email(email), usename = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self , email , username , password ): user = self.create_user( email = self.normalize_email(email), username = username, password = password ) user.is_admin=True user.is_staff=True user.is_superuser=True user.is_active=True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): username = models.CharField(max_length=60 ) email = models.EmailField(max_length=60 , verbose_name='email' , unique=True) date_joined = models.DateTimeField(auto_now=True , verbose_name='date joined') last_login = models.DateTimeField(auto_now=True , verbose_name='last login') is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=False) is_superuser= models.BooleanField(default=False) hide_mail= models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = 'username' objects = CustomUserManager() def __str__(self): return … -
Django Model: ForeignKey and Relations
I have 2 models: class Post(models.Model): pass class Vote(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(django.contrib.auth.models.User) I want to allow logged User to make a vote on Post's Admin site. I think about 3 solution as below: Add 'voted' field to Post model. Customize Post's Admin forms by add a Button control and implement do_vote() function in Post model to call when the Button is clicked. Do you have any other solutions? Additionally, I don't know how to implement 2 above solutions. Could you give me some lines of code?