Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update form with multiple images
I'm trying to implement product update form with multiple images. I have already done the main form but have stucked with following thing: When user want to update image using formset he can use only square images, so i've implemented custom validation for it. But here is the problem: after the validation the form "current" image and "clear" checkbox disappear. Here is what it is: incorrect form after validation Here is how it should be + validation error message (it's not on the screenshot): correct form after validation The only place where the isse could be is following piece of code form.instance = form.cleaned_data.get('id') fixes the problem when after form submission it shows me an uploaded image (which is not valid by the way), because i receive it from form.instance.image.url: class ProductImageUpdateInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if form.cleaned_data and form.cleaned_data.get('image'): try: square_image_validator(form.cleaned_data.get('image')) except ValidationError as ex: form.instance = form.cleaned_data.get('id') form.add_error('image', ex.message) # FormSet for updating product images ProductImageUpdateFormSet = inlineformset_factory(Product, ProductImage, formset=ProductImageUpdateInlineFormSet, fields=['image'], max_num=3, min_num=1, can_delete=False) class ProductUpdateForm(ProductAddForm): def __init__(self, data=None, files=None, instance=None, **kwargs): super().__init__(data=data, files=files, instance=instance, **kwargs) self.image_formset = ProductImageUpdateFormSet(data=data, files=files, instance=instance, **kwargs) self.fields['price'].initial = instance.price -
TemplateDoesNotExist in get_template in loader.py - Django
Hello, this is the error I'm getting on VS code. I'm using Windows 10. I'm following this course and did exactly as they said. It's still showing me this exception. These are my folders and files. This is from the settings.py file. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my loader.py file from the template folder. from . import engines from .exceptions import TemplateDoesNotExist def get_template(template_name, using=None): chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) raise TemplateDoesNotExist(template_name, chain=chain) def select_template(template_name_list, using=None): if isinstance(template_name_list, str): raise TypeError( 'select_template() takes an iterable of template names but got a ' 'string: %r. Use get_template() if you want to load a single ' 'template by name.' % template_name_list ) chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") def render_to_string(template_name, context=None, request=None, using=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request) def _engine_list(using=None): return … -
Build a PoC of OCPP server which can communicate with an EV charger using OCPP protocol
I am new to OCPP protocol and I have the following task involving OCPP protocol which I can not find any documentation about it: build a PoC of OCPP server which can communicate with an EV charger using OCPP protocol.Server should be implemented using Python django. Features needed on server side: Connect an EV charger to server List all connected chargers Authenticate user via RFID Start/stop charging process. I basically do not understand the OCPP server. I think it's like a server that receives the requests from clients and respond them. I also found the python package available in the link here. But I could not find the documentations for this, for example, is there any method to list all connected chargers. Can anyone give me simple demo implementation for this task on Python django? Any help would be aprreciated. -
django receiver only works with superuser status
in my users/models.py I have user creation which works fine. I added this. @receiver(post_save, sender=User) def create_userprofile(sender, instance, *args, **kwargs): up, created = UserProfile.objects.get_or_create(user=instance) if created: logger.debug(f"Created UserProfile for {instance.username} using create_userprofile(*)") up.save() the UserProfile instance it creates only creates with superuser. It doesn't matter I add the user through the normal sign up process or the admin. When I change the status of the user to superuser the receiver is kicked off. I want the receiver code to kick off every time. -
How to add the logged in user email in a field in the model directly without using a view in django
I have a field in my model as shown below uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False) This field will store the username (email in this case) of the user who has uploaded the data. As you can see that this is non editable so there is no way the user can edit it. The data has to be entered from the admin pannel. I wanted to know if there is any way to fill this field with the username of the loged in user who is uploading the data. I know if I use the view I can do some thing like uploaded_by = request.user So is there a way to do the same directly in the model so that I can use the admin pannel directly to store the username without using a view. -
How to update model fields from views with values from a href/url?
I'm making a events website, I need to show the event history of a user logged in. Currently I'm only passing Event instance to below template not User instance So when he clicks on Register for Event button on a certain event with id event.id. {%for event in events%} <div class='card-event'> <div style="font-weight: 600; margin-top:5px;font-size: 20px;">{{event.name}}</div> <div style="margin:10px 0 5px 0;">{{event.event_desc}}</div> <div style="margin:5px 0 10px 0;">Entry Fee: {{event.entry_fee}}</div> <a href="{%url 'update-event' value1=user.id value2=event.id%}"><button class='register-button'>Register for Event</button></a> </div> {%endfor%} He is redirected to url path('update-event/<value1>/<value2>/',web_views.update_event,name='update-event') Then the update_event view where database is updated,and is redirected to a simple stable template my_events.html def update_event(request,value1,value2): user= User.objects.get(id=value1) ev=Event.objects.get(id=value2) data=Participated(user_id=user,event_id=ev) data.save() return redirect(request,'webpage/my_events.html') This is the Participated model class Participated(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE) event_id=models.ForeignKey(Event,on_delete=models.PROTECT) I'm getting an error Reverse for '<WSGIRequest: GET '/update-event/1/4/'>' not found. '<WSGIRequest: GET '/update-event/1/4/'>' is not a valid view function or pattern name. So how to insert values to Partcipated model? -
How to set token expiration time when using django-rest-authtoken?
I'm using the django-rest-authtoken library (https://github.com/wichmannpas/django-rest-authtoken) to manage my API users. The biggest inconvenience is that the user authentication tokens expire in 24 hours, effectively requiring to perform login every day. Unfortunately I couldn't find a way to change the token expiration time. Any help appreciated. -
Can we create multiple users in Django which edit a single product information?
I am new to Django. I have to work on a project which allows 5 or more users to edit a single value. For example, User1 logs in and modifies the status of a product. The modification should be publicly visible. All groups should now see that okay, User1 has added this information at this time. Now, User2 should also be able to modify it and rest should see it. How can we make this happen? Thank you for your valuable time! -
Django rest setting the one to one relation creating an post method
I am new to django,I have created the models with OnetoOne relationship , I have user table and i have onetoone relation with storyboard library table, the issue is when i am creating an storyboardlibraby object , i need to save the user objectin the onetoonefield , even after adding user object not able to save the storyboardlibrary to the database, if anybody can help on this please help me , i will add the code which I have written. class StoryboardLibrary(models.Model): name = models.CharField(max_length=50) data = JSONField(db_index=True) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return "%s The Library" % self.name Serializer class class StoryboardSerializer(serializers.ModelSerializer): class Meta: model = StoryboardLibrary fields = ('data','name','user') views post method def add_storyboard(request): # validating for already existing data if StoryboardLibrary.objects.filter(**request.data).exists(): raise serializers.ValidationError('This data already exists') user = get_object_or_404(User, id=request.user.id) request.data['user'] = user storyboard = StoryboardSerializer(data=request.data) print(storyboard) if storyboard.is_valid(): storyboard.save() return Response(storyboard.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_404_NOT_FOUND) After hitting the post api i am not able to save the data storyboardserializer is not valid hence it is executing the else block and returning the status 404 not found -
How to test a Django REST APIView class with get and post methods combining multiple models?
I am currently testing my API for a game (models and view) and since I have never written tests before, I am only getting errors for my tests. This is my GameView: class GameView(APIView): """ API View that retrieves the game, retrieves an game round as well as a random resource per round allows users to post tags that are verified and saved accordingly to either the Tag or Tagging table """ def get(self, request, *args, **kwargs): current_score = 0 if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk random_resource = Resource.objects.all().order_by('?').first() first_resource_serializer = ResourceSerializer(random_resource) gameround = Gameround.objects.create(user_id=current_user_id, gamesession=gamesession, created=datetime.now(), score=current_score) gameround_serializer = GameroundSerializer(gameround) return Response({ # 'gametype': gametype_serializer.data, 'resource': resource_serializer.data, 'gameround': gameround_serializer.data, }) def post(self, request, *args, **kwargs): tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) This is what I have tried so far in my test suite: class ARTigoGameViewTests(TestCase): def setUp(self): self.client = APIClient() self.artigo_game_data = {'resource': '', 'gamesession': '', 'gameround': ''} self.response = self.client.get('http://localhost:8000/artigo_api/artigo_game/', self.artigo_game_data, format="json") def test_api_can_create_game_data(self): """Test the api has resource retrieve capability.""" self.client = APIClient() self.assertEqual(self.response.status_code, status.HTTP_200_OK) def test_get(self): response = self.client.get('http://localhost:8000/artigo_api/artigo_game/') self.assertEqual(response.status_code, 200) def test_post(self): self.client = … -
Serviceworker.js code being shown on page (only in Google) each time i open root site directory and being replaced with index.html after ctrl+f5
I guess, it is something about django-pwa. This problem appears only in google chrome (in local mode it even works fine on 127.0.0.1:8000 but doesnt work on localhost:8000). My project structure: D:. ├───api │ └───migrations ├───core │ └───__pycache__ ├───games │ └───migrations ├───main │ ├───migrations │ └───__pycache__ ├───static │ ├───images │ └───js ├───staticfiles └───templates it appears, that chrome browser requests the empty path for pwa.urls firstly, but other browsers requesting main urls. i dont really how to make chrome request my urls from main app on first place. this is my urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.views.generic import TemplateView from rest_framework.schemas import get_schema_view import debug_toolbar schema_url_patterns = [ path('api/v1/', include('api.urls')), ] urlpatterns = [ path(r'', include('main.urls')), path('openapi', get_schema_view( title="Gamers Gazette", description="API!", version="1.0.0", patterns=schema_url_patterns, ), name='openapi-schema'), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui'), path('redoc/', TemplateView.as_view( template_name='redoc.html', extra_context={'schema_url':'openapi-schema'} ), name='redoc'), path('admin/', admin.site.urls), path('games/', include('games.urls')), path('api/v1/', include('api.urls')), path("", include("pwa.urls")), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include('debug_toolbar.urls')), ] + urlpatterns this is my serviceworker.js: var staticCacheName = 'djangopwa-v1'; self.addEventListener("install", event => { this.skipWaiting(); event.waitUntil( caches.open(staticCacheName) .then(cache => { return cache.addAll(filesToCache); }) ) }); // Clear cache on activate self.addEventListener('activate', … -
Cant upload multilple images using django
I'm trying to create page to add new product with it's images in other model on my website using Djnago. The length of the list of images I get is always 0 and i'm getting IndexError: list index out of range. I guess that i'm getting files from request not properly using images = request.FILES.getlist('images') models.py class Products(models.Model): product_name = models.CharField( max_length=255, verbose_name='Product name') product_slug = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) product_image = models.ImageField( default='image-placeholder.png', verbose_name='Image') creaton_date = models.DateTimeField(auto_now_add=True) brand = models.ForeignKey( Brands, verbose_name='Brand', on_delete=models.PROTECT) price = models.FloatField(verbose_name='Price') description = models.TextField(null=True, verbose_name='Description') category = models.ForeignKey( Categories, on_delete=models.CASCADE, verbose_name='Category') bought_count = models.IntegerField(null=True, default=0) template.html <form id="checkoutform" action="" method="post"> {% csrf_token %} <div class="caption"> <div class="form-group"> <input class="input" type="text" name="product-name" placeholder="Product name"> </div> <div class="form-group"> <input class="input" type="text" name="brand" placeholder="Brand"> </div> <div class="form-group"> <input class="input" type="number" name="price" placeholder="Price"> </div> <div class="form-group"> <input class="input" type="file" multiple name="images" placeholder="Images"> </div> <div class="form-group"> <input class="input" type="text" name="desc" placeholder="Description"> </div> <div class="form-group"> <input class="input" type="text" name="category" placeholder="Category"> </div> <input type="submit" value="Submit"> </form> views.py def create_product(request): if request.user.is_superuser: if request.method == 'POST': data = request.POST images = request.FILES.getlist('images') brand = Brands.objects.get(name=data['brand']) category = Categories.objects.get(name=data['category']) product = Products.objects.create( product_name = data['product-name'], brand=brand, price = data['price'], description = data['desc'], category = … -
How to fix "Authentication credentials were not provided "on post request Even on [AllowAny]
I have a simple function-based @api_view(['POST']) with @permission_classes([AllowAny]) And in DRF settings in settings.py are: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } Now the Documentation says The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated. But I'm getting the following response on making a post request: { "detail": "Authentication credentials were not provided." } Can anybody describe what might be the problem? Is I have to modify to DEFAULT_AUTHENTICATION_CLASSES from the settings or something else, As I don't want to permit the request on this @api_view. -
Fatal error while creating superuser in Django (django-rest-framework)
I want to make an AbstractUser without a username field so I got this: from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import RegexValidator class CustomUser(AbstractUser): email = models.EmailField(max_length=254, unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] session_token = models.CharField(max_length=10, default=0) #Newsletter/Shipment Info (not required) newsletter = models.BooleanField(default=False) first_name = models.CharField(max_length=35, blank=True, null=True) last_name = models.CharField(max_length=35, blank=True, null=True) adress = models.CharField(max_length=50, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) postal_code = models.CharField(max_length=6, blank=True, null=True) phone = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{9}$/')], blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I got this migrated into the database and now I need to craete an admin user so I would be able to enter the admin panel. I typed email and both passwords into the comand prompt after python manage.py createsuperuser and I got this error: Traceback (most recent call last): File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 22, in <module> main() File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 195, in handle … -
Remove group when the user is removed django
I'm new to Django and I've created a registration form where, when a user signs up, it automatically creates a group with the same name as the user's username and puts the new user in it. In this way, every user is inside a unique user group (that happen to have the same name as the user inside it). Now, my problem is that, if I delete the user, the group clearly won't be deleted as well. Is there a way to automatize this process? So, delete user --> delete the group he/she/it was in there? My code views.py @unauthenticated_user def register_user(request): if request.method == "POST": form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Succesfully") # every user is inside an unique group with its name Group.objects.get_or_create(name=username) group = Group.objects.get(name=username) group.user_set.add(user) user.save() return HttpResponseRedirect('register') else: pass else: form = RegisterUserForm() return render(request, 'authenticate/register_user.html', { 'form': form, }) -
Return one field after creation via post-request in django rest framework
This is my class-based view: class PurchaseAPICreate(generics.CreateAPIView): serializer_class = PurchaseSerializer and serializer: class PurchaseSerializer(serializers.ModelSerializer): class Meta: model = Purchase fields = "__all__" Get-request return me all fields, but I need only id. I tried fields = ('id',). But post request needs all fields for serialization. I did this, but think it shouldn't work in this way. class PurchaseAPICreate(generics.CreateAPIView): serializer_class = PurchaseSerializer queryset = Shop.objects.all() def create(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = PurchaseSerializer(queryset, many=True) return Response({ 'id': serializer.data[len(serializer.data)-1]['id'] }) How I can get only id in right way? -
Using User Profile to automatically add to field
In my pervious question I asked how I can automatically save the user submitting the form. I found the form_valid method to be the best in that case. However in my models I also have a user profile model like this models.py .... class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=24) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) email = models.EmailField(max_length=64) phone_number = models.CharField(max_length=12) department = models.ForeignKey(Department,null=True,on_delete=models.SET_NULL) supervisor = models.ForeignKey('self',blank=True,null=True,on_delete=models.SET_NULL) ... As you can see I used the One to One method to make my UserProfile As before in my models.py I have my reports model ... class Report(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False) department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL) user= models.ForeignKey(User,on_delete=models.PROTECT) submission_date= models.DateField(auto_now=True) #invisible to user submission_time = models.TimeField(auto_now=True) #invisible to ,user date = models.DateField(default=now,blank=False) time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss") location = PlainLocationField() building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL) size = models.PositiveIntegerField() notes = models.TextField(blank=True) def __str__(self): return f'{self.date} {self.time} ({self.company}) ... My question how I can make it so that the department field will load from the user profile? I would hope to eventually make it possible for users in the same department to be able to view and update each others Reports. As before: form.py class ReportForm(forms.ModelForm): class Meta: model = Report fields = '__all__' location = PlainLocationField() … -
loading foreign key data in drop down select name too slow
I'm trying to show foreign key data as a drop down list, but we have a big data, the problem is it takes too long to load page that has the drop down field with the foreign key, is there a way to load it part by part? here is my models.py class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,default=1) full_name = models.CharField(max_length=150,verbose_name=_('ناوی تەواو')) dob = models.DateField(max_length=14,verbose_name=_('بەرواری لەدایک بوون')) city = models.ForeignKey(City,on_delete=models.CASCADE,verbose_name=_('شار')) class Meta: constraints = [ models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information') ] def __str__(self): return f'{self.full_name} - {self.city} - {self.dob}' and here is my views.py def add_new_post(request): ... context = { 'form':form, 'room_number':room_number, 'cities':City.objects.all(), 'all_guests':Vistor.objects.all().order_by('-pk'), #the problem is here, has a big data } return render(request,'booking/add_booking.html',context) and here is my templates <div class="grid md:grid-cols-10 md:gap-5 child_formset_row" id="guests_no-${form_no}"> <div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "full information" %}</label> <select name="guestinfo-0" id="guestinfo-0" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white"> <option value="-----">------</option> {% for c in all_guests %} <option value="{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}">{{ c.full_name }} - {{c.city}} - {{c.dob | date:'Y-m-d'}}</option> {% endfor %} </select> </div> <div class="col-span-4 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "reason" %}</label> <input type="text" … -
Gunicorn status is active(running) but service is disabled
when I run 'sudo systemctl gunicorn status', it shows to me : Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: active (running) since Sun 2022-02-06 11:55:05 EET; 23min ago I cant figure out why it is disabled. here is my gunicorn.service : [Unit] Description=gunicorn daemon After=network.target [Service] User=arh Group=www-data WorkingDirectory=/home/arh/toy-model/server ExecStart=/home/arh/toy-model/venv/bin/gunicorn --workers 3 --bind unix:/home/arh/toy-model/server/server.sock server.wsgi:application [Install] WantedBy=multi-user.target -
ModuleNotFoundError: No module named 'djoser' while running Django + Docker project
To add registration to django-project, I decided to use 'djoser' library. But while making migrations, the same error raises: Creating school-co_server_run ... done Traceback (most recent call last): File "/home/web/server/manage.py", line 22, in <module> main() File "/home/web/server/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/web/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/web/venv/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'djoser' ERROR: 1 The thing is that I already pip installed djoser (using the newest update of pip), I froze djoser too with the help of requirements.txt: asgiref==3.2.10 attrs==21.2.0 Django==3.1 django-environ==0.8.1 django-extensions==3.1.5 django-filter==21.1 djangorestframework==3.12.4 djangorestframework-camel-case==1.2.0 drf-spectacular==0.21.0 inflection==0.5.1 jsonschema==4.2.1 Markdown==3.3.6 mysqlclient==2.1.0 Pillow==8.4.0 pyrsistent==0.18.0 pytz==2021.3 PyYAML==6.0 sqlparse==0.4.2 uritemplate==4.1.1 djoser==2.0.1 pandas=1.1.3 But it still doesn't work. Section of 'settings.py' INSTALLED_APPS also is correct: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', 'school_co', 'django_extensions', 'rest_framework', 'rest_framework.authtoken', 'drf_spectacular', 'djoser', 'rest_framework_simplejwt', ] -
How to merge a function into another
Sorry for asking a basic thing. new to Python and Django , I want to resend email if the OTP from PUT request is incorrect. I have a function which send email with otp automatically on Register. But if user PUT incorrect OTP I want to resend that email with new otp, So I want to merge sent_email_otp into verifyEmail function. So how could I achieve that? @receiver(post_save, sender=CustomUser) def send_email_otp(sender, instance, created, **kwargs): if created: try: subject = "Your email needs to be verified to use site" message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})' email_from = settings.EMAIL_HOST_USER recipient_list = [instance.email] send_mail(subject, message, email_from, recipient_list) print(f"Email Sent to {instance.email}") except Exception as e: print(e) print("Something Wrong at send_email_otp") @api_view(['PUT']) @permission_classes([IsAuthenticated]) def verifyEmail(request, pk): user = CustomUser.objects.get(id=pk) data = request.data otp_to_verify = data['otpForEmail'] if otp_to_verify == user.otpForEmail: user.isEmailVerified = True user.save() message = {'detail': 'Your email is now verified'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
Show image name inside the image field in Django forms
I have this edit or update form in which I want to display only the image name in the form for a better user experience so that the user could know which image he has uploaded while creating the data. I am storing the image name in the model as well,but i want to display the image name inside the image field. forms.py class MenuCategoryForm(forms.ModelForm): image = forms.ImageField(allow_empty_file=True, required=False) class Meta: model = MenuCategory fields = ['name', 'description', 'menu_options'] view def menu_category_update(request, id): item = MenuCategory.objects.get(id=id) if request.method == 'POST': form = MenuCategoryForm(request.POST, request.FILES, instance=item) if form.is_valid(): if request.FILES['image']: image = request.FILES['image'] image_url = upload_image(image, 'menu_category', image.name) obj = form.save(commit=False) obj.image_url = image_url form.save() else: form.save() return redirect('menu-category') else: form = MenuCategoryForm(instance=item) context = { 'form': form, 'item': item } return render(request, 'menu/menu_category_update.html', context) -
best code for this query in Django query DRF
I write a code for get all image of a list of objects these are my my model code models.py: class Estate(models.Model): name = models.CharField(max_length=50, null=True, blank=True) . . . class Image(models.Model): sell_id = models.ForeignKey( Estate, related_name = "images", on_delete=models.CASCADE, null=True ) image = models.ImageField(upload_to="images/sell/", null=True) i wanna to get images of estate with get request this is my code that I wrote: serializer.py: class ImageEstate(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" views.py: class EstateImageList(APIView): permission_classes = [AllowAny,] serializer_class = ImageEstate def get(self, request): estates = Estate.objects.all() data = {} for estate in estates: estateimage = estate.images.filter().first() serializer = ImageEstate(estateimage) data[sell.id] = serializer.data return Response(data, status=status.HTTP_200_OK) but I think these logic don't have good performance what are the best queries for get first image of all objects list. additional I wanna to be able to use filters in this list objects. any suggestion for this question -
Creating ForeignKey reference with 2 different models as choice
Here is what i want to try, I have a User model inherited from Abstract user with custom manager, i need a feeld in CustomUser model to choose either Seller model or Customer model class CustomUser(AbstractUser): is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) user_type = ? "I want to have a choice feild to choose either Seller or Customer model" USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class CustomUserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, password=None, **extra_fields): if not email: return ValueError('Email required') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() 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 SellerDetails(models.Model): pass class CustomerDetails(models.Model): pass -
Problem on performing CRUD operation using Django REST API
Hey I am new to Django Rest Framework.I have recently created REST API name "api/studentapi" using django REST framework in local host. The CRUD operation works perfectly fine in browseable API. But When I try to access the same API from third party python file, I am not able to perform POST operation although I am able to perform GET operation.While performing POST operation the server reponse me as "Unsupported Media Type: /api/studentapi/".I am posting series of code images so that the stuffs gets more clear The third party python app that I have created to access the "api/studentapi" The file structure of my project The model form that I have created The serializer files that I have created The urls code And Finally the view file