Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django QuerySet .count() is 0 and .exists() is false, even though there's an object in the QuerySet (Django Rest Framework)
I've had an intermittent bug for months and I am stuck! Help is appreciated. @receiver(models.signals.post_delete, sender=ContentFile) def delete_file(sender, instance, *args, **kwargs): class ContentFile(models.Model): """ Represents the metadata for a single document. """ name = models.CharField(max_length=200) set = models.ForeignKey(Set, related_name='contentfile_set', on_delete=models.CASCADE) location = models.FileField(upload_to=get_content_file_upload_path) class Meta: app_label = 'ProtocolManager' unique_together = ('set', 'location') def __str__(self): return f"File {self.name} at location {str(self.location)} attached to {self.set}" """ Delete orphaned file once last ContentFile is removed. """ log.info(f"Checking {instance.location} for existing ContentFile") if instance.location: from django.db import connection from django.db import reset_queries reset_queries() files_queryset = ContentFile.objects.filter(location=instance.location) if not files_queryset.exists(): log.info(f"ContentFile does not exist for {instance.location}, deleting...") log.info(f"SQL: {connection.queries}") log.info(f"files_queryset: {list(files_queryset.all())}") log.info(f"count: {files_queryset.count()}") log.info(f"exists: {files_queryset.exists()}") instance.location.delete(save=False) The logic is pretty simple. When a ContentFile row is deleted, if it was the last one referring to an actual file location, we delete the file itself (on AWS S3, if it matters). 99% of the time this works as expected, but sometimes it will fail, and when it fails, it seems to fail for all of the ContentFiles associated with a given Set. I added the verbose logging to try to get more clues, but today it finally reproduced for the first time in months and the … -
Post multiple images Django
So I tried changing my model to upload multiple images. But as you may guess I am not uploading to database. Asking for a clue as to why. Following a tutorial to do it but not seeing what I messed up. Mote my form has all the fields Im just showing partial info in model and form View def add_seller(request): if request.method == "POST": sellerform = SellerForm(request.POST, request.FILES) files = request.FILES.getlist('car_image') if sellerform.is_valid(): seller_form = sellerform.save(commit=False) seller_form.save() for f in files: img =Image(image=f) img.save() seller_form.image.add(img) seller_form.save() print(seller_form + "Valid") sellers = VehicleStats.objects.all() return render(request, 'index.html', {'sellerform': sellers}) else: sellerform = SellerForm() print(sellerform ) return render(request, 'add_seller.html', {'sellerform': sellerform}) Model class VehicleStats(models.Model): car_id = models.AutoField(primary_key=True) make = models.CharField(max_length=30) model = models.CharField(max_length=30) car_image = models.ManyToManyField('Image') def __str__(self): return self.contact_name class Image(models.Model): car_image = models.ImageField(null=True, blank=True, upload_to="images") Form class SellerForm(forms.ModelForm): class Meta: model = VehicleStats widgets = { 'model' : forms.TextInput(attrs={'class':'form-control'}), 'series' : forms.TextInput(attrs={'class':'form-control'}), 'date_added':forms.DateInput(attrs={'class':'form-control', 'type':'date'}), 'car_image' : forms.FileInput(attrs={'class':'form-control', 'multiple': True}), } -
Using Djongo's ArrayField at Django Admin
Djongo is a Django and MongoDB database connector witch brings, beside others, the ArrayField to Django Models. It allows one to store multiple instances of an other djongo.models.Model in an unique MongoDB Array field inside a document related with the Model that has the Arrayfield As described in source documentation: "The model of the container must be declared as abstract, thus should not be treated as a collection of its own." As well as in djongo's site tutorials "In case you don’t plan on using your embedded model as a standalone model (which means it will always be embedded inside a parent model) you should add the class Meta and abstract = True This way Djongo will never register this model as an actual model." This way I made: # models.py class Contact(models.Model): key = models.CharField(max_length=100) class Meta: abstract = True class Person(models.Model): _id = models.ObjectIdField() ... contact = models.EmbeddedField( model_container=Contact, ) objects = models.DjongoManager() $ pip freeze Django==3.2.4 djongo==1.3.6 pymongo==3.11.4 ... However when I try to add a Person through Django Admin (in /admin/<app>/person/add/) I receive the error Abstract models cannot be instantiated from .../django/db/models/base.py This seems inconsistent with Djongo's description. Am I doing something wrong? -
ImportError: cannot import name 'PasswordsChangeView'
so I am trying to implement a password change in my blog project. Everything seems okay excerpt for this import error am getting. Below is my urls , i have gone through a couple of work arounds but still getting the same error from django.urls import path #from . import views from django.contrib.auth import views as auth_views from .views import UserRegisterView, UserEditView, PasswordsChangeView from .import views urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('edit_profile/', UserEditView.as_view(), name='edit_profile'), #path('password/', auth_views.PassWordChangeView.as_view()), #path('password/', PasswordsChangeView.as_view(template_name='registration/change- password.html')), # path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')), path('change-password/', auth_views.PasswordChangeView.as_view()), ] -
Form field in django is None and it shouldn`t be none
I have this form in django: class userRequest(forms.Form): lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"origin_address"})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"destination_address"})) I am using JS google maps api. I want to save coordinates values into lat_Origin,lon_Origin, etc. With the following code I obtain address data correctly and when I print latitude/longitude fields I obtain a good result. geocoder.geocode({ location: latlng }, (results, status) => { if (status === "OK") { if (results[0]) { map.setZoom(7); const marker = new google.maps.Marker({ position: latlng, map: map, }); contentString = '<div id="content-map">' + '<p>' + results[0].formatted_address + '</p>' + "</div>"; infoWindow.setContent(contentString); infoWindow.open(map, marker); window.alert(is_origin); if (is_origin) { document.getElementById('origin_address').value = results[0].formatted_address; // console.log(lat); // console.log(lng); document.getElementById('lat_Origin').value = lat; document.getElementById('lon_Origin').value = lng; remove_mapMarkers('origin_address', marker) } else { document.getElementById('destination_address').value = results[0].formatted_address; document.getElementById('lat_Dest').value = lat; document.getElementById('lon_Dest').value = lng; remove_mapMarkers('destination_address', marker); } } else { window.alert("No results found"); } } else { window.alert("Geocoder failed due to: " + status); } }); I don`t know why but location data is none and previous days ago it was correct. {'lat_Origin': None, 'lon_Origin': None, 'lat_Dest': None, 'lon_Dest': None, 'origin_address': 'Calle San Amaro, 1A, 09001 Burgos, España', 'destination_address': "Calle de O'Donnell, Madrid, España", 'date': datetime.date(2021, 6, 12), 'maxPrice': None, 'OrderType': … -
django facebook data deletion callback
Does someone have an working example of facebook data deletion callback? I was searching for it for quite a long time, but still didn't find any, only on php and node.js, so if someone have a working example or link to git repository i wil be greatfull. -
Django: Pass form.cleaned_data to the view that handles the page to where user is being redirected with HttpResponseRedirect
I have the following situation and would appreciate your help very much. Making use of the Post/Redirect/Get design pattern, I have created a form with Django Forms. This then redirects to a page with HttpResponseRedirect. I have created a view for that page and that part works fine. I would like to use the form data (form.cleaned_data) on the redirected page to dynamically insert the (form.cleaned_data) values to a sql script and show the results using a template. Everything works smoothly but I just don't succeed in passing the form data. What works: Form (and the view with that form). Sql functionality works, without dynamically added form data, so it is a static sql for now. templating works fine redirect works fine. As you can see, all works fine but I can't make it dynamic. How to capture the cleaned form data and pass / forward it to the page (view) that loads with HttpResponseRedirect, (which is a page that loads using the GET method)? Thank you very much in advance. Kindest regards, PieThon -
Django Rest Framework - Optimize Serializer with nested objects and @property on related Model
Let me explain briefly the context with some code. Two related Models. One of them has a really expensive @property field: # models.py class MyModel(models.Model): [... fields ...] class RelatedModel(models.Model): [... fields ...] related_field = models.ForeignKey(MyModel, ...) @property def expensive_query_field(self): return OtherModel.objects.filter( Q(some_field__some_relation__id=self.some_field_id) | Q(some_other_field__some_other_relation__id=self.some_other_field_id) | [...] ).distinct().order_by('-id') On the serializer side those are mirrored: # serializers.py class RelatedModelSerializer(serializers.ModelSerializer): [... fields ...] expensive_query_field_objects = OtherModelSerializer(many=True) class MyModelSerializer(serializers.ModelSerializer): [... fields ...] related_field_objects = RelatedModelSerializer(many=True) Everything works fine BUT it's really inefficient, since the @property is a python-land thinghy and it's also querying off an unrelated Model I can't really prefetch_related or select_related to reduce the number of queries. Thus, when serializing an instance of MyModel, I end up with N expensive queries (with N equal to the number of RelatedModel connected to MyModel). I'm looking for optimization ideas to avoid the N+1 queries. I've tried, in MyModelSerializer.to_representation(), to manually pre-fetch all expensive queries in one go for all RelatedModel and then unpack the data directly into Queryset._result_cache but don't want to go so low-level as it makes code more fragile and I'm not even sure it might work :( -
Downloading a file in downloads directory - flask, python
I have a flask app in which it has a button to download an HTML report. The download button when hit creates an xlsx file. It worked fine until that app was running on my local server because the python code found my Downloads directory no matter what os it is using python's os module. Now the app is deployed on a remote server, in this case, how do you let the system know the client's download directory path where this xlsx file can then be created? Or any other pointers for a better solution if I'm missing something? -
DateTimeField not showing previous date and time when editing
I want previously set dates and times to be displayed before they are edited. The previously set name and description of my event are being displayed as it should. Here's a part of my code: Forms: class EventForm(forms.ModelForm): name = forms.CharField(label='Event name', widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(label='Description', required=False, widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'cols': 15})) date_hour_start = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={'type': 'datetime-local', 'class': 'form-control col-md-4'})) date_hour_end = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={'type': 'datetime-local', 'class': 'form-control col-md-4'})) Views: def event_update_view(request, event_id): event = get_object_or_404(Event, event_id=event_id) event.date_hour_start = datetime.datetime.strftime(event.date_hour_start, '%d/%m/%Y %H:%M:%S') event.date_hour_end = datetime.datetime.strftime(event.date_hour_end, '%d/%m/%Y %H:%M:%S') if request.method == 'POST': form = EventForm(request.POST, instance=event) if form.is_valid(): event = form.save() event.save() return redirect(reverse('list_events')) return redirect(reverse('list_events')) HTML (just a part): <div class="col-md-12"> <p style="margin-bottom: .5rem">Date and Time (Start) <span style="color:red">*</span></p> {{ form.date_hour_start }} </div> <div class="col-md-12"> <p style="margin-bottom: .5rem">Date and Time (End)<span style="color:red">*</span></p> {{ form.date_hour_end }} </div> Why isn't it working? Here's how it's showing. (It's aaaa because it's in Portuguese but it's the year) -
I'm getting this error using axios in my react app
I need to connect my backend and frontend, for that i'm using axios and i'm following this tutorial: https://www.digitalocean.com/community/tutorials/como-crear-una-aplicacion-web-moderna-para-gestionar-la-informacion-de-clientes-con-django-y-react-on-ubuntu-18-04-es but i'm getting this error and i dont know why My Error My backend My frontend1 My frontend2 It's my first time using react , django, and axios so i need help! -
Update or edit a specific field of my form from Django?
I am learning django and I am trying to edit / update a specific field of my model from my ListView, I mean I want to update only my field status, how can I do this? Models.py from django.db import models class RequestContract(models.Model): PENDIENT = "Pendiente" APPROVED = 'Aprobado' REJECTED = 'Rechazado' CANCELLED = 'Cancelado' STATUS = ( (PENDIENT, 'Pendiente'), (APPROVED, 'Aprobado'), (REJECTED, 'Rechazado'), (CANCELLED, 'Cancelado'), ) objective = models.TextField( verbose_name='Objeto', blank=False ) request_date = models.DateTimeField( verbose_name='Fecha de solicitud', null=True, blank=False ) status = models.CharField( verbose_name='Estado', max_length=30, choices=STATUS, default='Pendiente' ) def __str__(self): return self.objective forms.py from django import forms from .models import RequestContract class RequestContractForm(forms.ModelForm): class Meta: model = RequestContract fields = ('__all__') views.py In my listview I am rendering the form using the get_context_data method (I don't know if it is the best way for what I want to do), I think it is a good idea to use the patch method, because I only want to partially update my model, but idk how to use it class RequestContractList(ListView): model = RequestContract template_name = "contratacion/contratacion_list.html" paginate_by=5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['action_new_url'] = '/requestscontracts_create/' context['form'] = RequestContractForm() return context def patch(self): pass And finally this is my template,I … -
ipfshttpclient.exceptions.StatusError: HTTPError: 405 Client Error: Method Not Allowed for url: http+ip4://127.0.0.1:5001/api/v0/version?
How can I connect IPFS with my Django project? This error is thrown after installing ipfs for django and making changes in settings.py settings.py IPFS_GATEWAY_API_URL= 'http://localhost:8080/ipfs/', IPFS_STORAGE_API_URL= 'http://localhost:5001/api/v0/', IPFS_GATEWAY_API_URL= 'https://ipfs.io/ipfs/', DEFAULT_FILE_STORAGE = 'ipfs_storage.InterPlanetaryFileSystemStorage' IPFS_STORAGE_API_URL = 'http://localhost:5001/api/v0/' IPFS_STORAGE_GATEWAY_URL = 'http://localhost:8080/ipfs/' -
Django Sum of Avg's
I have the existing SQL query and struggling to get the same result from Django SELECT cast(sum(avg)/count(avg) as decimal(13,12)) as a FROM ( SELECT cast(sum(HG)/count(Things) as decimal(13,12)) as avg FROM mydb.mytbl WHERE `stuff` = 'AU' group by Things ) I have managed the count(avg) easy enough and can get the SUM or AVG of all it, but don't know how to get the sum of all the individual avg's -
Django Queryset filter
My code looks like below Extracting the tag-id from the Car class tags = [UUID('1b2990eb-f625-4458-8878-1ab199e3e72b'), UUID('6e663259-9bf0-4e2d-8bf6-11be14218036')] When I try the below codes : Car.objects.filter(uuid__in=tags).values_list('id',flat=True)[0] -> Output 11 Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all()[0] -> Output :11 Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all() -> Output : <QuerySet [11,12]> I want the output in the format of [11,12] -
Passing values from views.py to select tag in html template
I wrote a code that calculates the difference between two stations and the fees required by taking values from the user through the two variables "x" and "y" then calculates stations difference and the fees. I want to know how to pass the values in this code from a function in views.py to select tags in the html template and submit to execute the code. This is the function in views.py def postcalc(request): firstLine = ["Helwan","Ain Helwan","Helwan University","Wadi Hof","Hadayeq Helwan","El- Maasara","Tora El-Asmant","Kozzika","Tora El-Balad","Sakanat El-Maadi", "Maadi","Hadayek El-Maadi","Dar El-Salam","El-Zahraa'", "Mar Girgis","El-Malek El-Saleh","Al-Sayeda Zeinab","Saad Zaghloul", "Sadat","Nasser","Orabi","Al-Shohadaa","Ghamra","El-Demerdash", "Manshiet El-Sadr","Kobri El-Qobba","Hammamat El-Qobba","Saray El-Qobba", "Hadayeq El-Zaitoun","Helmeyet El-Zaitoun","El-Matareyya","Ain Shams", "Ezbet El-Nakhl","El-Marg","New El-Marg"] secondLine = ["El-Mounib","Sakiat Mekky","Omm El-Masryeen","Giza","Faisal", "Cairo University","El Bohoth","Dokki","Opera","Sadat","Mohamed Naguib", "Attaba","Al-Shohadaa","Masarra","Rod El-Farag","St. Teresa","Khalafawy", "Mezallat","Kolleyyet El-Zeraa","Shubra El-Kheima"] thirdLine = ["Adly Mansour","El Haykestep","Omar Ibn El-Khattab","Qobaa","Hesham Barakat", "El-Nozha","Nadi El-Shams","Alf Maskan","Heliopolis Square","Haroun","Al-Ahram", "Koleyet El-Banat","Stadium","Fair Zone","Abbassiya","Abdou Pasha","El-Geish", "Bab El-Shaaria","Attaba"] # Entering Gate check = 0 while(check==0): check = 1 try: x = input("Enter the Source station: ") if x in firstLine: currentStation = firstLine.index(x) currentLine = 1 elif x in secondLine: currentStation = secondLine.index(x) currentLine = 2 elif x in thirdLine: currentStation = thirdLine.index(x) currentLine = 3 except: check=0 msg = "Enter the station again" return render (request, "calc.html", {"msg":msg}) # … -
How to access attributes of the 'User' model extended by another model referenced by a OnetoOneField in admin.py
In model.py, I have a class extending the User model class Tutor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) In admin.py, I tried to access user.id with 'user_id', which works class TutorAdmin(admin.ModelAdmin): list_display = ('user_id', 'contact_number') However, when I try to access other attributes of 'user' such as username, email with this format class TutorAdmin(admin.ModelAdmin): list_display = ('user_id', 'user_username', 'contact_number') This occurs What is the format to access attributes such as user.username or user.email? -
Error inserting data into Django database field with a OneToOnefield
I've asked this question before and tried to Google it but I've had no luck, so I have simplified my question. I have two very simple models: one holds some shift numbers and the other holds some data related to the sale of gift cards during a shift. In this case, we have an employee who worked shift "1234" and sold $200.45 and $43.67 worth of gift card from each of two terminals. The models are below: class Data_Shifts(models.Model): shift_id = models.CharField(max_length=25, primary_key=True, db_column="shift_id", verbose_name="Shift ID") def __str__(self): return str(self.shift_id) class Data_GiftCards(models.Model): shift_id = models.OneToOneField('Data_Shifts', on_delete=models.CASCADE, primary_key=True, db_column="shift_id", verbose_name="Shift ID") net_sales_terminal_1 = models.DecimalField(max_digits=8, decimal_places=2, default=0) net_sales_terminal_2 = models.DecimalField(max_digits=8, decimal_places=2, default=0) def __str__(self): return str(self.shift_id) I then try to insert some test data into the table using the following command: Data_GiftCards.objects.create(shift_id="1234", net_sales_terminal_1="200.45", net_sales_terminal_2="43.67") Upon submitting the web form, I get the following error: Cannot assign "'1234'": "Data_GiftCards.shift_id" must be a "Data_Shifts" instance. I am boggled by this. I have a workaround that bypasses django and inserts directly into the table successfully, but this is dirty and I'd prefer to use the proper Pythonic Django way. What am I doing wrong here? Many thanks in advance. -
How can I access the outer loop context value in inner loop section in Django Template
In my case, I want to access the context value which is present in the outer for loop and use(print) that value in the inner for loop section. There are two context values one for the outer loop and the other one is for the inner loop. here is my template logic. when the condition becomes false it did not print the values that belong to the outer-loop context variable(else part of if statement not working). <div class="panel-group" id="accordion"> {% for x in queryset %} <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}"> Question </a> </h3> </div> <div id="collapse{{ forloop.counter }}" class="panel-collapse collapse"> <div class="panel-body"> <!-- <input type="button" onclick="updateques();" value="Edit!!"><br> --> <br><br> <div> <form action="tobeupdated" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{x.question.id}} <input type="hidden" id="quesid" name="quesid" value="{{x.question.id}}"> <label>Q- <input type="text" id="ques" name="ques" value="{{x.question.question}}" readonly></label><br><br> <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br> {% for q2 in queryset2 %} {% if q2.option_id == x.option_id %} <label>A- <input type="text" id="op1" name="op1" value="{{x.option.option1}}" readonly><br><br> <img src="{{q2.option1_img}}" alt="" srcset="" width="400"><br><br> <label>B- <input type="text" id="op2" name="op2" value="{{x.option.option2}}" readonly><br><br> <img src="{{q2.option2_img}}" alt="" srcset="" width="400"><br><br> <label>C- <input type="text" id="op3" name="op3" value="{{x.option.option3}}" readonly><br><br> <img src="{{q2.option3_img}}" alt="" srcset="" width="400"><br><br> <label>D- <input type="text" id="op4" name="op4" value="{{x.option.option4}}" readonly><br><br> <img … -
Django : unique=True constraint does not get removed using django migrations
I have a model as : class order(models.Model): serial = models.CharField(max_length=20,unique=True) I've migrated this model using django migrations (PostgreSql). Now I wish to remove the unique constraint. class order(models.Model): serial = models.CharField(max_length=20) On running makemigrations, only an AlterField migration is created : migrations.AlterField( model_name='order', name='serial', field=models.CharField(max_length=20), ), On migrating this, the unique constraint is not removed. (it's visible in pgAdmin). After this, I tried removing the constraint manually. The unique constraint name as in pgAdmin is 'order_serial_key'. In the migrations file, I added : migrations.RemoveConstraint( model_name='order', name='order_serial_key' ) On migrating, it shows ValueError: No constraint named order_serial_key on model order How can I remove this constraint using migrations ? -
Superuser can't access Django Admin Panel. It shows "You don’t have permission to view or edit anything."
I've created a custom User model in Django==3.2.3 Here is my model.py file class MyUserManager(BaseUserManager): """ A custom Manager to deal with emails as unique identifer """ def _create_user(self, email, password, **extra_fields): """ Creates and saves a user with a given email and password""" if not email: raise ValueError("The Email must be set!") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=60, unique=True, verbose_name='Email') first_name = models.CharField(max_length=30, verbose_name='First Name') last_name = models.CharField(max_length=30, verbose_name='Last Name') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('first_name', 'last_name') objects = MyUserManager() def __str__(self): return self.email def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin class Meta: verbose_name_plural = "Users" Here is my admin.py file class MyUserAdmin(UserAdmin): form = UserchangeForm add_form = UserCreationForm list_display = ('email', 'first_name', 'last_name', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': (('first_name', 'last_name'))}), ('Permissions', {'fields': ('is_admin',)}), ) add_fieldsets = … -
No parameter on drf_yasj on using swagger_auto_schema
Code Swagger Page name = openapi.Parameter('Product Name', in_=openapi.IN_BODY, description='Enter Product Name', type=openapi.TYPE_STRING) # cat = openapi.Parameter('Product Category', in_=openapi.IN_BODY, description='Enter Product Category', # type=openapi.TYPE_STRING) @api_view(['POST']) @swagger_auto_schema(manual_parameters=[name]) No parameter option in swagger window -
how to install templates in django? I connected the template to the views file and in the settings file. then i used render to display the template
I connected the template to the views file and in the settings file. then i used render to display the template ** def index(request): return render(request, 'pages/pages.html') ** and in the settings file i setted it through os library os.path.join(BASE_DIR, 'templates') but i'm still getting an error "template does not exist" while i'm very sure i typed the right path and imported the views file in the urls file and everything is fine just that template doesn't load. anyone knows what could be the problem? [1]: https://i.stack.imgur.com/Wdu2g.png -
How to add value to a many-to-many field in Django
Suppose I have a relation as down below: class Student(models.Model): firstname lastname ... class Teacher(models.Model): firstname lastname email ... class Meeting(models.Model): student = models.ManyToManyField(Student) teacher = models.ManyToManyField(Teacher) How should I add/set a value to field 'student' or 'teacher'. I tried to assign an object from related models to them but got an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use student.set() instead. -
How do I overwrite the variable from cleaned_data
I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved. if request.method == 'POST': form_w = ImageForm(request.POST, request.FILES) if form_w.is_valid(): form = form_w.save(commit=False) cd = form_w.cleaned_data['img'] im = Image.open(cd) width, height = im.size draw = ImageDraw.Draw(im) text = "TEST WATERMARK" font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) im.save('Luki/media/upload_p/{}'.format(cd)) form.save() return redirect('Luki:gallery') else: form = ImageForm() return render(request, 'Luki/upload_img.html', { 'form': form, })