Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django upload multiple files to dynamic subfolder
Is there any way to upload multiple files to a dynamic subfollder? I need to create the file system like this: _uploads _incident _folder1 _file1.docx _file2.xlsx _folder2 _file1.docx _file2.xlsx _file3.xlsx Where the name of the folder is defined in when upload files. I manage to upload multiple files but each time they are saved in incident folder and only 1 file is saved in subfolder folder1/folder2. These are some of my code. Models.py from django.db import models #Create your models here. def form_directory_path(instance,filename): # file will be uploaded to MEDIA_ROOT/<folder_name>/<filename> return 'incidents/{0}/{1}'.format(instance.folder_name, filename) class UploadFiles(models.Model): folder_name = models.CharField(max_length=40,unique=True) files = models.FileField(upload_to=form_directory_path) date = models.DateField(auto_now_add=True, blank=True, null=True) def __str__(self): return f'{self.folder_name} ({self.date})' Forms.py from django import forms from .models import UploadFiles # class FileFieldForm(forms.Form): # file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class FileFieldForm(forms.ModelForm): class Meta: model = UploadFiles fields = '__all__' widgets = { 'files': forms.ClearableFileInput(attrs={'multiple': True}), } Views from django.shortcuts import render from django.views.generic.edit import FormView from .forms import FileFieldForm from .models import UploadFiles class FileFieldFormView(FormView): form_class = FileFieldForm template_name = 'upload_files_app/upload.html' # Replace with your template. success_url = 'thankYou/' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('files') if … -
Django authenticate user does not work after logging in
I'm trying to create a custom session-based login in Django using a custom user model and a custom login template. For some reasons it worked at first but now the authenticate method from django.contrib.auth is not authenticating user. When it did work, the login and signup button were hidden. users/urls.py app_name = 'users' urlpatterns = [ path('login/', login_user, name='login_user'), path('logout/', logout_user, name='logout_user'), ] users/views.py app_name = 'users' def login_user(request): django_logout(request) message = '' if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: django_login(request, user) return redirect('homepage') else: message = "Log in failed!" messages.error(request, message) return redirect('users:login_user') else: return render(request, 'users/login.html') @login_required(login_url='users/login/') def logout_user(request): django_logout(request) templates/users/login.html <form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="/"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> <label class="form-label" for="form1Example1">Email address</label> <input type="email" name="email" id="form1Example1" class="form-control" /> </div> <!-- Password input --> <div class="form-outline mb-4"> <label class="form-label" for="form1Example2">Password</label> <input type="password" type="password" id="form1Example2" class="form-control" /> </div> <!-- Submit button --> <button type="submit" class="btn btn-primary btn-block">Sign in</button> </form> users/models.py class CustomUserManager(BaseUserManager): def create_superuser(self, email, password): if email is None: raise TypeError('Users should have an Email') if password is None: raise TypeError('Password should not be none') user … -
How can i edit file field in Django?
how can I change the input file in Django?I have 3 input fields. But I want to change 2 of them another one has to store old file from database. How can I restore it -
Django with Conda DJANGO_SETTINGS_MODULE error
I am using Django installed under conda-forge conda install -c conda-forge. Right after installation, when I call django-admin, I receive the following error Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). I found the documentation recommend pointing it to mysite.settings, but this is before I start a project. Mind have anyone tell me how should I deal with it? Best, HS -
Dialogflow webhook not working with django
My Dialogflow webhook was working completely fine till yesterday but it is suddenly not connecting to the webhook today. Although I've made no changes in the code. I'm getting the following fulfillment status: Webhook call failed. Error: NOT_FOUND, State: URL_ERROR, Reason: ERROR_NOT_FOUND, HTTP status code: 404. Please note the following points: Fulfillment URL is written in the correct format (with HTTPS protocol). My Django server is running fine and it is also receiving requests when instigated from the browser. (Just not receiving requests from Dialogflow) Suddenly, none of my Dialogflow agents (previously built and working fine) are sending requests to Django/Flask server. I've checked multiple things like trying from different Dialogflow accounts and different browsers but I can conclude that the issue is with the Dialogflow webhook/Fulfillment. Please, help me with the solution. Thank you in advance. -
How to post data in django-cms using cms.api?
I am using django-cms. I want use react as front end and post data in django-cms by using cms.api. I am not able to get proper solution. -
How to save django form without displaying it
I have a page (se_balance.html) that displays a parent form and a child formset. The contents of the parent form is set by the link selected by the user on the previous page. I would like to only display the formset and the parent form to be saved without being displayed, however, if I do not have the parent form in the html I receive an error related to the fact that the parent form is invalid. This is the view used to generate the page in question class CaseView(TemplateView): model = Case template_name = "../templates/se_balance.html" def get(self, *args, **kwargs): # here the parent form is created based on user selected link from previous page p = self.request.GET.get("p", None) case_form = CaseForm(initial={'pharm_class_name': p}) #i sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none()) return self.render_to_response( { "case_form": case_form, "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) def post(self, *args, **kwargs): form = CaseForm(data=self.request.POST) sideeffect_formset = SideeffectFormSet(data=self.request.POST) if form.is_valid(): case_instance = form.save(commit=False) if self.request.user.is_authenticated: case_instance.user = self.request.user case_instance.save() if sideeffect_formset.is_valid(): sideeffect_name = sideeffect_formset.save(commit=False) for sideeffect in sideeffect_name: sideeffect.case = case_instance sideeffect.save() return redirect( reverse( "results", kwargs={"case_id": case_instance.case_id}, ) ) How should I amend it so that I don't ned to display the parent form to the user -
How to built ola in django
I want to crate ola like service app using django that provide cooking and other services so i want to integrate map just like ola in this django project. What technologies packages and APIs i should use if someone could help that would be very helpful. -
How to fix AttributeError in django?
I am unable to find out the issues. Please let me How to fix this one and which website is good for this types of issues.