Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
crontab is not working with docker django
I'm setting up the cron job in my Django project, when I go to add the corn using this command python manage.py crontab add in my docker container so I got the following error. error: /bin/sh: 1: /usr/bin/crontab: not found settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('0 0 * * *', 'projects.views.notifications_cron') ] and I want to run my corn job after every 24 hours at 12am midnight. -
Getting an "Integrity Error Exception Value: NOT NULL constraint failed" in my Django application
I keep getting an integrity error for a particular table on my database - the review table, whenever a user tries to review a selected movie. I have gone through my codes line by line but can't seem to find the error. Please help! I always get an "IntegrityError Exception Value:NOT NULL constraint failed: movieworld_review.review_number" whenever the user tries to review a movie. I even tried setting the review_number to null=True, yet a new integrity constraint pops up, this time it is that "NOT NULL CONSTRAINT FAILED: MOVIEWORLD_REVIEW.MOVIE.ID". BELOW ARE MY CODES FOR THE VIEW AND MODEL: MODELS: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') picture = models.ImageField(upload_to = 'profile_images', blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) SIZE = 250, 250 if self.picture: pic = Image.open(self.picture.path) pic.thumbnail(SIZE, Image.LANCZOS) pic.save(self.picture.path) def __str__(self): return self.user.username class Genre(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(null=False, unique=True) def get_absolute_url(self): return reverse('genres', args=[self.slug]) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.title.replace(" ", "") self.slug = slugify(self.title) return super().save(*args, **kwargs) class Movie(models.Model): imdbID = models.CharField(max_length=20, blank=True) Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank = True) Genre = models.ManyToManyField(Genre, blank=True) Language = models.CharField(max_length=250, blank=True) Poster = models.ImageField(upload_to='movies', blank = True) Poster_url = models.URLField(blank=True) TotalSeasons … -
python3 manage.py migrate gives error about field even when it is deleted from the model class
Every time I run python3 manage.py migrate I get the same error about one of the fields in the model class. Even after deleting the field, the same error occurs. This is what the model class looks like: class Events(models.Model): name = models.CharField(max_length=200, null=True) date = models.DateTimeField(editable=True, null=True) sport = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) num_seats = models.IntegerField(null=True, blank=True) creator = models.CharField(max_length=200, null=False) And this is what the error looks like: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'IntegerField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 22, in <module> main() File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 253, in handle post_migrate_state = executor.migrate( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 126, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 156, in _migrate_all_forwards state … -
Django Query many to many field count miscalculation
I am creating a Django Blog Website and I am stuck at one point finding the no of likes on a specific post. I have created a webpage where all the posts are displayed. Now the problem I am facing is the no of likes are getting calculated wrong. Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") def __str__(self): return self.title Query in Views.py file to fetch all the posts -> posts = Post.objects.select_related().prefetch_related('images_set').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now when I see the post.Likes__count in template it shows wrong count of 6 for one specific post but when I use post.likes.count() it shows count of 3. for other posts they both show same result. I am unable to find out why it is happening. This is the result for that specific post -> {'post_id': 22, 'user_id': 1, 'title': 'wkjdfh', 'description': 'kjwdfn', 'Tags': '.,smdf,m', 'category': <Category: Shoes>, 'userName': 'admin', 'images': <QuerySet [<Images: Images object (10)>, <Images: Images object (11)>, <Images: Images object (12)>, <Images: Images object (13)>]>, 'comments_count': 6, 'likesCount': 6, 'actualLikeCount': 3} This is very … -
How to safely execute user-written code in the backend?
I'm trying to build a Django web application that allows users to write Python code and runs that in the backend, kinda like how an IDE would work. I'm just wondering, what security risks does this come with? I'm sure there are plenty, the user could literally do anything with that code, so what would be a good solution to safely do this? Would running it inside a Docker container be a good solution? -
Django Authentication Application
I've just started to the django and got a little lost in between various doumentations and outdated tutorials. What I want to achieve is to create a simple dashboard application that also contains some backend scripts to integrate various apis most of them are open API's like weather API's , calendar API's etc just for learning. But I need to create a login page for the application and current tutorials for the authentication mosule of django is a little bit cunfusing as it never gives me how to implemelent a login form to the auth backend. I need a little bir more simple documentation for that. Is there anyone able to help me on that. I know the question is not code related but still any help will be appriceated. Most of findings from my previous searches are outdated and implementing those methods are often causes errors like non-existent templates etc... Meanwhile I'll be also checking the offical documentation. Thank you. -
Hashicorp Vault - Django query from docker container
Good afternoon, I have a two docker containers, one running a django app and the other running Hashicorp Vault as I am starting to play with Vault in a dev environment. I am using HVAC from a django view to write a secret to the vault that is entered by a user to set up an integration to a REST API for a data pull. When I run the following from my host machine, it writes just fine. client_write = hvac.Client(url='http://127.0.0.1:8200', token='MY_TOKEN') client_write.is_authenticated() When I run the same from the Django container, it fails with: requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8200): Max retries exceeded with url: /v1/auth/token/lookup-self (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2a21990610>: Failed to establish a new connection: [Errno 111] Connection refused')) Django docker container is running on localhost:8000 & the vault is localhost:8200. I also have a front end written in VueJS running on localhost:8080 that has no trouble communicating back and forth with the django rest API (django-rest-framework). Is there something in vault that I need to list where the queries can come from? Thank you, I am very new to Vault and am struggling through it a bit. BCBB -
Why is django's forloop.counter0 confused by an adjacent loop?
I have a template that looks like this: <table> <tbody> {% for row in rows %} <tr> {% for column in row %} <td>{{ column }}</td> {% endfor %} <td><input type=checkbox name="checkbox_{{ forloop.counter0 }}"></td> </tr> {% endfor %} </tbody> </table> The checkboxe names in the table that get generated start with checkbox_1 instead of checkbox_0. If I remove the inner for loop however: <table> <tbody> {% for row in rows %} <tr> <td>Column 1</td> <td>Column 2</td> <td><input type=checkbox name="checkbox_{{ forloop.counter0 }}"></td> </tr> {% endfor %} </tbody> </table> They start with checkbox_0 as they should. The inner loop appears to be messing up the counter for the outer loop. I even tried to use the with tag, but that didn't seem to help: <table> <tbody> {% for row in rows %} {% with forloop.counter0 as outer_counter %} <tr> {% for column in row %} <td>{{ column }}</td> {% endfor %} <td><input type=checkbox name="checkbox_{{ outer_counter }}"></td> </tr> {% endwith %} {% endfor %} </tbody> </table> Any idea what might be going wrong? -
Save and Update Record date wise in via Django Rest framework
I am new to django , I am using AIPView method of restframework to create and update leaderboard model. The requirement is to save Email, Name and Total Score along with a date field which automaticall updates the date each time the record is saved. Each time a users score his highest score , its pushed to database on server. A user can achieve higest score many times within a single day or within of a few days The issue is that my client wants to save highest score record date wise. I am able to update total Points everytime I receive from the client for the current dateand I am unable to keep the previous days hights score/TotlaPoints, Please advice a solution. This is my Models.py file class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) email = models.CharField(_("email"), max_length=255, default='myemail@gmail.com') TotalPoints = models.IntegerField(_("TotalPoints")) updated_at = models.DateTimeField(auto_now=True)code here This is my Views.py file: I tried ofllowing code but it only saves the highest score to Total_points field and updates the date field (updated_at), I want to keep on updating Total Points until the dat changes, when the next day comes a new entry for the same record should be done but with … -
Image file can't covert to pdf when using python-pdfkit
Here is my code options = { "enable-local-file-access": True, ... } pdfkit.from_string(html_file, pdf_file, options=options, ...) since Im using Django template, here is my code to reference that <img src="{{ static_root }}{% static '../../target.svg' %}" alt=""> I use a local image file in html, It just shows a blank box in pdf output file I also tried using "base64" to resolve my issue base on this link pdfkit not converting image to pdf It doesn't really work to me. -
Image not Updating using DOM manipulation
I am trying to toggle between 2 images based on a condition. I am thinking to change the src of img tag. I am able to change the src but on the webpage the image is not getting updated. can someone point out where or what should be used or updated. Here is my JS code -> success: function(data){ if(data.status == 200){ if(data.message == "Liked"){ document.getElementById("like_image_state_change").src="{% static 'FrontEnd1/Static_Images/CovrPage_Like_R.png' %}"; } else if(data.message == 'Like Removed'){ document.getElementById("like_image_state_change").src="{% static 'FrontEnd1/Static_Images/CovrPage_Like_W.png' %}"; console.log(document.getElementById("like_image_state_change")); } } else{ console.log('wrong'); } } }); Here when I console the document.getElementById in 'like Removed' I could see the updated src for the Image but the Image is still the same on the webpage. PS -> The backend I am using is DJango. (if it matters) -
Django Python contact form saves file but doesn't send the email
I'm trying to set up a simple contact form with an optional file upload; I don't want the file to be attached to the email message, I simply want to save the file to /media. I'm using required=False in the form to not require a file. But still, some of my form validation or form processing logic is wrong; the code below works when I submit the contact form without a file and I get an email. But if I attach a file, the file is saved to media, but I don't get an email even though the contact form correctly renders thanks.html after form submission. No errors in the logs. Ubuntu 20.04; Django 4.0.3; Python 3.8.10; Apache 2.4 contact/contactform/forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'maxlength': '100'} )) email_address = forms.EmailField(required=True, widget=forms.EmailInput( attrs={'class': 'form-control', 'maxlength': '100'} )) document = forms.FileField(required=False) message = forms.CharField(required=True, widget=forms.Textarea( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) contact/contactform/views.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.shortcuts import render, get_object_or_404, redirect from django.core.files.storage import FileSystemStorage from contactform.forms import ContactForm from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST def thanks(request): return render(request, 'thanks.html', {}) def contact(request): if request.method … -
Save django CreateView in Python Shell
I'm trying to write a test for my CreateView view in django. As part fo the test, I want to create a new object through a CreateView class, though I'm unsure how to save the object through tests.py. models.py class MyClass(models.Model): name = models.CharField( max_length = 50, ) tests.py from myapp.views import MyCreateView m = myCreateView() m.name = 'John Doe' # save object here Neither m.save() nor m.submit() will work. Any suggestions? -
Create a custom superuser django
I'm trying to create a custom user model but when I create a superuser with "python manage.py createsuperuser" and try to login from the django admin, I get this message: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. username and password are correct. and this is my models: class MyUserManager(BaseUserManager): def create_user(self, username, password, **extra_fields): user = self.model(username=username) user.set_password(password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(username, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10,unique=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] publisher = models.BooleanField(default=False) admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = MyUserManager() def __str__(self): return self.username -
django-crispy: error filed not displayed (but added to the DOM)
I use django-crispy for template rendrering my issue is that field error is not displayed even if added to the DOM input field is underlined with red <form id="id-form" method="post"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="alert alert-danger mb-0" role="alert"> {{ error }} </div> {% endfor %} {% endif %} <br> {% crispy form %} </form> If I render my form fied by field, error message is displayed <form id="id-form" method="post"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="alert alert-danger mb-0" role="alert"> {{ error }} </div> {% endfor %} {% endif %} <br> <div class="row mb-0"> <div class="input-group input-group-sm col-6"> <label>{{ form.inc_dat.label }}</label> </div> <div class="input-group input-group-sm mb-1 col-2"> {{ form.inc_dat }} <div class="input-group-append"> <span class="input-group-text rounded-right" id="basic-addon2"><span data-feather="calendar"></span></span> </div> {% for error in form.inc_dat.errors %} <div class="invalid-feedback">{{ error }}</div> {% endfor %} </div> </div> </form> what is wrong with django-crispy? -
DRF: Using URL parameters to determine ordering on nested serializer fields
My question is whether there is a way to use filters given by the user in the URL to order a queryset using nested serializers using the nested fields. For example: class EventsSerializer(serializers.ModelSerializer): class Meta: model = Events fields = ['date', 'location'] class GuestsSerializer(serializers.ModelSerializer): events = EventsSerializer() class Meta: model = Events fields = ['name', 'phone', 'seat_no', 'events'] class GuestEvents(generics.ListAPIView): serializer_class = GuestsSerializer name_param = self.kwargs['name'] order_param = self.request.query_params.get('orderBy') def get_queryset(self): data = Guests.objects.select_related('events').filter(name=name_param) return data def list(self, request, *args, **kwargs): res = super(TestData, self).list(request, *args, **kwargs) res.data = {"guestevents":res.data} return res If i have these serializers and view in order to show what events a guest is attending and the ordering is by default ascending based on the date; is it possible to have the user type location as the orderType and have that be used for ordering or can i not make use of thee 'location' field at this point? -
Django Channels receive message from room group doesn't appear to be working
I am trying to build a notifications system using Django Channels. I completed the intial setup and when I run my server I get confirmation of Handshake and connection confirmed. However, when I view my console log, I cannot see the message to be sent. I also put a print statement on the send_notification function but it is never reached. I am new to using Django Channels so any help would be appreciated. What am I terribly doing wrong? Here is my ASGI file setup: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clicksource.settings') from channels.auth import AuthMiddleware, AuthMiddlewareStack from notifications.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ) }) Here is my consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'notification_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from room group async def send_notification(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message':message })) Here is my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/notification/(?P<room_name>\w+)/$', consumers.NotificationConsumer.as_asgi()), ] And the script in my … -
Adding fields from a many-to-many relationship to a Django Admin Inline
I am trying to set up a project where I have user, questions for the users, and then the answers that the users give. Here are my models. class User(models.Model): name = models.CharField(max_length=20) email = models.EmailField() def __str__(self): return self.name class Question(models.Model): question = models.TextField() def __str__(self): return self.question class Answer(models.Model): answer = models.TextField() user = models.ManyToManyField(User) question = models.ManyToManyField(Question) def __str__(self): return self.answer Then in the admin I would like to be able to click on a user and see their answers so I set my admin up like so. class AnswerInline(admin.TabularInline): model = Answer.user.through class UserAdmin(admin.ModelAdmin): list_display = ('name', 'email') inlines = [AnswerInline] class QuestionAdmin(admin.ModelAdmin): list_display = ('question',) class AnswerAdmin(admin.ModelAdmin): list_display = ('answer', ) fields = ('question', 'answer',) admin.site.register(User, UserAdmin) admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) However, when viewing users it only shows their answer. It doesn't show the question that answer is associated with. How do I add this information to the admin page in a way that makes sense. Preferably with the question first and then the answer to that question to the right of it. -
Bootstrap delete confirmation dialog
I am trying to Delete a record using bootstrap model in Djando while getting a confirmation. The Model view gets triggered and deletes the record but on success it points to the url pointing to the deleted record and it gives a 404 error. It seems it tries to post the request twice. I could not find resources on this to help me get around and also I am in learning phase so I am looking forward to expert advice on this. Thanks Delete button in the index.html against the record to delete. <button type="button" class="delete-task btn btn-sm btn-primary" data-id="{% url 'delete' task.pk %}"><span class="fa fa-trash"></span></button> Javascript in index.html $(".delete-task").each(function () { $(this).modalForm({formURL:$(this).data('id')}); }); Model.html: <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> delete_task.html: {% load widget_tweaks %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Delete Task</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="delete-text">Are you sure you want to delete Task with title <strong>{{ task.title }}</strong>?</p> </div> <div class="modal-footer"> <button id="delete-task" type="submit" class="delete-task btn btn-danger" >Delete</button> </div> </form> View.py: class TaskDeleteView(BSModalDeleteView): model = Task template_name = 'delete_task.html' success_message = 'Deleted Successfully' def get_success_url(self): return reverse_lazy('index') Urls.py: path('delete/<str:pk>', … -
DRF upload extracted zip files
I'm going to upload some files through my DRF API. This API receives a .zip file that has some .xlsx files in, and I extract its content in the API view. Then I send this data to the serializer, But I get this error: [ { "file_name": [ "The submitted data was not a file. Check the encoding type on the form." ] } ] This is how I'm extracting my .zip file before passing data to the serializer: def _get_serializer_initial_data(self): with ZipFile(self.request.FILES.get('file_name')) as input_zip: return [ { 'file_name': input_zip.open(_input_excel) } for _input_excel in input_zip.infolist() ] Then I send data to the serializer this way: initial_data = self._get_serializer_initial_data() serializer = self.get_serializer(data=initial_data, many=True) I checked the extracted files type in the serializer class and it's ZipExtFile, which seems to be unacceptable by DRF. Any help would be appreciated. -
How to send notification before 30 days from expire date in django?
How i schedule notification for this program , i am using channels to create notification and use "crontab" for scheduling but it does't work............. please provide exact solution... def my_schedule_job(): vehicle_objs = Vehicle.objects.all() for vehicle_obj in vehicle_objs: insurance_expiry = vehicle_obj.insurance_expiry insurance_expiry_date = insurance_expiry - timedelta(days=5) today = date.today() print('insurance_expiry_date',insurance_expiry_date) print('today',today) if insurance_expiry_date == today: notification_obj = Notification(user_id=vehicle_obj.user_id,notification="Your insurance for {} will expire on {}".format(vehicle_obj.vehicle,insurance_expiry) ,is_seen=False) notification_obj.save() elif insurance_expiry_date <= today: notification_obj = Notification(user_id=vehicle_obj.user_id,notification=vehicle_obj.vehicle + " insurance is going to expire on " + str(insurance_expiry),is_seen=False) notification_obj.save() -
Python Azure SDK azure.mgmt.recoveryservices.operations VaultsOperations "VaultsOperations.__init__() missing required positional arguments' Error
I'm trying to get the list of RecoveryServiceVaults by resource group name using Azure SDK package for Python azure.mgmt.recoveryservices. . I coded as follows; from azure.identity import ClientSecretCredential from azure.mgmt.recoveryservices import RecoveryServicesClient from azure.mgmt.recoveryservices.operations import VaultsOperations subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] tenant_id = os.environ["AZURE_TENANT_ID"] client_id = os.environ["AZURE_CLIENT_ID"] client_secret = os.environ["AZURE_CLIENT_SECRET"] credentials = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) recovery_services_client = RecoveryServicesClient(credentials=credentials,subscription_id=subscription_id) vault=VaultsOperations(recovery_services_client) vaults_in_rg = vault.list_by_resource_group(rg_name) for vault in vaults_in_rg: print(vault) And the Error I got is; TypeError: VaultsOperations.__init__() missing 3 required positional arguments: 'config', 'serializer', and 'deserializer'. I don't know what variables I should provide to create VaultsOperations() class object. Could you give some guidance ? Does anyone know what kind of variable should be provided for object to be created? Any opinions is appreciated. Thanks in advance -
How build a category model after building legacy model in Django REST Framework
Hello, I have a question about improving legacy models. The Material model is old model, and i want to make category by using new model 'type'. But i have a little problem with when i use admin site. In admin site, i hope to choose the 'type' first, and upload data .. how can i make better models # new model class MaterialType(BaseModel): type = models.CharField(choices=MaterialTypeChoice.choices, max_length=50, null=True, blank=True) def __str__(self): return self.type # old model class Material(models.Model): type = models.ForeignKey(MaterialType, verbose_name=, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField max_length=50, null=True, blank=True) size = models.CharField(max_length=50, null=True, blank=True) unit = models.CharField(max_length=5, null=True, blank=True) price_unit = models.IntegerField(null=True, blank=True) def __str__(self): return self.name serializers # new class MaterialTypeListSerializer(serializers.ModelSerializer): class Meta: model = MaterialType fields = ["type"] # old class MaterialListSerializer(serializers.ModelSerializer): class Meta: model = Material fields = ["id", "type", "name", "size", "unit", "price_unit"] views # new class MaterialTypeList(ListCreateAPIView): queryset = MaterialType.objects.all() serializer_class = MaterialTypeListSerializer # old class MaterialList(ListAPIView): queryset = Material.objects.all() filter_class = MaterialFilter serializer_class = MaterialListSerializer admin @admin.register(Material) class MaterialAdmin(ImportExportModelAdmin): list_display = ["name", "size", "unit", "price_unit"] list_display_links = ("name",) list_filter = ("type",) list_per_page = 10 # list_editable = ('type',) search_fields = ("name", "size") resource_class = MaterialResource @admin.register(MaterialType) class MaterialTypeAdmin(ImportExportModelAdmin): list_display = ["type"] list_filter … -
Render all products that relate to one of subcategories of one category, in category page
I had a question. I am creating an ecommerce website in django. There, I have categories and subcategories. When I enter to subcategory page, I able to render all products that relate to this subcategory. But, when I wanted to render all product that relate on one parent category, I am having troubles. So, I have some subcategories in one category. In that category page, I want to render all products that relate to one of subcategories of this category. Can you help me please? models.py class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, verbose_name="Изображение") ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Categories' ordering = ('ordering',) def __str__(self): if self.parent is not None: return f"{self.parent}/{self.title}" return self.title @property def imageURL(self): try: url = self.image.url except: url = '' return url def get_absolute_url(self): return '/%s/' % (self.slug) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) parent = models.ForeignKey('self', related_name='variants', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=200, verbose_name="Название продукта") price = models.IntegerField(verbose_name="Цена") slug = models.SlugField(max_length=255) description = models.CharField(max_length=5000,blank=True, verbose_name="Описание:") image = models.ImageField(null=True, blank=True, verbose_name="Изображение") novinki = models.BooleanField(default=False, verbose_name="Новинки") popularnye = models.BooleanField(default=False, verbose_name="Популарные") def __str__(self): return self.name class Meta: verbose_name = … -
How to securely generate random passwords in Django?
I have imported a set of user data into a Django project. Now I need to set a random password for each of them. My question here is, how do I securely generate random passwords in Django?