Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead
I have 3 models: Order, orderTimelocation and timeInterval. Order has a relation one to many with orderTimelocation and this has a relation one to many with timeInterval: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation', null=True) class timeInterval(models.Model): start = models.DateTimeField() end = models.DateTimeField() order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE) I am using Writable nested serializers as the documentation suggests. class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order class orderTimelocationSerializer(serializers.ModelSerializer): time_interval = timeIntervalSerializer(many= True) class Meta: model = orderTimelocation fields = ('longitude', 'latitude', 'time_interval') def create(self, validated_data): time_intervals_data = validated_data.pop('time_interval') ordertimelocation = orderTimelocation.objects.create(**validated_data) for time_interval_data in time_intervals_data: orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data) return ordertimelocation class timeIntervalSerializer(serializers.ModelSerializer): class Meta: model = timeInterval fields = ['start', 'end'] The error is the following: Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line … -
unable to get data from django form
forms.py `class ScanForm(forms.Form): image = forms.ImageField() xml_file = forms.FileField() description = forms.CharField(max_length=500)` views.py `def home(request): form = ScanForm() if request.method == 'POST': form = ScanForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] xml_file = form.cleaned_data['xml_file'] description = form.cleaned_data['description'] return render(request,'app/home.html',{'form':form})` home.html `<form enctype="multipart/form-data" method = "POST"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Submit" class="btn btn-success btn-lg"/> </form>` only description is printed on the terminal values of image and xml_file i get is None or NoneType -
Loose Coupling in Django Templates
I am in a situation Really Confusing .. I Have Read alot about loose Coupling And Also i have read that Django is a loose coupled framework But in django tutorial and also in generic class based views like ListView The context which is going to send to template contains queryset or Model instances like : {'object' : Model.objects.get(id=2)} And use like this :{{ object.title }} Well title is a field in a Model and in this way the template system is going to know so much about model layer and with a change in model fields, the template must change to .. Well if django use this way in Its source code then im missing something... Can someone explain how this is not higg coupling ? And what kind of coding in django is loose coupling? -
create user remotely using built in django user model
I'm trying to figure out how to test the process of using the userviewset from the django quickstart guide to create a user account with postman. I'm assuming I have to make a post request to the "create" route, but postman says "this request doesn't have a body" so I have no idea how to send the email, username, and password. I feel like I'm missing something pretty major here, but I have no idea how to find out what it is. -
How to display an input like stackoverflow answer box
I'm working on a Django chat app and I want a <textarea> or <input type="text"> with the markdown format, like this own input, that I can format code, put images, etc. -
django docker postgres issue: password authentication failed
I might be the n person to ask this question but i am sorry because now i spent 5 hours on it and still has not solve it Everything was working great in my django project until i messed around with multi user setup...thats another now postgres is giving me a hard time to work while using docker-compose .env file POSTGRES_NAME=somedb POSTGRES_USER=someuser POSTGRES_PASSWORD=somepassword django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("POSTGRES_NAME"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': '5432', } } docker-compose version: "3.9" services: backend: build: ./backend container_name: backend stdin_open: true tty: true restart: "on-failure" env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - "backend_network" db: image: postgres container_name: db restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - "backend_network" networks: backend_network: driver: bridge volumes: postgres_data: when i spin up the containers with docker-compose -d --build and check the logs with docker-compose logs, here is what i see backend | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend | return func(*args, **kwargs) backend | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect backend | self.connection = self.get_new_connection(conn_params) backend | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend | … -
Getting Error im Django "Exception Value:name 'order_id' is not defined" whne query with a view to List Child records
Getting Error im Django "Exception Value:name 'order_id' is not defined" whne query with a view to List Child records I am making a custom View of a Cart that is Editable where I can still add/Update OrderItems. Problem is the View is showing all OrderItems from all Orders. No matter how I try to Filter the results I get an Error "name "xxxxxxx" is not Defined The View works but list all Child Records I cant format this in view def get_context_data(self, **kwargs): # used to send additional context context = super().get_context_data(**kwargs) context["title"] = 'Edit Sizing' context["savebtn"] = 'Update Sizing' context["delbtn"] = 'Delete Sizing' # data = cartData(request) # cartItems = data['cartItems'] **items = OrderItem.objects.filter(orderitem__in=order_id)** # items = OrderItem.objects.filter(order=order) orders = Order.objects.filter(orderitem__in=items) # items = OrderItem.objects.all() context = {'items': items, 'orders': orders} return context Error in Browser NameError at /sizing/1/edit name 'order_id' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/sizing/1/edit Django Version: 3.2.4 Exception Type: NameError Exception Value: name 'order_id' is not defined Exception Location: C:\Users\LS\source\repos\esstools17\esstools\store\views.py, line 58, in get_context_data Python Executable: C:\Users\LS\source\repos\esstools17\env\Scripts\python.exe Python Version: 3.9.3 Python Path: ['C:\\Users\\LS\\source\\repos\\esstools17\\esstools', 'c:\\python39\\python39.zip', 'c:\\python39\\DLLs', 'c:\\python39\\lib', 'c:\\python39', 'C:\\Users\\LS\\source\\repos\\esstools17\\env', 'C:\\Users\\LS\\source\\repos\\esstools17\\env\\lib\\site-packages'] Server time: Thu, 22 Jul 2021 23:41:03 +0000 Traceback Switch to copy-and-paste view Models.py … -
Django and Powershell
:) I'm having a problem with two things: I'm unable to run PowerShell script from views.py I cannot find a way to send JSON data via POST First problem I've written a dummy python script that's going to call PowerShell script. getaduser.py import subprocess import json def run_powershell_script(ID, Domain): args = ['-SAMACCOUNTNAME', ID, '-DOMAIN', Domain] result = subprocess.check_output([ 'powershell.exe', '.\\getaduser.ps1', *args ]) return json.loads(result) getaduser.ps1 Param( [Parameter(Mandatory)][string]$SAMACCOUNTNAME, [Parameter(Mandatory)][string]$DOMAIN ) $result = [PSCustomObject]@{ samAccountName = $SAMACCOUNTNAME domain = $DOMAIN } return $result | ConvertTo-Json PowerShell script is now only returning what I passed to it, but in the future, it'll take data from Active Directory, also I don't think it's important now. getaduser.py and getaduser.ps1 are working just fine together when I use them off Django. Example of what I'm getting after running the getaduser.py: Path/getaduser.py {'samAccountName': 'exampleID', 'domain': 'exampleDomain'} But when I try to call the script from the views.py I'm getting an error message saying: Command '['powershell.exe', '.\\getaduser.ps1', '-SAMACCOUNTNAME', 'exampleID', '-DOMAIN', 'exampleDomain']' returned non-zero exit status 1. From what I already understood it might mean that the PowerShell script has not been executed properly, but I'm at loss since it's working without Django. And here's how I call it: … -
how to concatinate a date into a string Django
I'm quite new to DRF so sorry in advance. What I want to do is create a function to concatinate the letter "P", the ID value of another model and the year from a submitted date all into one to make a name. Now the value that I want to add this to is the value on the counter model. Any ideas would be appreciated. Here's the models class Order(models.Model): code = models.IntegerField code_year = models.IntegerField date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) def __str__(self): return str(self.code) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField class Counter(models.Model): name = models.CharField(max_length=10) value = models.IntegerField -
How to filter MongoDB collection from Django to find matching string in a list of strings?
Let's assume MongoDB collections has the following document: { _id: ObjectId('asdasd232344'), article: 'some name', type: 'latest', tags: ['books', 'cars', 'code'] },{ _id: ObjectId('asdasd232345'), article: 'some name', type: 'latest', tags: ['books', 'food'] },... Assuming the model is named Story, I am trying to query the articles that have type latest and 'cars', or 'books' and 'cars' tags. Want to do this in a query instead of looping over the result afterward and filtering the ones that have desired tags in them. news = Story.objects(type='latest'). ???? maybe something like find($in: {'books', 'tags'}) I cannot find what I am looking for online since not sure what is this called or how to search it. Thanks, community! -
NoReverseMatch: Reverse for 'edit' with keyword arguments '{'title': ''}' not found
This is the extention of the same problem i asked about in a previous question. The problem i'm having here now is that after fixing the problem with the trans views function and expecting the program to run without problems, i get the following error NoReverseMatch at /wiki/Python/edit Reverse for 'edit' with keyword arguments '{'title': ''}' not found. Which i can't for the life of me understand considering that i AM passing the title argument in the html and set up the edit views function and the urlpath in urls.py to expect the title argument. when i take a closer look at the traceback, it highlights this block of code from the edit views function. return render(request, "encyclopedia/edit.html", { "form": EntryForm(initial={ "title": title, "content": entry }) }) but i don't understand what the problem is here? this is the final part of the project i'm working on so i'll be very grateful for any and all help. below is the relevant code. HTML entry.html <!-- The edit button in the entry's page --> <form action="{% url 'wiki:trans' %}" method="POST"> {% csrf_token %} <input type=hidden value={{title}} name="title"> <input type=submit value="Edit"> </form> edit.html <!-- the edit page --> {% block body %} … -
Django Signals how to create notifications objects for sender and receiver both?
I am building an notification system for send notifications blog subscribers and bog author. I am using Django post_save signals which creating notifications objects. Is it possible to create two separate notification objects for my BlogCommnet model one for sender(blog commenter. Who commented in blog post) and another for receiver(author. Who created blog post). here is my code: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fields #here signals starting def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() post_save.connect(BlogComment.user_comment, sender=BlogComment) Right now it's creating only one notifications objects. see the picture: I want it will create two objects one for sender and another for receiver. is it possible ??? -
Django Get Value from dropdown where multiple options can be selected
This is my form. The user can select multiple options. I dont know how to pass the form data to my view. <form method="POST"> <div class="form-group" action="/"> <select class="mul-select" multiple="true" onchange="fun()"> <option value="Cambodia">Cambodia</option> <option value="Khmer">Khmer</option> <option value="Thiland">Thiland</option> <option value="Korea">Korea</option> <option value="China">China</option> <option value="English">English</option> <option value="USA">USA</option> </select> </div> <input type="submit" class="btn btn-secondary" value="Select"> </form> This is my view from .models import Countries def savedata(request): if request.method == 'POST': if request.POST.get('value'): saveresults = Countries() saveresults.country = request.POST.get('value') saveresults.save() return render(request, 'index.html') else: return render(request, 'index.html') My request.POST.get('value') is returning None. -
Django - Unique Collection of Foreign Keys Constraint
I have two models like so: class Group(...): pass class Identifier(...): value = models.CharField(...) group = models.ForeignKey('Group', ..., related_named = 'identifiers') How can I: restrict a Group to only have at most 4 Identifiers? Ensure that any combination of up to 4 Identifiers (the value of the identifier) is unique across all Groups? For part 2, here is an example of flattened Groups table: id | id__0__val | id__1__val | id__2__val | id__3__val -- | ---------- | ---------- | ---------- | ---------- 0 | abc | 123 | xyz | 456 1 | abc | 123 | xyz | - <-- valid (nulls are okay) 2 | 123 | abc | xyz | 456 <-- invalid (same combo as row 0) Previously I have tried (something like) this, but it seems messy, has limited functionality, and I'm not sure it will even work: class Group(...): id__0 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__1 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__2 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__3 = models.OneToOneField('Identifier', blank = True, null = True, ...) class Meta: unique_together = ('id__0__value', 'id__1__value', 'id__2__value', 'id__3__value') What is a better way to handle … -
File/Image field not submitting when using Ajax to submit Django form
I'm currently working on a customized admin page on my site where users will be allowed to update their profile page. I have several fields including an image field for profile images... I have then created a EditProfileForm to deal with this action. I've learned about serializing the form within the Ajax request to post the form data to server side. I have this working for other forms that doesn't have a file field, and it works perfectly. But somehow, it's just not working for this form with the image field. forms.py class EditProfileForm(forms.Form): avatar = forms.ImageField(widget=forms.ClearableFileInput(attrs=edit_profile_form_fields['avatar']), label='Change Profile Image') mobile = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['mobile']), label='Mobile Number', required=False) street = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['street']), label='Street', required=False) city = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['city']), label='City', required=False) state = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['state']), label='State', required=False) country = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['country']), label='Country', required=False) about = forms.CharField(widget=forms.Textarea(attrs=edit_profile_form_fields['about']), label='About Me', required=False) def clean_mobile(self): if Account.objects.filter(mobile=self.cleaned_data['mobile']).exists() and len(self.cleaned_data['mobile']) > 0: raise forms.ValidationError('Mobile already exists!') return self.cleaned_data['mobile'] def save(self, user_id): account = Account.objects.get(user_id=user_id) account.avatar = self.cleaned_data['avatar'] account.mobile = self.cleaned_data['mobile'] account.street = self.cleaned_data['street'] account.city = self.cleaned_data['city'] account.state = self.cleaned_data['state'] account.country = self.cleaned_data['country'] account.about = self.cleaned_data['about'] account.save() In my html I have... <form id="edit-profile-form" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="avatar"> {{ edit_profile_form.avatar.label }} </label> {{ edit_profile_form.avatar }} </div> <div class="form-group"> <label … -
Django createview with listview
I am new. I wish In my todo app uce createview and listview obe html, forexaple if i create task in createview then it which i create task title show bottom .helpphoto -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead
I'm new into django, and I have 3 models: Order, orderTimelocation, timeInterval. Order has a one to many relation with orderTimelocation,a and orderTimelocation has a one to many relation with timeInterval. class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_timelocation'), longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) class timeInterval(models.Model): start = models.DateTimeField() end = models.DateTimeField() order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE) I tried to follow the example given in django rest framework documentation on the topic Nested relationships: class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order class orderTimelocationSerializer(serializers.ModelSerializer): time_interval = timeIntervalSerializer(many= True) class Meta: model = orderTimelocation fields = ('longitude', 'latitude', 'time_interval') def create(self, validated_data): time_intervals_data = validated_data.pop('time_interval') ordertimelocation = orderTimelocation.objects.create(**validated_data) for time_interval_data in time_intervals_data: orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data) return ordertimelocation class timeIntervalSerializer(serializers.ModelSerializer): class Meta: model = time_interval fields = ['start', 'end'] But the following error occurs Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, … -
TinyMCE - Displaying Text Properly - Django
I'm using the TinyMCE text editor and have it successfully integrated into my Django Website. However when I go to display the TinyMCE document with the same styling, font, color, images, etc. it just displays the content as one single line of text. I use the |safe when I display my variable of the content in my HTML file but it only shows the color and font size it does not format it like it was with indents and spacing. I found a couple of solutions but I am saving it to my Django database so I am using the CONFIGURATION in my settings.py file instead of javascript with the HTML. I'm completely stuck and coming close to a dead-line so I could really use some help. Thanks! settings.py tinymce config TINYMCE_DEFAULT_CONFIG = { 'selector': 'textarea', 'theme': 'modern', 'plugins': 'link image preview codesample contextmenu table code lists print save autosave fullscreen spellchecker textcolor', 'toolbar1': 'formatselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify' '| bullist numlist | outdent indent | table | link image | preview', 'contextmenu': 'formats | link image', 'menubar': True, 'inline': False, 'statusbar': True, 'width': 740, 'height': 990, } HTML - display {{ … -
Different model field requirements for superuser vs normal user? django
Example(not true example): I want the superusers to have to save on register their username and email. and the normal users to save username, email, and a number(unique=True). I wanted to use the user models django has, but I don't see how when the number has to be unique? or rather I originally wanted it to be the primary key, but only for normal users. Do I have to manually make two different user classes along with the permissions, authentication etc.? or is there separate user models for admin/user in django? I tried(as a complete amateur, new to oop and django)... after gave up on using it as primary key, bc AbstractUser is fly. Tried with onetoonefield, but couldn't make a combined form with UserCreationForm, bc "too many fields error". Also weird to have an important part of the user table be in a different table (or is it?). something like (not 100% accurate): #in models.py class AdminUser(AbstractUser): username email class NormalUser(): ontoonefield(AdminUser) number(unique=True) #in forms.py class NormalUserForm(UserCreationForm): class meta: fields class onetoonefieldForm(NormalUserForm): class meta: add_field += (number) tried playing with required_fields, but again... number is unique tried making two abstractUsers... permissions errors thought about just making it non-unique and … -
why doesn't my function launch after calling it in django
I am trying to launch a script when I click on an html button with django, I get what's have been entered in the input when I click on the button but the rest of the script in my function doesn't run although when tried alone in a py file it works normally So I got here index.html : <form action='/' method="get"> {% csrf_token %} <input type="text" class="input" name="result" placeholder="Search..."> <button class="btn" type="submit"> <i class="fas fa-search"></i> </button> views.py def play(request): inp_value = request.GET.get('result', '') context = {'inp_value': inp_value} print(context) chpath = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s' webbrowser.get(chpath).open('google.com') urls.py urlpatterns = [ path('', views.home, name="home"), path('/', views.play, name="play") ] So when I click on the button search, only the url change as for example : http://127.0.0.1:8000/?csrfmiddlewaretoken=xYQaShcfX3apwjaOTeYvNsiXV4qXZoG3W4K5yP582IKAljAE1o0clnCagpVW3MPT&result=hey If someone could give me a hand I would be really grateful I am not able to find why Thanks -
Run python through frontend request using Django and Docker
I need to build a website that has a form in it. This form will get info that will further be submitted to a backend python file. This python file is very heavy, it will run with the given input, and when it is done, there should be returned the output to the website. The goal is to use django and 2 docker containers but I dont know how to use them, and I have never worked with RPC requests before. I know how to build static HTML sites, and I know python. But for this project I need some help. Anyone can tell me how I should do this? I have a scheme: Goal architecture -
Why is django-select2 ModelSelect2Widget widget not retreiving results
I am using django-select2 to represent the Department (ForeignKey) in a Model form. I followed the documentation to install the django-select2, including placing the {{ form.media.js }} and {{ form.media.css }} tags, but for some reason the select2 widget is not retreiving any result. I checked the browser console log and is showing the following error: jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 Here is the definition of the form class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'surname1' : forms.TextInput(attrs={'class': 'form-control'}), 'surname2' : forms.TextInput(attrs={'class': 'form-control'}), 'identification':forms.TextInput(attrs={'class': 'form-control'}), 'birthday_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}), 'type' :forms.Select(attrs={'class': 'form-control'}), 'department' : ModelSelect2Widget(model=DepartmentModel, queryset=DepartmentModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;','data-placeholder':'Seleccionar'}), 'is_social_service': forms.CheckboxInput(attrs={'class': 'form-control i-checks'}), } And this is the full console log jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</HidePlaceholder.prototype.append@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4199:25 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Results.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:1098:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerEvents/</<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5670:14 request/$request<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3637:17 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 done@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9796:14 callback/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10057:17 EventHandlerNonNullsend@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10076:18 ajax@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9690:15 transport@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3582:26 request@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3624:30 S2</</AjaxAdapter.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3661:7 S2</</MinimumInputLength.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3937:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._registerEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5669:24 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerDropdownEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5629:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:649:12 S2</</Search.prototype.handleSearch@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4174:12 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Search.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4120:12 dispatch@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5430:27 add/elemData.handle@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5234:28 EventListener.handleEventadd@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5282:12 on/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5182:16 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5181:14 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5906:10 S2</</Search.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4114:18 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</CloseOnSelect.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4682:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</AttachBody.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4338:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._bindAdapters@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5536:19 Select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5418:10 S2</</$.fn.select2/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6762:26 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 S2</</$.fn.select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6759:14 initHeavy@http://127.0.0.1:8000/static/django_select2/django_select2.js:48:14 $.fn.djangoSelect2/<@http://127.0.0.1:8000/static/django_select2/django_select2.js:56:18 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 $.fn.djangoSelect2@http://127.0.0.1:8000/static/django_select2/django_select2.js:53:7 @http://127.0.0.1:8000/static/django_select2/django_select2.js:71:26 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 … -
Will a SSG get me better SEO, than standard server side rendering? (Django)
I am just about to make my website and I will build it with either Gatsby (React SSG) or Django. SEO and the price of the hosting are the two most important deciding factors to me. I would love to build it with Django because overall I am more experienced in it than Gatsby and I might later add things like Stripe payments, client login,... But as SEO is very important to me, I can't decide between Django and Gatsby. Is the difference in SEO significant? Thank you very much. -
Update QuerySet by attribute variable
Take for example my data below where prop is the queryset I am trying to update, and results is a dict of information. This dict has keys that are attributes in this queryset, and also has keys that are not attributes in this queryset. I only want to update this queryset if it's attribute matches... prop = Property.objects.get(pk=14) results = {'price': '525000', 'code': '55285', 'estimate': '1500'} I know this does not work as it calls for an attribute literally named 'apicall' but this is the logic that I am looking to achieve: for apicall in results: if hasattr(prop,apicall): prop.apicall = results[apicall] prop.save() How can I avoid calling literally prop.apicall and instead prop.price if it exists in the queryset? -
how to return alert message instead of HttpResponse in models.PROTECT django
i'm trying to prevent user from removing an object if it has been used as a FK class MainGroup(models.Model): name = models.CharField(max_length=30,unique=True) class Parts(models.Model): main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) my views.py def delete_maingroup(request,id): try: object = get_object_or_404(MainGroup,id=id) object.delete() messages.success(request,'deleted') return redirect('products:maingroup') except: messages.info(request,'you cant delete it , sorry!') but it expects to return HttpResponse in the exception !? is it possible please , to show the error message instead of HttpResponse !