Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
QuerSet object has no attribute
i am trying to create a "Kriskras" that has a list of activities behind it. so i used a foreign key to link them. but every time i am trying to add something to the list i get the error enter image description here this is my model enter image description here how can i solve it so i can use the vergadering_set attribute? -
Django Serializer takes too much time to query
I have an API which is currently returning just returning 465 KB data but taking too long to process: Here's an image of postman: There are just 300 objects in the query and the views and serializers are like the following: Views.py class MaterialRequestListEmployeeAPIView(generics.ListAPIView): serializer_class = EMaterialRequestListSerializer permission_classes = (permissions.IsAuthenticated,) queryset = MaterialRequest.objects.all().order_by('-id') def get_queryset(self): queryset = super(MaterialRequestListEmployeeAPIView, self).get_queryset() return queryset Serializer.py class EMaterialRequestFlowsListSerializer(serializers.ModelSerializer): class Meta: model = MaterialRequestFlow fields = "__all__" depth = 1 class EMaterialRequestListSerializer(serializers.ModelSerializer): flows = EMaterialRequestFlowsListSerializer(many=True) class Meta: model = MaterialRequest fields = "__all__" depth = 1 Models.py class MaterialRequestFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) class MaterialRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') flows = models.ManyToManyField(MaterialRequestFlow) is_allocated = models.BooleanField(default=False) delivery_required_on = models.DateTimeField(default=datetime.now) raised_by = models.CharField(max_length=1000, default="__________", blank=True, null=True) How can I increase the performance of the API? I tried increasing the instance configuration on AWS but it had no effect on the retrieval time -
AttributeError at when I add entries in admin for Season , This Error comes 'Season' object has no attribute 'tv_show_publish'
Theres alot of same type of questions but Im blank now how to create this model without this error. I want to create a tree like model, Imagine a Netflix like Tv show has multiple seasons and their multiple episodes. For each episode I want to store some links to play that episode. Model Pattern Should be Like this ; OneTv_Show > Multiple Season > Each Season with multiple Episodes Lets take a look #models.py class Tv_Show_PublishedManager(models.Manager): def get_queryset(self): return super(Tv_Show_PublishedManager, self).get_queryset().filter(status='published') class Season_PublishedManager(models.Manager): def get_queryset(self): return super(Season_PublishedManager, self).get_queryset().filter(status='published') class Episode_PublishedManager(models.Manager): def get_queryset(self): return super(Episode_PublishedManager, self).get_queryset().filter(status='published') class Tv_Show(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) tv_show_name = models.CharField(max_length=250) tv_show_slug = models.SlugField(max_length=250, unique_for_date='tv_show_publish') tv_show_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tv_shows') tv_show_cover = models.ImageField(upload_to='upload/', null=True) tv_show_body = models.TextField() tv_show_imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) tv_show_publish = models.DateTimeField(default=timezone.now) tv_show_created = models.DateTimeField(auto_now_add=True) tv_show_updated = models.DateTimeField(auto_now=True) tv_show_views = models.IntegerField(default=0) tv_show_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-tv_show_publish',) def __str__(self): return self.tv_show_name objects = models.Manager() published = Tv_Show_PublishedManager() tags = TaggableManager() class Season(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) number = models.ForeignKey(Tv_Show, on_delete=models.CASCADE, related_name='season') season_slug = models.SlugField(max_length=250, unique_for_date='tv_show_publish') season_publish = models.DateTimeField(default=timezone.now) season_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') season_views = models.IntegerField(default=0) class Meta: ordering = ('-season_publish',) … -
How to solve non_field_errors error concerning unique_together relationship
Having my class Plug class Plug(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) station = models.ForeignKey(Station, related_name="plugs", on_delete=models.CASCADE) ocpp_name = models.CharField(max_length=50, null=True, blank=True) I defined a unique_together relationship as below in the Plug model : class Meta: unique_together = ('station', 'ocpp_name',) The strange thing is that every time I try to create a new plug instance in a specific station given the ocpp_name I got the error attached in the screenshot. The stack trace raises no error, just a 400 Error response How can i solve that? Is that related with the serializer of the Plug model? -
django model Form data not getting saved to database
I am trying to save form data to DB but it is not getting saved. I am not getting any errors as well. Here is my form.py: def create_lead(request): form = LeadForm() if request.method == 'POST': form = LeadForm(request.POST) print(form.data) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] country = form.cleaned_data['country'] email = form.cleaned_data['email'] status = form.cleaned_data['status'] agent = form.cleaned_data['agent'] avatar = form.cleaned_data['avatar'] lead = Lead( first_name=first_name, last_name=last_name, age=age, city=city, country=country, email=email, status=status, agent=agent, avatar=avatar ) lead.save() return redirect('/all') return render(request, 'create.html', {'form': LeadForm}) I even tried to create a model directly as mentioned here: HTML form data not saved in database - django but it did not help. def create_lead(request): form = LeadForm() if request.method == 'POST': form = LeadForm(request.POST) print(form.data) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] country = form.cleaned_data['country'] email = form.cleaned_data['email'] status = form.cleaned_data['status'] agent = form.cleaned_data['agent'] avatar = form.cleaned_data['avatar'] Lead.objects.create( first_name=first_name, last_name=last_name, age=age, city=city, country=country, email=email, status=status, agent=agent, avatar=avatar ) return redirect('/all') return render(request, 'create.html', {'form': LeadForm}) Here is my forms.py: class LeadForm(forms.ModelForm): class Meta: model = Lead fields = '__all__' Here is the model: class Lead(models.Model): lead_status = ( ('Potential', 'Potential'), … -
Django text search with partial sentence match update to python 3.9
I am trying to apply partial search in Django postgres, exactly the same as described here django-text-search-with-partial-sentence-match I found there a pretty nice solution from psycopg2.extensions import adapt from django.contrib.postgres.search import SearchQuery class PrefixedPhraseQuery(SearchQuery): """ Alter the tsquery executed by SearchQuery """ def as_sql(self, compiler, connection): # Or <-> available in Postgres 9.6 value = adapt('%s:*' % ' & '.join(self.value.split())) if self.config: config_sql, config_params = compiler.compile(self.config) template = 'to_tsquery({}::regconfig, {})'\ .format(config_sql, value) params = config_params else: template = 'to_tsquery({})'\ .format(value) params = [] if self.invert: template = '!!({})'.format(template) return template, params It works fine for python 3.6 but does not work for 3.9. The difference is, than in 3.6 SearchQuery inherits from Value: class SearchQuery(SearchQueryCombinable, Value): output_field = SearchQueryField() SEARCH_TYPES = { 'plain': 'plainto_tsquery', 'phrase': 'phraseto_tsquery', 'raw': 'to_tsquery', } def __init__(self, value, output_field=None, *, config=None, invert=False, search_type='plain'): self.config = config self.invert = invert if search_type not in self.SEARCH_TYPES: raise ValueError("Unknown search_type argument '%s'." % search_type) self.search_type = search_type super().__init__(value, output_field=output_field) and in python 3.9 SearchQuery inherits from Func: class SearchQuery(SearchQueryCombinable, Func): output_field = SearchQueryField() SEARCH_TYPES = { 'plain': 'plainto_tsquery', 'phrase': 'phraseto_tsquery', 'raw': 'to_tsquery', 'websearch': 'websearch_to_tsquery', } def __init__(self, value, output_field=None, *, config=None, invert=False, search_type='plain'): self.function = self.SEARCH_TYPES.get(search_type) if self.function is … -
Django Login Says Invalid Password Even For Correct Login Credential even though the login works for Django Admin
I created a custom user for my django project using django 3.1 and python 3.8. Apparently, the login system keeps saying incorrect password yet it works if i log in using admin site. My Installed Apps are INSTALLED_APPS = [ "users.apps.UsersConfig", "country.apps.CountryConfig", "clients.apps.ClientsConfig", # "customers.apps.CustomersConfig", "agents.apps.AgentsConfig", "products.apps.ProductsConfig", "quotes.apps.QuotesConfig", "providers.apps.ProvidersConfig", # 'countries', "banks.apps.BanksConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "vidabot.apps.VidabotConfig", "crispy_forms" ] I also created a custom user model and a custom usermanager as shown below: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.base_user import BaseUserManager from django.conf import settings from PIL import Image from phonenumber_field.modelfields import PhoneNumberField class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_("The Email must be set")) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ 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 … -
TypeError at /doLogin authenticate() missing 1 required positional argument: 'request'
that is the error I get when I tried to log in I don't really know if something is missing in my login code please help me review this code this is my views.py import datetime from django.contrib.auth import authenticate, login, logout from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from student_management_app.EmailBackEnd import EmailBackEnd # Create your views here. def showDemoPage(request): return render(request, "demo.html") def ShowLoginPage(request): return render(request, "login_page.html") def doLogin(request): if request.method!="POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user=EmailBackEnd.authenticate(request,username=request.POST.get("email"),password=request.POST.get("password")) if user!=None: login(request,user) return HttpResponse("Email : "+request.POST.get("email")+ "password :"+request.POST.get("password")) else: return HttpResponse("Invalid Login") def GetUserDetails(request): if request.user!=None: return HttpResponse("User :"+request.user.email+" usertype : "+request.user.user_type) else: return HttpResponse("Please Login First") def logout_user(request): logout(request) return HttpResponseRedirect("/") Urls.py Code from django.contrib import admin from django.urls import path from django.conf.urls.static import static from student_management_app import views from student_management_system import settings urlpatterns = [ path('demo', views.showDemoPage), path('admin/', admin.site.urls), path('', views.ShowLoginPage), path('get_user_details', views.GetUserDetails), path('logout_user', views.logout_user), path('doLogin', views.doLogin) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) -
How to exclude a serialiser field from being used in an UpdateView in Django REST Framework
Hi everyone I have an issue, I have created a sign up using a Custom user model which inherits from AbstractBaseUser, when the user signs up all fields required are there to be full filled but when the user visits /my-account endpoint I want a field to not be there in the RetrieveUpdateDestroy View so that user cannot change that data any thoughts about this? -
How to tell browser that the form was wrong and do not save password
I have a website with a login form. My problem is that every time this form is submitted, chrome suggests to save the password, even if it's incorrect The form: <form method="POST" action="" id='sign-in'> {% csrf_token %} <div class="form-group inner-addon"> <input name="txt_login_username" type="text" class="form-control" placeholder="Username"> <i class="fa fa-user fa-lg fa-fw" aria-hidden="true"></i> </div> <div class="form-group inner-addon"> <input name="txt_login_pass" type="password" class="form-control" placeholder="Password"> <i class="fa fa-key fa-lg fa-fw" aria-hidden="true"></i> </div> {% for message in messages %} <p class='alert alert-danger'>{{ message }}</p> {% endfor %} <button type="submit" class="btn btn-primary" name="btn_login">Log In</button> </form> -
How to add the logged in user's username with django
I am building a basic blog site with Django. Here's my views.py (AddPostView should be the relevant class) : class HomeView(ListView): model = Post template_name = 'community.html' ordering = ['-id'] class ArticleDetailView(DetailView): model = Post template_name = 'articles_details.html' class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' #fields = '__all__' And here's my forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','author', 'body', 'image'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } And models.py: class Post(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255, null=True) #author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, blank=True, upload_to='images/qpics') def __str__(self): return self.title + ' - ' + self.author def get_absolute_url(self): return reverse('community') I do get that I have to remove the author from forms.py and change it accordingly into models.py and write a code in views.py but i can't find a working solution to my problem. Most of the answers online are for class based views and do not work for me. Little help will be appreciated. THANKS! -
time data '03/16/2021 5:06 PM' does not match format '%d/%m/%Y %I:%M %p'
I have a variable in my Django project named this_rmg_date. Now I am trying to reformat it (for saving it in my database's DateTimeField) print(this_rmg_date) this_rmg_date = datetime.strptime(this_rmg_date, "%d/%m/%Y %I:%M %p") Here the print(this_rmg_date) print the value in console, and it is: 03/16/2021 5:06 PM but an error occers with the next line, it says: ValueError at /input_industryinfo/ time data '03/16/2021 5:06 PM' does not match format '%d/%m/%Y %I:%M %p' Yesterday, I did almost the same kind of code and that was working perfectly, other parts of my code are like this: stackOverflow-link. How can I fix this problem? -
Validate file existence
Django 3.1.5 class PhpFile(models.Model): subdir = models.CharField(max_length=255, null=False, blank=False, unique=True, verbose_name="Subdir") file = models.FileField(upload_to=php_upload_to, verbose_name="PHP file",) class ReadonlyFiledsForExistingObjectsMixin(): """ Disable a field "subdir" when modifying an object, but make it required when adding new object. """ def get_readonly_fields(self, request, obj=None): if obj: # editing an existing object return self.readonly_fields + ('subdir',) return self.readonly_fields @admin.register(PhpFile) class PhpFileAdmin(ReadonlyFiledsForExistingObjectsMixin, admin.ModelAdmin): form = PhpFileForm exclude = [] class PhpFileForm(ModelForm): def clean_file(self, *args, **kwargs): if "file" in self.changed_data: uploading_file = self.cleaned_data['file'].name subdir = self.cleaned_data['subdir'] upload_to = get_upload_to(subdir, uploading_file, FILE_TYPES.PHP) file = os.path.join(MEDIA_ROOT, upload_to) if os.path.isfile(file): raise ValidationError( "File already exists. Change its version or don't upload it.") return self.cleaned_data['file'] # File doesn't exist. I want files to be concentrated in subdirs. So, a model contains a subdir field. And I want to check if a file has already been uploaded. If it has been, I raise validation error. This code works only if I don't use ReadonlyFiledsForExistingObjectsMixin. If I uncomment it, subdir is not visible in the cleaned_data. Could you help me organize both: Readonly subdir field for existing objects. Validation for existence of a file with such a name. -
Django cut and put only the face in the picture field using opencv
This is the first question Django cut and put only the face in the picture field using opencv2 I have some problems First. It works even when I update it, so the picture gets weird. Second. The image size is weird because 'ProcessedImageField' works first and 'FaceCropped' works later. here we go my codes class Student(models.Model): picture = ProcessedImageField( verbose_name = 'pictures', upload_to = 'students/%Y/', processors=[ResizeToFill(300,300)], options={'quality':80}, format='JPEG', null=True, blank=True, default='students/no-img.jpg', ) def save(self, *args, **kwargs): super().save(*args, **kwargs) FaceCropped(self.picture.path) def FaceCropped(full_path): base_dir = os.path.dirname(os.path.abspath(__file__)) file_list = os.listdir('student') for i in file_list: if i == 'haarcascade_frontalface_default.xml': face_cascade_path = os.path.join(base_dir, i) face_cascade = cv2.CascadeClassifier(face_cascade_path) full_path = full_path path,file = os.path.split(full_path) ff = np.fromfile(full_path, np.uint8) img = cv2.imdecode(ff, cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3,5) for (x,y,w,h) in faces: cropped = img[y - int(h/4):y + h + int(h/4), x - int(w/4):x + w + int(w/4)] result, encoded_img = cv2.imencode(full_path, cropped) if result: with open(full_path, mode='w+b') as f: encoded_img.tofile(f) break; What i want to is When 'FaceCropped' works, only when i create a new model. So that it doesn't work when i update the model. plz help me up -
Sort a queryset by related model field and some operations
I have 3 models as follows: class Topic(models.Model): title = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) class Thread(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) description = models.TextField() created = models.DateTimeField(auto_now_add=True) class Message(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to get: 1- most active topics in this week by number of new messages 2- most active topics by most recent messages Note: I have solved this challenge by getting the QuerySet and sorting it with python code. I want to know if there is a way to do the same with django ORM. -
How to solve Value Error assign error in Django?
I am creating a system with Django. I create a system for limiting. I have several company, and every company has to create their own limit criteria. I think I can use foreign key for that. What I mean is I want to take company name from user's company name. You can understand clearly from my models. But user should not see comp_name field in their page, it should only be seen from the admin page (kind of a hidden field in frontpage. I tried a model for what I want but I get an error: ValueError at /add/limit Cannot assign "'Test 1'": "DoaTable.comp_name" must be a "CompanyProfile" instance. how can I solve it? views. py def create_doa_table(request): form_class = DoaTableForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) companyName = userP[0].comp_name # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = DoaTableForm(request.POST) # Check if the form is valid: if form.is_valid(): newDoaElement = form.save() newDoaElement.comp_name = companyName newDoaElement.save() # redirect to a new URL: return render(request, 'doa_table.html') else: form = form_class() return render(request, 'add_doa_element.html', {'form': form}) models.py class DoaTable(models.Model): … -
Set href dynamically
{% for stg in statusUrl %} <tr> <td>{{forloop.counter}}</td> <td>{{stg.title}}</td> <td> <a href="{% url {{stg.addLink}} %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> <a href="{% url {{stg.editLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url {{stg.deleteLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url {{stg.previewLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> </td> </tr> {% endfor %} Trying to set href to dynamically passed urls from the views. How can href be adjusted to render a hyperlink to the path in urls.py. -
Setting href to dynamic view name
{% for stg in statusUrl %} <tr> <td>{{forloop.counter}}</td> <td>{{stg.title}}</td> <td> <a href="{% url {{stg.addLink}} %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> <a href="{% url {{stg.editLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url {{stg.deleteLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url {{stg.previewLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> </td> </tr> {% endfor %} Trying to pass urls.py view names dynamically to template and then creating hyperlink to each view. How can href be adjusted to handle it. -
The record cannot be inserted into the database after adding a record on the admin panel in django
models.py from django.db import models class NewsUnit(models.Model): catego = models.CharField(max_length=10,null=False) nickname = models.CharField(max_length=20,null=False) title = models.CharField(max_length=50,null=False) message = models.TextField(null=False) pubtime = models.DateTimeField(auto_now=True) enabled = models.BooleanField(default=False) press = models.IntegerField(default=0) def __str__(self): return self.title views.py from django.shortcuts import render from newsapp import models import math # Create your views here. page1 = 1 def index(request,pageindex=None): global page1 pagesize = 8 newsall = models.NewsUnit.objects.all().order_by('-id') datasize = len(newsall) totpage = math.ceil(datasize/pagesize) if pageindex == None: page1 = 1 newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[:pagesize] elif pageindex == '1': start = (page1-2)*pagesize if start >= 0: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] page1 -= 1 elif pageindex == '2': start = page1*pagesize if start < datasize: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] page1 += 1 elif pageindex == '3': start = (page1-1)*pagesize if start < datasize: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] currentpage = page1 return render(request,'index.html',locals()) def detail(request, detailid=None): unit = models.NewsUnit.objects.get(id=detailid) category = unit.catego title = unit.title pubtime = unit.pubtime nickname = unit.nickname message = unit.message unit.press += 1 unit.save() return render(request, "detail.html", locals()) urls.py from django.contrib import admin from django.urls import path from newsapp import views urlpatterns = [ path('',views.index), path('index/<pageindex>/',views.index), path('detail/<detailid>/',views.detail), path('admin/', admin.site.urls), ] For this django project, I would like to insert the new record on the database list after adding a … -
invalid literal for int() with base 10: 'undefined'
I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I tried to edit record with actual id I got this error: invalid literal for int() with base 10: 'undefined'. I made a research but can't really find something helpful in my case. my edit function in views.py: def staff_edit(request, id=0): #employees = Employee.objects.all() #print(employees) if request.method == 'GET': if id == 0: form = EmployeeEditForm() else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(instance=employees) return render(request, 'staffedit.html', {'form': form}) else: if id == 0: form = EmployeeEditForm(request.POST) else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(request.POST, instance=employees) if form.is_valid(): form.save() return redirect('feedback:index_employees') context = {'form': form} #when the form is invalid return render(request, 'staffedit.html', context) this is my model.py for Employee: class Employee(models.Model): coreapiemployee_id = models.CharField(max_length=100) webflow_id_employee = models.CharField(max_length=100, default=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, default=True) email = models.EmailField(max_length=100) user_type = models.CharField(max_length=100) status = models.CharField(max_length=100, default=True) roles = models.ManyToManyField('Role', through='EmployeeRole') def __str__(self): return self.coreapiemployee_id + " " + self.email + self.first_name + self.last_name this is my general html staff.html: $(document).ready(function() { var data; fetch("http://192.168.2.85:8000/displayEmployeesToFroentend/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); let … -
ValueError: Related model 'auth.Group' cannot be resolved when running django test
I am new to Django REST Api testing and I am running an error like this raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'auth.Group' cannot be resolved when running an error, and im not sure this happen -
Multiple instance jquery function with bootstrap modal
I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running. <script type="text/javascript"> $(document).ready(function () { $(".test").click(function () { var cid = $(this).attr('cid'); $("#post-form").one('submit',function (event){ event.preventDefault(); $.ajax({ url: '{% url 'create_request' %}', type: 'POST', data: { 'cid': cid, 'req_num' : $('#request_number').val(), }, success: function (data) { console.log("success") if (data['request']=='0') { alert("Request is already there"); } else if(data['request']=='1') { alert("Not enough components:("); } $("#exampleModal").modal('hide'); } }) }) }) }) </script> -
How to fix OS error at '/' Invalid Argument?
I have a django application that converts excel to csv files. This works fine but for larger files,it shows OSError at /conversion/ [Errno 22] Invalid argument: '<django.core.files.temp.TemporaryFile object at 0x000001C4C2C21A60>' I have successfully tested with converting smaller files but when I upload large files and try to process it, it shows the above error. views.py def conversion(request): excel_form = '' if request.method == 'POST': excel_form = ConversionForm(request.POST,request.FILES) if excel_form.is_valid(): excel_file = request.FILES['excel_file'].file df = pd.read_excel(excel_file) filename1 = excel_form.cleaned_data.get('excel_file').name filename1 = filename1.replace('.xlsx','') filename1 = filename1.replace('.xls','') df.to_csv(filename1 +'.csv',encoding='ascii',index=None, header=True) context = {'excel_form': excel_form, } return render(request,'colorlib-regform-6/convert_result.html',context) else: excel_form = ConversionForm() rontext = {'excel_form' : excel_form} return render(request,'colorlib-regform-6/convert_result.html',rontext) else: return render(request,'colorlib-regform-6/convert_result.html') -
Django Utils six for Django 3.1.5
I have a token generator that uses six from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() This runs on Django 2.2 but my boss told me to run this on latest 3.1.5. However, six was already depreciated. I also checked this SO suggestion https://stackoverflow.com/a/65620383/13933721 Saying to do pip install django-six then change from django.utils import six to import six I did the installation and changes to the code but it gives error message: ModuleNotFoundError: No module named 'six' I think I did something wrong or something is missing but I don't know how to proceed. Here is my pip freeze for reference asgiref==3.3.1 Django==3.1.5 django-six==1.0.4 djangorestframework==3.12.2 Pillow==8.1.0 pytz==2020.5 sqlparse==0.4.1 -
DjangoAdmin: How to get the Add/Edit/Del buttons for an `AutocompleteSelect` form field
I'm using the AutocompleteSelect widget for a ForeignKey field. To do this, you override the ModelForm class like so: class XForm(forms.ModelForm): ... x = forms.ModelChoiceField( queryset=X.objects.all(), widget=AutocompleteSelect(x.field.remote_field, admin.site) ) However, by using this widget I lose the + ✎ ✕ buttons that are available on the Django Admin interface for a Foreign Key field by default. What will be a good way to use AutoCompleteSelect widget but also keeping these Add/Edit/Delete buttons besides the foreign key field on the Admin UI?