Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I return the most sold item given a month and a year?
I need to be able to return the most sold item (and the quantity sold) given a month and a year. For example, if in a month: a) order 23: 2 cakes, 5 cupcakes b) order 21: 3 cupcakes Then I'd need it to return 5 cupcakes. How do I do this? This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Order(models.Model): food = models.ManyToManyField('Food', related_name='order', blank=True) def __str__(self): return self.food Ths is the serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' -
Django permissions for PasswordResetView
I am using django.contrib.auth.views to provide a reset email page to my users. The page to reset the password is generated as follow : path("user/reset_password/", auth_views.PasswordResetView.as_view(template_name="accounts/reset_password.html"), name="reset_password"), However my users can still access this page when logged in. How can I control the permissions to access the page since I do not have direct access to the view ? -
Python pip raising NewConnectionError while installing django-braces
I am getting the following error when I tried to install django-braces: WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000168673EC2E0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /packages/6d/ce/accaea120b323e62cb3bf8cce26892cdbfbf6b86d1b220fa2432b9b86acb/django_braces-1.14.0-py2.py3-none-any.whl I can install any other libraries without any problem. Questions: Is there any problem with django-braces ? If so, can you recommend an alternative to braces.SelectRelatedMixin ? Versions: python 3.9.2 django 3.1.7 -
Django Form - setting data
I'm improving my English, be patient My form is a ModelForm and all the necessary data is sent by the user, but I want dynamically set the field ["viagem"] with the last object in the queryset. How to set a field after sending the data def cadastro(request): dono = Dono.objects.get(user=request.user) if request.method == "POST": form = VendaForm(dono, request.POST) # Here I get the necessary data to call my qs colocador_id = form["colocador"].value() viagem = Colocador.objects.get(pk=colocador_id).viagem_set.last() # I want something like this form["viagem"] = viagem if form.is_valid(): form.save() else: print('error') print(form.errors) else: form = VendaForm(dono) context = {"form": form, } return render(request, 'dashboard/cadastro.html', context) print(form.errors) => <ul class="errorlist"><li>viagem<ul class="errorlist"><li>This field is required</li></ul></li></ul> -
Django command - django-admin command not working
i have tried to install django using below three command. Now when i execute the django-amdin command then its showing me below error. Even i cant see the django-admin --version. sudo apt install python3.8 sudo apt-get install python3-pip pip3 install Django Error is : Traceback (most recent call last): File "/home/dev/.local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line File "/home/dev/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/home/dev/.local/lib/python3.5/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/home/dev/.local/lib/python3.5/site-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/home/dev/.local/lib/python3.5/site-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/home/dev/.local/lib/python3.5/site-packages/asgiref/sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax Please help here if anyone have an idea. -
DRF prefetch_related optimization problem
I'm trying to optimize the query I've written, but I can't optimize its menus and sub-menus. The problem is; Queries arise separately for each menu item and its sub-item. I use django-debug-toolbar and when I look at the queries tab I see more than 10 queries count Queries; SELECT ••• FROM "xxx_settings" (1 query) SELECT ••• FROM "xxx_menu" WHERE "xxx_menu" (1 query) SELECT ••• FROM "xxx_menuitem" INNER JOIN "xxx_menuitem" (8 similar queries) Models.py class Menu(models.Model): name = models.CharField(max_length=128, null=True, blank=True) class MenuItem(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE) name = models.CharField(max_length=128) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='subitems') class Settings(models.Model): homepage_title = models.CharField(max_length=255) header_menu = models.ForeignKey(Menu, null=True, blank=True, on_delete=models.SET_NULL, related_name='HeaderMenu') Serializer.py class SettingsSerializer(serializers.ModelSerializer): header_menu = MenuSerializer(read_only=True) class Meta: model = Settings fields = '__all__' class MenuSerializer(serializers.ModelSerializer): menuitem_set = MenuItemSerializer(read_only=True, many=True) class Meta: model = Menu fields = '__all__' depth = 1 @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related('menuitem_set') return queryset class MenuItemSerializer(serializers.ModelSerializer): subitems = serializers.SerializerMethodField() class Meta: model = MenuItem fields = '__all__' def get_subitems(self, obj): serializer_context = {'request': self.context.get('request')} children = MenuItem.objects.select_related('parent').prefetch_related('parent__menu__menuitem_set').filter( parent=obj) serializer = MenuItemSerializer(children, many=True, context=serializer_context) return serializer.data queryset queryset = Settings.objects.select_related('header_menu',).prefetch_related( 'header_menu__menuitem_set__subitems', 'header_menu__menuitem_set',) -
How can I pass an array to a Django form
I am trying to pass an array to my form that needs to be displayed as a select in my template, but the code I tried isn't working. def __init__(self,*args,**kwargs): self.categs = kwargs.pop('categs') super(CheckForm,self).__init__(*args,**kwargs) CHOICES = [(1,'Drop'),(2,'Mean'),(3,'Max'),(4,'Min')] missing = forms.ChoiceField(label = 'Please indicate how you want to handle missing values', widget=forms.RadioSelect, choices=CHOICES) nametar = forms.CharField(label = 'Please indicate the name of the prediction') dropcol = forms.ArrayField(choices = categs, label = 'Please select the column you want to drop')``` -
Django Extensions - Jupyter Not working. Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
I have done many times in my career to jupyter notebook in Django projects. Today I don't know why its NOT Working. I have installed Django 3.0, Python 3.8.9, MySQL. Might be issue with version of Django or python. I put django-extensions in my installed apps. also put this settings file. import os os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" -
add new form whene click on button in javascripts and django
I'm new at using javascripts with Django I'm trying to create an html page that contains 2 button one click on one of them it add a form to the page, and if I click on the other button it add another form this is the html page <body> <div class="container"> <form action="{% url 'create_appointement' %}" method="post"> {% csrf_token %} <button type="submit" name="type" class="button1" id="button1">register patient</button> <button type="submit" name="type" class="button2" id="button2">non register patient</button> </form> <div id='form'> </div> </div> <script language="javascripts" type="text/javascripts" src="static/js/onclick.js"> </script> </body> and this is me trying to create this script, but it did not work document.addEventListener('DOMContentLoaded', function showAppointementForm() { document.getElementById("button1").onclick = function() { document.getElementById("form").innerHTML = ` <form action="{% url 'create_appointement_non_register_patient' %}" method="POST"> {{ form.media }} {{ form.as_p }} {% csrf_token %} <button type="submit" value="create_appointement_non_register_patient"> ok </button> </form> ` } document.getElementById("button2").onclick = function() { document.getElementById("form").innerHTML = ` <form action="{% url 'create_appointement_register_patient' %}" method="POST"> <p> <label for="patients">select a patient</label> <select name="patients" id="patients"> <option value="">-- select a patient --</option> {% for patient in patients %} <option value="{{patient}}">{{patient}}</option> {%empty%} <option value="nothing">nothing</option> {% endfor %} </select> </p> {{ form.media }} {{ form.as_p }} {% csrf_token %} <button type="submit" value="create_appointement_register_patient"> ok </button> </form> ` } }) is something wrong with my code in … -
i want inverse all the produts uploaded from the django admin panel?
here is the code how i am fetching them {% for category in smartphone_banners %} {% for product in category.product_detail_set.all %} <div class="swiper-slide py-2"> <a href="product/{{product.name}}/{{product.id}}" style="text-decoration: none;"> <img src="{{product.imageURL}}" alt="" style="width: 80%; margin: 0 auto;"> <h6 class="mt-1">{{product.name}}</h6> <p>₹{{product.price}}</p> </a> </div> {% endfor %} {% endfor %} |slice:"0::-1" how can I inverse them I hope you can help me if there is any another way then please tell me -
Error when creating user from custom model
I am relatively new to Django, but just finished creating a custom user model rather then using the base. When running createsuperuser im getting the following error stack: File "C:\Users\adamt\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save super().save(*args, **kwargs) TypeError: save() got an unexpected keyword argument 'user' My custom model and create_user and create_superuser are: def create_user(self, email, username, FirstName, Surname, password=None): if not email: raise ValueError("Users must have an Email Address") if not username: raise ValueError("Users must have a Username") if not FirstName: raise ValueError("Users must have a First Name") if not Surname: raise ValueError("Users must have a Surname") user = self.model( email=self.normalize_email(email), username=username, FirstName=FirstName, Surname=Surname, ) user.set_password(password) user.save(user=self._db) return user def create_superuser(self, email, username, FirstName, Surname, password): user = self.create_user( email=self.normalize_email(email), username=username, FirstName=FirstName, Surname=Surname, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(user=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name ="email", max_length=60, unique=True) username = models.CharField(max_length=100, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) DateofBirth = models.DateField(verbose_name="Date of Birth") MarketingOptIn = models.BooleanField(verbose_name="Marketing Opt In", default=False) FirstName = models.CharField(verbose_name="First Name", max_length=100) Surname = models.CharField(verbose_name="Surname", max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','FirstName','Surname', ] objects = … -
Image fields or Boolean fields in django forms widgets?
I am trying to add an image field in the widgets dictionary but I don't know what is the property for forms to do that. like forms.TextInput what should I use for an image field or a Boolean field? here the code is giving me error in image property of widgets dictionary. class CreateProductForm(ModelForm): class Meta: model = Product fields = ['name', 'price', 'category', 'description', 'image'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'image': forms.ImageInput(attrs={'class': 'form-control'}), } -
How can i set a custom values in models.py (Python - Django)
I'm beginner in python django and i want to put "test" in the "name" field of the "games" table with the class models.py. I read some documentation but it's complicated and i don't understand how can i do it. Thanks for help. from django.db import models from django.utils import timezone class games(models.Model): name = models.TextField(max_length=255) -
show list in django without html file
i have 2 models but i want to show name of artist in my output class Musician(models.Model): name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): name = models.CharField(max_length=100) artist = models.ForeignKey(Musician, on_delete=models.CASCADE) num_stars = models.IntegerField() i want to show artist name by HttpResponce funcction class Musician_list(View): def get(self, request): persons = Album.objects.all().values_list("artist__name").order_by("artist__name") return HttpResponse(persons) but this code dont show any things please help me. -
Django throwing attribute error and i dont know why it is happening
I am trying to take image input from user in Django first the code was working fine but when I tried to run this code after a week it is giving me an attribute error and I don't why it is happening I tried to search on the internet but they only say it is because of the wrong syntax. The line, where the error arises, is file_type = file_type.lower() and line will be at last in the product_details function views.py from django.shortcuts import render from django.http import HttpResponse from datetime import datetime from machine_website.models import contact_detail from machine_website.models import product_data from machine_website.forms import product_Form # Create your views here. def homepage(request): descp1 = product_data() descp1.disc = ' this is the discription' descp1.img = '2.jpg' descp2 = product_data() descp2.disc = ' this is the discription 2' descp2.img = '2.jpg' descp3 = product_data() descp3.disc = ' this is the discription 3' descp3.img = '5.jpg' descp = [descp1, descp2,descp3] return render(request,'homepage.html', {'descp': descp}) def contact(request): if request.method=="POST": name = request.POST.get('name') email = request.POST.get('email') desc = request.POST.get('desc') contact = contact_detail(name=name , email=email, desc=desc, date=datetime.today()) contact.save() return render(request,'contact.html') def services(request): return render(request,'services.html') def index(request): return HttpResponse("this is index page") def more(request): info = product_data.objects.all() … -
How to return object details and Aggregated data under the same Django Rest API
I want to return Object details and Aggregated data under the same Django rest api. Can it be possible from ModelViewSet? If not what is the correct way of doing this? Here is my Code. #Tin class TinTable(CoreModel): tin=models.CharField(unique=True, max_length=30) assessee_name=models.CharField(max_length=500) def __str__(self): return self.tin # Financial Year class FinancialYear(CoreModel): financial_year = models.CharField(max_length = 50) class Meta: ordering = ["start_year"] def __str__(self): return self.financial_year Ledger Class # Ledger class Ledger(CoreModel): UNDISPUTED = 0 APPEAL = 1 TRIB = 2 HC = 3 ONE_SEVENTY_THREE = 4 ONE_TWEENTY_ONE = 5 ADR = 6 Ledger_SECTION_CHOICES = ( (UNDISPUTED, 'Undisputed'), (APPEAL, 'Appeal'), (TRIB, 'Tribunal'), (HC, 'High Court'), (ONE_SEVENTY_THREE, '173'), (ONE_TWEENTY_ONE, '121/A'), (ADR, 'ADR') ) tin=models.ForeignKey(TinTable, on_delete = models.CASCADE) financial_year = models.ForeignKey(FinancialYear, on_delete = models.CASCADE) demand = models.FloatField(default = 0.0 ) #demand disputed_demand = models.FloatField(default=0.0) payment = models.FloatField(default = 0.0 ) #payment balance = models.FloatField(default = 0.0 ) status = models.PositiveSmallIntegerField( choices=Ledger_SECTION_CHOICES, default=UNDISPUTED) comment = models.CharField(max_length=500, blank=True) def __str__(self): return self.tin.tin Serializer of Ledger class LedgerSerializer(serializers.ModelSerializer): financial_year = serializers.PrimaryKeyRelatedField( queryset=FinancialYear.objects.all(), source='financial_year', write_only=True ) tin = serializers.PrimaryKeyRelatedField( queryset=TinTable.objects.all(), source='tin', write_only=True ) assessee_name = serializers.ReadOnlyField( source='tin.assessee_name' ) class Meta: model = Ledger fields = ('tin','assessee_name','financial_year','demand','disputed_demand', 'payment','status') View of Ledger class LedgerView(viewsets.ModelViewSet): serializer_class = LedgerSerializer queryset = Ledger.objects.active() … -
DRF: Functional view not returning Response as expected
In the Django Rest Framework, I am looking to have my view return a personalised message using the following line: return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"}) What I expect it to return: {'Message': 'Post 130 successfully liked by 8'} What is actually returned: <Response [200]> Why is this happening? How can I return the expected message? Here is the full view if it helps: @api_view(['POST']) def like_view(request, pk, destination): #destination is the user_id post = Posts.objects.get(pk=pk) if post.is_expired == True: print("expired") return Response({"message":"post expired"}) if check_self_action(destination,post): return Response({"message":"cannot like own post"}) liked = check_like(destination, post) prefix = "" if liked: post.likes.remove(destination) prefix = "un" else: post.likes.add(destination) return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"}) -
Django sets model time field three hour less from my current local time
I'm following the Django tutorial part 2 and have some troubles applying my local time to the models I've created. This is my time config from settings.py: TIME_ZONE = 'Europe/Kiev' USE_I18N = True USE_L10N = True USE_TZ = True These are models of my app. I suppose that an issue is somehow related with an error message that Pyright gives. But this code have been just copied and pasted from official Django tutorial. This picture shows actually my problem: time of record creating three hour less than my actual time -
not able to access uploaded media files in django
This is the error i am getting template does not exist This is my settings file I have added media root and media directory in settings.py -
display python function result in html django
I made a web application with django that execute a python function . this function runs every 5 second and prints results in console and I want to show the result in html page and the results extend to prior results in html file . the problem is when I press the button to start service, the function starts but the page is always in reloading and doesn't redirect to new page to show the function results in new page : this is my code : def index(request): login_form = LoginForm(request.POST, request.FILES) context = { "form": login_form, } if login_form.is_valid(): ip = login_form.cleaned_data.get('IP') port = login_form.cleaned_data.get('port') username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') handle_uploaded_file(request.FILES["certificate"]) request.session['ip'] = ip request.session['port'] = port request.session['username'] = username request.session['password'] = password return redirect('monitor/', request.session) return render(request, "index.html", context) def monitor(request): ip = request.session['ip'] port = request.session['port'] username = request.session['username'] password = request.session['password'] p = sp.Popen(monitoring(ip, port, username, password), stdout=sp.PIPE, stderr=sp.PIPE) output, errors = p.communicate() return render(request, "monitor.html",{'output':output}) this is my html : html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> <h3>{{ output }}</h3> </body> </html> -
Heroku Django website relation does not exist on PstgreSql Database
I developped a website which runs fine on my local machine. I uploaded my site and the postgre database to Heroku. It displayed correctly, and I'm able to access to the admin console. In the front page of my site I have links that make request to my database, but I receive "relation "mytable" does not exist" I'm able to make request manually with heroku pg:psql without any problems. My models are like this : class Data(models.Model): i = models.AutoField(primary_key=True) version = models.CharField(max_length=10, blank=True, null=True) id = models.JSONField(blank=True, null=True) attributes = models.JSONField(blank=True, null=True) audiofiles = models.JSONField(blank=True, null=True) class Meta: managed = False db_table = 'data' On my settings.py I have the following for Database node (I replaced infos for obvious reasons): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': '', 'PORT': '5432', 'OPTIONS': { 'options': '-c search_path=card' } } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) Here my requirements.txt: asgiref==3.3.1 dj-database-url==0.5.0 Django==3.1.7 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.8.6 pytz==2021.1 sqlparse==0.4.1 whitenoise==5.2.0 I tryed many things like : heroku run python manage.py makemigrations followed by migrate heroku run python manage.py migrate --run-syncdb Drop my database a recreate it makemigrations on local then commit the change to heroku (and migrate again … -
is there a way to paginate multiple querysets in django list view?
i will use bootstrap tabs to make a tab for the (newest questions) posted which i will use the original query from the model to sort objects by date posted, and a tab for the (most liked) question which i will an additional context queryset for... when i have them on the template the pagination is only for the model queryset, how do i make it also for the second query when the user is on the (most likes) tab my view: class QuestionListView(ListView): model = Question template_name = 'question/question_list.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = Category.objects.root_nodes() count = Question.objects.count() question_likes = Question.objects.all().order_by('-like_count') context['category'] = category context['count'] = count context['question_likes'] = question_likes return context my models class Question(models.Model): title = models.CharField(max_length=150, unique=True) slug = models.SlugField(max_length=150, unique=True) content = RichTextField(null=False, blank=False) tags = TreeManyToManyField(Category, related_name='cat_questions') author = models.ForeignKey(UserBase, on_delete=models.CASCADE, related_name='questions') date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(UserBase, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') class Meta: ordering = ['-date_posted'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('question:question_detail', kwargs={'slug':self.slug}) def __str__(self): return self.title my template pagination {% if is_paginated %} <div class="col-12 text-center mt-5"> {% if page_obj.has_previous %} <a class="btn btn-outline-dark my-4" href="?page=1">First</a> <a … -
Django: Handling Foreign Key value in template
I have recently started working with Django and I am struggling to work with 2 models in a single form. I have looked a lot of questions in stackoverflow but I couldn't find any that answers this question. I have 2 models - Student & Address This is my models.py class Students (models.Model): Student_Name = models.CharField(max_length=50, db_column='Student_Name') College_Number = models.CharField( max_length=10, db_column='College_Number') Gender = models.CharField(max_length=50, db_column='Gender') Blood_Group = models.CharField(max_length=50, db_column='Blood_Group') Set = models.CharField(max_length=50, db_column='Set') Standard = models.CharField(max_length=50, db_column='Standard') class Addresses (models.Model): Student_ID = models.ForeignKey( Students, on_delete=models.CASCADE, db_column='Student_ID') City = models.CharField(max_length=50, db_column='City') State = models.CharField(max_length=50, db_column='State') Pincode = models.CharField(max_length=50, db_column='Pincode') AddressLine1 = models.CharField(max_length=1024, db_column='AddressLine1') AddressLine2 = models.CharField(max_length=1024, db_column='AddressLine2') This is my views.py def student_create_view(request): student_form = StudentFrom(request.POST or None) address_form = AddressForm(request.POST or None) if (request.POST.get('Student_Name') and request.POST.get('College_Number') and request.POST.get('Gender') and request.POST.get('Blood_Group') and request.POST.get('Set') and request.POST.get('Standard') and request.POST.get('AddressLine1') and request.POST.get('AddressLine2') and request.POST.get('City') and request.POST.get('State') and request.POST.get('Pincode') and student_form.is_valid() and address_form.is_valid()): # Fetch values from the Student Form student_form.name = request.POST.get('Student_Name') student_form.collegenumber = request.POST.get('College_Number') student_form.Gender = request.POST.get('Gender') student_form.Blood_Group = request.POST.get('Blood_Group') student_form.Set = request.POST.get('Set') student_form.Standard = request.POST.get('Standard') # Fetch values from the Address Form address_form.AddressLine1 = request.POST.get('AddressLine1') address_form.AddressLine2 = request.POST.get('AddressLine2') address_form.City = request.POST.get('City') address_form.State = request.POST.get('State') address_form.Pincode = request.POST.get('Pincode') student_form.save() address_form.save() return redirect('/create') … -
Django MySQL - correct way to connect
I have been using Django to connect to MySQL on my local computer and I have been using the following method to connect: run pip install mysqlclient and update the requirements.txt file appropriately. update the database connection in settings.py to something like this: 'ENGINE': 'django.db.backends.mysql', 'NAME': ......, 'USER': ......, A bit of a problem arose when I started to use a Dockerfile to try to run the Django app. When I build the Dockerfile and then run the django project, I start to get errors: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? It seems to me that there are 2 potential solutions to this: 1 ) Adjust the Dockerfile so that it installs the software necessary for mysqlclient. This is actually a bit trickier than expected. Could you please make some recommendations for python:3.10.0a5-alpine3.12. 2 ) I was reading about mysql-connector-python. At present I have not got this to work. I installed it using pip, updated the requirements file and then changed the settings.py file to something like this: 'ENGINE': 'mysql.connector.django', 'NAME': ...., 'USER': ...., I have two area's of concern and I would really appreciate some help: 1 ) Which of these methods is the most appropriate … -
Delete and Restoring Files and Cascaded Folders Django
I am new to django and I am working on a project similar to google Drive. I want when I soft delete a folder or file, it should Appear to Trash (only parent folder in case it has children), But it should not be removed in media root folder I want to be able to restore the folder (and its children if it has one) or a file I also want to be able to delete permanently files or folders that are in Trash Here is the code that I have written import os import safedelete from django.db import models from safedelete.models import SafeDeleteModel from safedelete.models import SOFT_DELETE_CASCADE from safedelete.models import HARD_DELETE from documentation.manager import * from datetime import datetime from django.urls import reverse from django.utils.text import slugify from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from account.models import CustomUser from program.models import Activity #a model to create the folder class Folder(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE objects = MyModelManager() creator = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null = True) activity_name = models.ForeignKey(Activity, on_delete=models.CASCADE, blank = True, null=True) name = models.CharField(max_length=64) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) path = models.CharField(max_length=2048, blank=True) slug = models.SlugField(blank=True) def __str__(self): return self.name def get_absolute_url(self): kwargs …