Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to roll back execution of delete method with ldap3
I'm using Django 4.1 and ldap3 to connect directory service using ldap. Is there any way to roll back execution of delete method? the sample code likes below: # import class and constants from ldap3 import Server, Connection, ALL # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') # perform the Delete operation c.delete('cn=user1,ou=users,o=company') #some checks here #if condition: # user1.recover() after some checking, I want to recover user's data based on a condition. Thanks! I've searched about rollback delete execution, but did not find any solution. -
Clean up unused database tables after removing a Django app?
When I remove a Django app from my list of INSTALLED_APPS, it doesn't get rid of the old database tables; running ./manage.py makemigrations doesn't detect any changes. Apart from going into the database myself and dropping the old tables, is there a better way to clean up unused tables after uninstalling an app from my Django project? -
Display data by date, when data comes from multiple models in Django
I'm currently working on an app with Django 4.1. I try to display a resume of some data comming from the database. Here is a simplified example of my models: class Signal(models.Model): data1 = models.CharField() data2 = models.CharField() date = models.DateTimeField() class Ban(models.Model): data3 = models.CharField() data4 = models.CharField() date = models.DateTimeField() What I'm trying to do is getting filtered data from these 2 models, and make a list ordered by date from all this data to display it. someting like: Ban1 (08/03/2023) Ban2 (07/03/2023) Signal2 (06/03/2023) Ban3 (05/03/2023) Signal1 (04/03/2023) Thanks in advance for your ideas -
Django I want to make comments on category posts
I want to make comments on posts. I found a lot of monual, but it either does not fit or does not work. I need to create a separate comment view function and display the comment form in a template. I don't understand how to make a separate comment function and display it in the post template. Need a simple, elegant solution to the problem. class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(episode,on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) FORM.PY from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') Views from .forms import * from .models import * ... def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'season':seasonpages, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): … -
How to add more details in a shoping cart in django?
I am building a application which is quiet similiar to an Ecommerce Shopping Cart in Django. However, in my case for each item in the shopping cart belongs to someone. So, instead of having the name of the item, the quantity, the price, ..., I would like to be able to see for each item, the name of the buyer, the receiver, the receiver's phone number and so fourth. So, for each order ID, I will be able to the details of beside the price, the quantity and items. Here are my file Cart.py class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # store current applied coupon self.coupon_id = self.session.get('coupon_id') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.prix), 'destinataire':product.destinataire } if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def remove(self, … -
How would I update a field to set a default value?
After updating an existing django field to have a default value if I save the field with a null value I get the error: IntegrityError: null value in column rather than the field being set to the default, does anyone know why this may be? If I include null=True it just sets it to null. -
Django sitemap problem for domain/category/city listing pages
I have a business directory and i made sitemaps for categories and firms, but when i came to build sitemap for category/city listing pages, i couldn't resolve. https://www.endustri.io/firma/enerji/bursa/ This is my live website. firma is prefix for business directory, enerji is a category and bursa is city. I am listing companies correctly. I made sitemap5.py codes with chatgpt. #Before the live version i am making local tries. but the result is here <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> </urlset> here is my models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() aciklama = tinymce_models.HTMLField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-category', args=[str(self.slug)]) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="firma", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural … -
Setting a timer for players in an online game in Django [closed]
I am implementing an online poker game with Django. Each player in the game has a certain amount of time to perform an action. What solution do you suggest for placing this timer? For this project, I am using Django Channel and WebSocket, and the scheduling work is done there -
Accessing Django on a secondary device
I am trying to access Django from a secondary device i.e. android phone. I have made sure that The laptop I am running Django on is connected to the same network as my secondary device. I have turned off the firewall on my laptop I configured CSRF to accept POST requests a trusted origin in settings.py Thereafter running python manage.py runserver 0.0.0.0:8000 , the POST requests on my website works when I access it from the laptop I am running Django from. However, when I use the same link http://192.168.16.130:8000/ on my phone, the POST requests don't work. import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.16.130', '127.0.0.1', 'localhost', '0.0.0.0'] # !!! Added for CSRF protection # CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_ALL_ORIGINS=True CORS_ALLOWED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # !!! Added for … -
Cookiecutter-django custom User field is never saved to DB
I'm struggling with a banal (I guess) issue with cookiecutter-django... I added the field invitation_code to users.models.User: class User(AbstractUser): """ Default custom user model for pintable. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Full name"), max_length=255, null=True, blank=True) first_name = None # type: ignore last_name = None # type: ignore invitation_code = CharField( _("Invitation code"), max_length=8, null=True, blank=True ) Then I added the same field to users.forms.UserSignupForm: class UserSignupForm(SignupForm): """ Form that will be rendered on a user sign up section/screen. Default fields will be added automatically. Check UserSocialSignupForm for accounts created from social. """ invitation_code = CharField( label=_("Invitation code"), widget=TextInput(attrs={"placeholder": _("Invitation code")}), ) The problem is that when a new user is saved to DB, the invitation_code field is always None. What am I missing..? Thanks for your help! -
How to auto create foreingKey object (python with django)
I'm creating a simple rest api This is my actual result from devices, i create first the group and options, and then associate, but i want to create the options at the same time i create the device. My result from devices right now [ { "id_device": "a099d2ce-812b-4d85-8c8b-cfe71057fbe7", "group": { "id_group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "name": "Cozinha" }, "options": [ { "id_option": "1b383a37-5229-4ae0-9649-f76aa32eeda0", "name": "1", "identifier": "POWER1" }, { "id_option": "4ff5406a-8c7b-4517-9ec0-14fd4f68f30b", "name": "2", "identifier": "POWER2" }, { "id_option": "a541216d-f509-4461-85ca-444491ac9217", "name": "3", "identifier": "POWER3" }, { "id_option": "3debe828-edd6-4d83-bfd8-2776a1594380", "name": "4", "identifier": "POWER4" } ], "name": "Interruptor 4", "identifier": "identifiertest" }, ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id_option = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id_group = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id_device = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): … -
Structure Policy for Django / Python Libraries
Question Summary Hi Folks, This is a kind of opinion question, I've built a Django library for my company and I keep swithering and changing my mind on how to structure it. Possible strategies I've come up with are below: Method 1 - Individual Libraries Split all parts of the library into separate repos. For example my_library_core my_library_cookies my_library_exporter and include from them individually. Pros Each library is compartmentalised and can be updated or included individually, so you can include only some of the functionality and install only some of the library modules. Cons Dependencies / functionalities between libraries can get out of sync, if library one is using version 1 of the core library and library two is using version 2, you're forced to upgrade both to upgrade one. Lots of separate repos to keep on top of. Harder to have a reliable "core" library for common functionality. Feels messy / uncentralised. Method 2 - Monolithic Library Have one large library that contains all functionality. Pros Centralised, everything is referencing the same library. Dependencies are centralised, the whole library has one set of dependencies that apply to all sub apps. Neater, everything imports from a one library. Cons Upgrading … -
Can't make superuser: error no such column
Hi I try make superuser to login my admin panel but I recieved this error while making superuser: django.db.utils.OperationalError: no such column: accounts_user.password1 and this is my model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(unique=True, max_length=10) email = models.EmailField() password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) is_publisher = models.BooleanField(default=False) def change_user_type(self): if self.is_publisher: self.is_superuser = True self.save() -
Handling concurrent user in Django + PostgreSql
I am creating a website which will take input from form and store it to database (PostgreSql) and the Input will be used for operation using python (eg: adding two numbers taken from form) and also there will be a button to take input from form again and previous given input will also be seen by a click. My question is : Let's say 100 users at same time comes to the website and filling the form, then in that case how should I handle the database, how to Store data each time from form so that It will not be an issue for other user and user can only see their previous input. I am new to development field, So I have no idea how to handle this. -
I am experiencing an error which comes anytime
I am experiencing an error which comes anytime i.e. sometime the code works fine but other time, this error occurs. I am working on login and signin project with minimalist html. The error is "Reason given for failure: CSRF token from POST incorrect." from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from home.models import contactIssue from django.contrib.auth.forms import UserCreationForm def index(request): if (request.method=="POST"): if (request.POST.get('LoginButton','false')!='false'): return redirect('loginPage') else: return redirect('signinPage') return render(request, template_name="index.html") def loginFunc(request): if (request.method=='POST'): username = request.POST.get('username','Not found') password = request.POST.get('password','No password') print(username, password) try: user = User.objects.get(username=username) print(user) user = authenticate(request, username=username, password=password) if (user is not None): print("Login successful") login(request, user) return redirect('/loginPage') else: print("Login failed") except: print('No user found') return render(request, template_name='loginPage.html') def signinPage(request): # if (request.method=='POST'): # username = request.POST.get('username','Not found') # email = request.POST.get('email','No email') # password = request.POST.get('password','No password') # print(username, email, password) # return redirect('/') form = UserCreationForm(request.POST or None) if (request.method=="POST"): if (form.is_valid()): user = form.save() login(request, user) return redirect('/') return render(request, template_name='signPage.html', context={'form':form}) def logoutFunc(request): logout(request) return redirect('/') def contact(request): if (request.method=='POST'): username = request.user.username description = request.POST.get('description', 'No description') contactObject = contactIssue.objects.create(username=username, description=description) contactObject.save() print("contact submitted … -
Django how to compare stored hash password and plain password
I'm new to Django and I created function to allow admin to create users accounts. I used a password generator + make_password() function to hash the password. Now it's sending the plain password to users email and storing it in the database hashed. now the user is able to login with the hashed password only. my view.py: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email, user_password=user_password).values() if user_details: request.session['logged_in'] = True request.session['user_email'] = user_details[0]["user_email"] request.session['u_id'] = user_details[0]["user_email"] request.session['user_name'] = user_details[0]["user_name"] request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') Any idea how to make the user login with the plain password and keep it hashed in … -
Changing modelformset labels
I have created a modelformset for voting on multiple subtitles. It looks like this: I want to change the "Vote:" label to the names of the different subtitles instead (so if the subtitles are A, B and C, A should be before the first field, B for the second field etc.). How can I change this? The modelformset is created in the views.py like this: VoteFormSet = modelformset_factory(YesNoVote, form=YesNoVotingForm, extra=3) YesNoVotingForm looks like this: class YesNoVotingForm(forms.ModelForm): class Meta: model = YesNoVote fields = ['vote',] widgets = { 'vote': forms.Select(attrs={"required": True}), } and this is the yesnovote model: class YesNoVote(models.Model): subtitle = models.CharField(max_length=128) vote = models.CharField(choices=choices, max_length=10) user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name="yesnovote_user", null=True) election = models.ForeignKey(YesNoElection, on_delete=models.CASCADE, related_name="yesnovote") def __str__(self): return f"{self.user} stemde {self.vote} bij {self.subtitle} (vallend onder {self.election})" and this is the html page: <form method="post"> {{ formset.management_data }} {% csrf_token %} {% for form in formset %} {{ form }} <br> {% endfor %} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> Let op: Je kunt je stem niet meer wijzigen. </form> -
fetch data from backend django and react
i'm trying to fetch data from my backend and i'm resiving this error "SyntaxError: Unexpected end of input" this my react app import './App.css'; import { useState, useEffect } from 'react'; function App() { const [articles, setArticles] = useState([]) useEffect(() => { fetch('http://127.0.0.1:8000/api/users/', { mode: 'no-cors', 'method':'GET', headers: { 'Content-Type':'application/json', 'Authorization':'token 2e8bfe0b7ff1716c0c255ac62adad9d9832e7173' } }) .then(resp => resp.json()) .then(resp => setArticles(resp)) .catch(error => console.log(error)) }, []) return ( <div className="App"> {articles.map(article => { return ( <h2>{article.first_name}</h2> ) })} </div> ) } export default App; -
Protection of Django Rest Framework API with AllowAny permission
I have a full-stack app and I am taking measures to protect the application from DDOS or bot attacks. All the sensitive data is protected by IsAuthenticated permission but there are still open APIs with public data with AllowAny permissions. I have so far added throttling and limited the request rate to 100 for both anonymous and authenticated users and on the frontend side I've added Captcha to protect the server from mass user registration, what are more ways to protect the server? REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("accounts.authentication.Authentication",), # "EXCEPTION_HANDLER": "accounts.custom_exception_handler.custom_exception_handler" 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/minute', 'user': '100/minute' } } -
How to check whether the database is closed in django
from django.db import connections from django.db.utils import OperationalError db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True In server I have not close the connection but unable to update the query it shows the db connection is closed. Is there any solution in django to check whether the database is closed -
how can I solve UNIQUE constraint failed: core_labor.id? I used shortuuid to generate uid?
from django.db import models from django.utils import timezone # Create your models here. class Labor(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=256) created_at =models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(auto_now=True) def __str__ (self): return f"Name: {self.name}" This is the serializers from rest_framework import serializers from ..models import Labor class LaborSerializer(serializers.ModelSerializer): class Meta: model = Labor fields = ['name'] This is the views from ..serializers.labor_serializers import LaborSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from ..models import Labor from django.utils import timezone from django.http import Http404 from rest_framework.permissions import IsAuthenticated from ..utils.utilities import generate_uuid generate_uid = generate_uuid() class LaborDetailViews(APIView): def get_labor(self, pk): try: return Labor.objects.filter(pk=pk) except Labor.DoesNotExist: raise Http404 def get(self, request, pk ): labor = self.get_labor(pk) serializer = LaborSerializer(labor ,many = True) return Response(serializer.data) def post(self, request): serializer = LaborSerializer(data = request.data) if serializer.is_valid(): Labor.objects.create(id = generate_uid, name = request.data['name'],modified_at = timezone.now()) labor = Labor.objects.filter(id= generate_uid).values() return Response ({"Message": "New Labor Status Added!", "Labor": labor, "Errors": serializer.errors}) I can't create new labor unless I reload the localhost server. When I use postman and try to add new labor(model) it throws me an error. which is that -
cart_total_amount showing 0 in django-shopping-cart
I have added cart.context_processor.cart_total_amount in settings.py But when i use it in the template it shows 0 I was expecting the total cart amount so want to know why the total cart amount is not showing up in {{cart_total_amount}} -
Django restarted (trigger file change) on every request when using runserver_plus
Django always detect file changes on every request on development mode. it was restarting even though i didn't make any change at all on the code. for a simple view this is not causing a problem. the process of rendering one page done before restart triggered. but if i have more complex logic in view, django restarted before the process of rendering a page completed. is any body know is this an expected behaviour? and why this is happened? how can i solve my problem? render a complex logic before django restarted. Is there are a way to disable that false positive trigger of file change? -
Try to make input file Not Required but it still Required in Django Python
Hi im still learning django and python, i made function to upload file, but i want the file is not required. heres my code: model.py class Ticket(models.Model): status = models.CharField(max_length=20, default="Pending") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) docfile = models.FileField(upload_to='attachments/file/%Y/%m/%d/%P', blank=True, null=True) views.py def new_ticket(request): form = TicketForm() if request.method == 'POST': form = TicketForm(request.POST, request.FILES) if form.is_valid() : form = form.save(commit=False) form.owner = request.user form.save() if form.docfile == 'docfile' : newdoc = TicketForm(docfile=request.FILES['docfile']) newdoc.save() return redirect('helpdesk:dashboard') documents = Ticket.objects.all() return render(request, 'helpdesk/new_ticket.html', {'form':form,'documents':documents}) forms.py class TicketForm(forms.ModelForm): status = forms.CharField(required=True) docfile = forms.FileField(required=False) class Meta: model = Ticket fields = ('status', 'docfile') new_ticket.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="status">Status</label> {% render_field form.status class="form-control"%} </div> <div class="form-group"> <label for="docfile">File Upload: </label> {% render_field form.docfile required=false class="form-control" %} </div> <hr> <input class="form-group button_main btn-lg" type="submit" value="Send" style="border: 0px;"></form> i already tried some solutions from this link : Django ModelChoice field is set to required=False but is still required in the browser Django Make ContentType Not Required Django form always shows error "This field is required" Django TextField always is required, despite blank=True,Null=True Django - Form template throws "This field is required" for Imagefield but the input field still … -
Vue-loader not recognizing template tag in a django + vue + tailwind SPA
I'm trying to set up a Django + GraphQL + Vue + Tailwindcss project on Windows 11 that would use static files generated by webpack but I'm getting the following 2 errors on vue files when trying to run npm run serve: ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??clonedRuleSet-14.use[1]!./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js??clonedRuleSet-14.use[2]!./node_modules/vue-style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js!./src/index.css) Module build failed (from ./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js): SyntaxError (1:4) C:\Users\deteu\Development\django\application\frontend\src\index.css Unknown word > 1 | // style-loader: Adds some css to the DOM by adding a <style> tag | ^ 2 | 3 | // load the styles @ ./src/index.css 4:14-324 15:3-20:5 16:22-332 @ ./src/main.js 9:0-21 ERROR in ./src/views/ProfileView.vue Module Error (from ./node_modules/vue-loader/dist/index.js): At least one <template> or <script> is required in a single file component. @ ./src/router.js 16:19-52 @ ./src/main.js 10:0-33 20:8-14 The second error is different on npm run build: ERROR Error: Build failed with errors. Error: Build failed with errors. at C:\Users\deteu\Development\django\application\frontend\node_modules\@vue\cli-service\lib\commands\build\index.js:207:23 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:148:8 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\HookWebpackError.js:68:3 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Cache.shutdown (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Cache.js:150:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1225:15 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Compiler.close (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1218:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:147:16 at finalCallback (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:441:32) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:458:13 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:33:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) …