Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /signup/ Cannot assign "<User: prosenjit>": "Referral.parent" must be a "Referral" instance
After reading a lot of answers similar to this problem I got a specific error in every single case. In the following, I have attached my mandatory code. Models.py import uuid import enum from django.db import models from django.utils import timezone, translation from django.conf import settings from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django_numerators.models import NumeratorMixin from mptt.models import MPTTModel, TreeForeignKey, TreeManager _ = translation.gettext_lazy from .utils import generate_ref_code class Referral(NumeratorMixin, MPTTModel, models.Model): class Meta: verbose_name = _('Referral') verbose_name_plural = _('Referral') unique_together = ('parent', 'account') limit = 3 parent = TreeForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='downlines', verbose_name=_('Up Line')) account = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, verbose_name=_('account')) balance = models.DecimalField( default=0, max_digits=15, decimal_places=2, editable=False, verbose_name=_("Balance")) created_at = models.DateTimeField( default=timezone.now, editable=False) code = models.CharField(max_length=12, blank=True) def __str__(self): return ( self.account.username if self.account.get_full_name() in ['', None] else self.account.get_full_name() ) def update_balance(self, balance): self.balance = balance self.save() def get_referral_limit(self): return getattr(settings, 'REFERRAL_DOWNLINE_LIMIT', None) or self.limit def get_uplines(self): return self.get_ancestors(include_self=False, ascending=True)[:self.get_referral_limit()] def save(self, *args, **kwargs): if self.code == "": code = generate_ref_code() self.code = code super().save(*args, **kwargs) utils.py import uuid import json from django.core.serializers.json import DjangoJSONEncoder from uuid import UUID import random def generate_ref_code(): code … -
Creating new SQLAlchemy project with possible future migration to Django in mind
I want to create a database with SQLAlchemy ORM. At this moment, no web server is needed, so this solution is ideal. However, it is likely, that in future, we will want to add some web server functionality (using Django). Are there any recommendations that I should do (when creating SQLAlchemy project) so that the possible migration to Django will be as easy as possible? (for example some naming conventions, using of multi column primary keys, and so on) I know that we can use Django with existing database, but my question is rather what are the steps I can do at the start of SQLAlchemy project to make the future transition easiest it can be. -
Django model: OperationalError: no such column: home_atliktas_darbas.bendrija_id, help fix, Django version 3.2
I am creating a model that is related to other one, meaning the model I am trying to create can't exist if the model its related to does not exist. now I am new to django (just a few months), but I have created models with the same concept and had no issues before, this is the first time this has happened and I have no idea what could be the cause this is the model its related to class Bendrija(models.Model): class Meta: verbose_name_plural = 'Bendrijos' name = models.CharField(max_length=254) address = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.name and this is the model I want to create class Atliktas_Darbas(models.Model): class Meta: verbose_name_plural = 'Atlikti Darbai' bendrija = models.ForeignKey(Bendrija, on_delete=models.CASCADE, related_name="atliktas_darbas") pavadinimas = models.CharField(max_length=254) aprasymas = models.CharField(max_length=254, null=True, blank=True) preliminari_kaina = models.CharField(max_length=254) galutine_kaina = models.CharField(max_length=254, null=True, blank=True) atlikti_iki = models.DateField() darbas_atlikas = models.DateField(null=True, blank=True) pastabos = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.pavadinimas first I thought I forgot to add "bendrija' (the model field) to list_display in admin.py and I was correct thinking that fixed it I thought I was done, but I was wrong, after that I tried a bunch of stuff, but nothing worked -
Popup window displayed wrongly
[tag: Hi All, I have added modal popup in my page. Popup was not coming correctly and unable to edit the popup screen as well. Pls see the attached image for more info I have a button, when user clicks it, it will show the popup <div class="mb-2 mb-sm-0"> <button type ="button" data-toggle="modal" data-target="#loginModal" class="btn px-4 btn-red mb-1"><i class="fa fa-upload"></i></button> </div> Modal code <!-- Login modal --> <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 360px;"> <div class="modal-content shadow border-none radius-2 px-3"> <div class="modal-header mt-n1 border-0 justify-content-center pos-rel"> <h3 class="modal-title text-white mt-n5 text-115" id="loginModalLabel"> Login to continue </h3> <button type="button" class="close position-br mb-n4" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body text-center py-0"> <h2 class="text-grey-d1 text-160"> <i class="fa fa-leaf text-success-m2 text-120 mr-1"></i> Test App </h2> <form autocomplete="off" class="form-row mt-45"> <div class="form-group col-12 mb-3"> <div class="d-flex align-items-center input-floating-label text-blue-m1 brc-blue-m2"> <input type="text" class="form-control pr-4 shadow-none radius-1" id="id-login-username" /> <i class="fa fa-user text-grey-m2 ml-n4"></i> <label class="floating-label text-grey-l1 text-95 ml-n3" for="id-login-username">Username</label> </div> </div> <div class="form-group col-12"> <div class="d-flex align-items-center input-floating-label text-blue-m1 brc-blue-m2"> <input type="password" class="form-control pr-4 shadow-none radius-1" id="id-login-password" /> <i class="fa fa-key text-grey-m2 ml-n4"></i> <label class="floating-label text-grey-l1 text-95 ml-n3" for="id-login-password">Password</label> </div> </div> <div class="form-group col-12"> <button type="button" … -
How to create a zip with multiple files from one folder and send it to the browser in modern Django
I was struggling with sending the downloadable Django zip with many files to browser, because many tutorials in the web are obsolete, like the one which was my inspiration to come up with what I will share with you: Django - Create A Zip of Multiple Files and Make It Downloadable -
'QueryDict' object has no attribute 'method'
So Im building a real estate website fro school. Im working on my CRUD functionality on the front end. When i try to post a new listing i get the error. 'QueryDict' object has no attribute 'method' I don't really know what the problem is. Any tips and i will be forever grateful. Also im new to this whole stack overflow thing, so please let me know if you need any more info from me. models.py from django.db import models from datetime import datetime from realtors.models import Realtor class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title forms.py from django.forms import ModelForm from listings.models import Listing class listingForm(ModelForm): class Meta: model = Listing fields = '__all__' views.py def createListing(request): form = listingForm() if request.method == 'POST': form = createListing(request.POST) if form.is_valid(): … -
User' object has no attribute 'make_password'
what is the error with set_password /base/backends.py in authenticate from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self,request,username=None,password=None,**Kwargs): UserModel=get_user_model() if username is None: username=Kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field='{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field:username}) except UserModel.DoesNotExist: UserModel().set_paassword(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user i try to put make_password but not working -
How to avoid username change through URL in django application
I am working on a basic django chat application where the user can login and then enter the room id to join a specific room where they can chat with other users. The room looks like this Chat login Now the problem is that if I change my username in URL to some other registered username then I am able to chat as if I am that user (By passing all the login). What changes I need to make to avoid this or the things that are to be added so that even if someone tries to attempt to change, it redirects it to the login page and after proper login only that person will be able to use that. I avoided the problem of accessing the unregistered user i.e. if someone enters the username that is not registered then he will not be able to chat with that username but it still is not redirecting them to login page. This code shows the above logic: def send(request): message = request.POST['message'] username = request.POST['username'] room_name = request.POST['room_name'] print("**********************************************************************") print(username) print(request) print("......................................................................") if(User.objects.filter(uname=username).exists()): #if(User.objects.filter(uname=username).is_authenticated) new_message = Message.objects.create(value=message, uname=username, rname=room_name) new_message.save() return HttpResponse('Message sent successfully') else: return redirect('/') Please suggest changes here … -
Django- How to replace list of items of a related set
I have table Group and UserConfig A group has many users, each user in a group has a config item UserConfig: unique (group_id, user_id) Example: class Group(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) class UserConfig(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='user_configs') user_id = models.IntegerField() config = models.JSONField() I want to replace all UserConfig instances of a group (update existing rows, add new rows and remove which rows are not in the new list) # list_replace_configs: List[UserConfig] group.user_configs.set(list_replace_configs, bulk=False, clear=False) This method not working because it uses method remove() remove(*objs, bulk=True): only exists if ForeignKey field has null=True if ForeignKey field has null=True: it does not removed UserConfig object, but just set user_config.group = None I don't understand why django designs this method. How to replace all UserConfig instances of a group ? -
Facing issue with django_admin_hstore_widget in production
at HTMLDocument.<anonymous> ((index):3024:36) at j (jquery.min.js:2:26911) at Object.fireWith [as resolveWith] (jquery.min.js:2:27724) at Function.ready (jquery.min.js:2:29518) at HTMLDocument.I (jquery.min.js:2:29709) This works fine in local server. -
Django get parameters deleted upon post request
On my page i have a users portfolio of items which they own. On this page 16 items can be displayed per page, so if the user has more than 16 items they will need to be able to navigate through pages 1,2,3, etc... To achieve this I use a form using the GET method which has two submit buttons, one for going back one page and another for going forward one page. The page number will be visible in the URL, http://127.0.0.1:8000/portfolio/?page=2 I also have a form using the POST method where a user can add items to their portfolio where they enter item_id, condition, quantity. My problem is when a user submits the POST form, the page number from the URL gets deleted and therefore puts the user back to page one as 1 is the default value in my get method in views.py. page = int(request.GET.get("page", 1)) How can i submit a POST form without deleting GET parameters from the URL and stay on the current page? portfolio.html <form action="{% url 'portfolio' %}" method="post"> <input type="hidden" name="form-type" value="add-item-form"> <!-- Inputs for name, condition, quantity --> <input type="submit" value="Add to Portfolio"> </form> <form action="{% url 'portfolio' %}" method="get"> … -
Django query to get frequency-per-day of events with a DateTimeField
I have a model with events that each have a DateTimeField and can readily write a query that gets me the count of events per day: MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')) which produces (Postgresql) SQL like: SELECT ("MyEvents"."date_time")::date AS "day", COUNT("MyEvents"."id") AS "count" FROM "Doors_visit" GROUP BY ("MyEvents"."date_time")::date which produces a QuerySet that returns dicts containing 'date' and 'count'. What I would like is to produce a histogram of such counts, by which I mean plotting hte 'count' as a category along the x-axis and the number of times we've seen that 'count' on the y-axis. In short, I want to aggregate the counts, or count the counts if you prefer. Alas, Django complains vehemently when I try: MyEvents.objects.annotate(day=TruncDate('date_time')).values('day').annotate(count=Count('id')).annotate(count_count=Count('count')) produces: django.core.exceptions.FieldError: Cannot compute Count('count'): 'count' is an aggregate Fair enough. Which raises the question, can this be done in one Django Query without resorting to Raw SQL? I mean in SQL it's easy enough to query the results of a query (subquerying). Django seems to lack the smarts for this (I mean, rather than complain it could just wrap the query to date as a subquery and build a query from there, but it elects not to). I mean, one work around is to … -
How to perform data validation from the DB and raise an nonFieldError in the form without saving using generic?
How best to perform data validation using Form_Class and CreateView. How to cause an error in the form and not lose the entered data. sing form_valid() or pre_save signal? HOW COULD IT BE USING DEF VIEW & RENDER if request.method == "POST": form = Buy_add_form(request.POST, instance=instance) if form.is_valid(): hasPrice = SellingPrice.objects.filter(item=form.instance.item, date=form.instance.date) if not hasPrice: form.save() return redirect("storage:index") else: form = Buy_add_form(instance=instance) return render(request, 'storage/add_flow.html', { 'form': form, }) I'm writing a small inventory application. Data on the price of each product should be recorded in the database no more than once a day. In this example, I'm trying to see if there is a record in the table for this product on the date specified in the form. If there is, I want to notify the user in the form and break the data saving process. I need to save the filled form data. MODELS.PY class SellingPrice(models.Model): date = models.DateField(blank=False) item = models.ForeignKey(Items, on_delete=models.PROTECT, blank=False) price = models.FloatField(blank=False) def __str__(self): return f"{self.date}_{self.item}_{self.price}" FORMS.PY class SetPrise_add_form(forms.ModelForm): date = forms.DateField(input_formats=['%d-%m-%Y'], initial=now().strftime('%d-%m-%Y'), widget=forms.DateInput(attrs={'data-mask': '00-00-0000'})) class Meta: model = SellingPrice fields = ["date", "item", "price"] VIEW.PY class setPrice(CreateView): form_class = SetPrise_add_form template_name = "storage/setPrise_create.html" success_url = reverse_lazy('storage:prices-view') def form_valid(self, form): last = SellingPrice.objects.filter(item=form.instance.item, … -
How to use getElementById in django
I'm trying to generate a code for editing posts using modal that are made before but it shows "Identifier or string literal or numeric literal expected" and "Statement expected" ERROR here is my code: ` function submitHandler(){ const textareaValue = document.getElementById("textarea_"${post.id}).value </script> <button type="button" class="btn btn-secondary"onclick=submitHandler({{post.id}}) > Save Changes</button> ` want to submit change to editing posts. -
how can i load another question from the database after i have clicked on a button
enter image description here I have a quiz game. After I click on the "Next" button (see picture), I want the next question to be loaded from the database. Only one question is currently displayed, but I don't know how to load more questions from the database. Summarized again: After clicking on the Next button, another question should be loaded from the database. I'm new to django, would be cool if someone could help me further views.py def quiz_math(request): if request.method == 'POST': questions = QuesModel.objects.filter(kategorie__exact="Math") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) print(answer) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'quiz_math.html', context) model.py class QuesModel(models.Model): Kategorie = ( ("Math", "Math"), ("Digital Skills", "Digital Skills"), ) kategorie = models.CharField(max_length=400, null=True, choices=Kategorie) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True,) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, … -
IntegrityError at /accounts/ProfileRegister/ UNIQUE constraint failed: auth_user.id
I am creating a registration page, and after finishing the work, I received this error, everything is saved, but the information is not displayed in the profile section. I am a beginner. Views def ProfileRegisterView(request): if request.method=='POST': profileRegisterForm=ProfileRegisterForm(request.POST,request.FILES) if profileRegisterForm.is_valid(): user=User.objects.create_user( username=profileRegisterForm.cleaned_data['username'], email=profileRegisterForm.cleaned_data['email'], password=profileRegisterForm.cleaned_data['password'], first_name=profileRegisterForm.cleaned_data['first_name'], last_name=profileRegisterForm.cleaned_data['last_name'],) user.save(profileRegisterForm) profileModel=ProfileModel(user=user, profileImage=profileRegisterForm.cleaned_data['profileImage'], Gender=profileRegisterForm.cleaned_data['Gender'], Credit=profileRegisterForm.cleaned_data['Credit']) profileModel.save() return HttpResponseRedirect(reverse(ticketsale.views.concertListView)) else: profileRegisterForm=ProfileRegisterForm() context={ "formData":profileRegisterForm } return render(request,"accounts/ProfileRegister.html",context) template {% extends 'ticketsale/layout.html' %} {%block titlepage%} ثبت نام {% endblock %} {%block mainContent%} <form action="" method="POST" class="form form-control bg-dark p-5" enctype="multipart/form-data"> {% csrf_token %} {% comment %} {{ Concertform }} {% endcomment %} <div class="container"> <div class="row"> <div class="col-md-6"> <p class="form form-control">نام: {{ formData.first_name }}</p> <p class="form form-control">نام خانوادگی: {{ formData.last_name }}</p> <p class="form form-control">جنسیت : {{ formData.Gender}}</p> <p class="form form-control">مقداراعتبار : {{ formData.Credit }}</p> </div> <div class="col-md-6"> <p class="form form-control">ایمیل: {{ formData.email }}</p> <p class="form form-control">نام کاربری: {{ formData.username }}</p> <p class="form form-control">رمز عبور: {{ formData.password }}</p> {{ formData.profileImage }} </div> </div> </div> <button type="submit" class="btn btn-info">ثبت نام</button> </form> {% endblock %} Models class ProfileModel(models.Model): class Meta: verbose_name="کاربر" verbose_name_plural="کاربر" user=models.OneToOneField(User,on_delete=models.CASCADE,verbose_name="کاربری",related_name="profile") # Name=models.CharField(max_length=100,verbose_name="نام") # Family=models.CharField(max_length=100,verbose_name="نام خانوادگی") profileImage=models.ImageField(upload_to="profileImage/",verbose_name="عکس") Man=1 Woman=2 status_chioces=((Man,"مرد"),(Woman,"زن")) Gender=models.IntegerField(choices=status_chioces,verbose_name="جنسیت") Credit=models.IntegerField(verbose_name="اعتبار",default=0) forms class ProfileRegisterForm(forms.ModelForm): first_name=forms.CharField(max_length=100) last_name=forms.CharField(max_length=100) username=forms.CharField(max_length=100) password=forms.CharField(widget=forms.PasswordInput) email=forms.CharField(widget=forms.EmailInput) class Meta: model=ProfileModel fields=['profileImage','Gender','Credit'] I expect that after … -
How to solve the error "could not install packages due to an OSError: [Errno 2] No such file or directory" after trying to install requirements.txt
After updating Python to the latest version, previous files were over-written and I was left with this error when trying to run: pip install -r requirements.txt Error: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot1/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/python3/python3-124/altgraph-0.17.2-py2.py3-none-any.whl' How would one go about solving or understanding the approach to fixing this issue? I am not quite sure where to begin, so any help would be really appreciated. I should be expecting the line to run without any errors and the web app should be able to run as well, but I encountered the previous error. When I ran: python manage.py runserver I encountered this error too: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
django-filters - field_labels not working for OrderingFilter
There is a model: class Calendar(models.Model): ... vendor_code = models.TextField() ... FilterSet class: from django_filters import OrderingFilter from django_filters.rest_framework import FilterSet, DjangoFilterBackend class CalendarFilter(FilterSet): ordering = OrderingFilter( fields=( ('vendor_code', 'vendor_code'), ), field_labels={ 'vendor_code': 'Vendor code', } ) class Meta: model = Calendar fields = ['vendor_code'] The view: class CalendarsView(mixins.ListModelMixin, GenericViewSet): ... filter_backends = (DjangoFilterBackend,) filterset_class = CalendarFilter I expected that if define field_labels param the label Vendor code would appear in swagger but there is only ordering without any description: What am I doing wrong? -
Trying to add a field to Django many-to-many relation
Right now I'm working on django project responsible for warehouse mangement system. I got product, customers, warehouse-branches, product type, orders, etc... products can be [Milk 1L bottle, cheese 500g pack, ....] The problem I been facing is that I'm trying to make a many-to-many relation between orders and products so I can track the products sold in each order. Yet, I want to add 'amount' coloumn to that table created by many-to-many because a customer can order 5 cheese packs and 2 milk bottles. I know that I can add 'ManyToManyField.through' but it takes string for a model as args and that's what i don't want. I wish to easily have extra IntegerField called amount. Here's how i wish my table to look-like enter image description here -
What are json.loads and json.dumps function doing?
class Realm(models.Model): server = models.ForeignKey(Server, related_name='realms', on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True, help_text='Name as known on the Keycloak server. ' 'This name is used in the API paths ' 'of this Realm.') _certs = models.TextField() @property def certs(self): return json.loads(self._certs) @certs.setter def certs(self, content): self._certs = json.dumps(content) I just wanted to know what is the (_) underscore is doing there and what is happing in this model with json.loads and json.dumps -
How to delete object using Django Inline Formset
I am having a trouble with deleting an object in inline formset. The formset is not saving if there are objects to be deleted, but it just works properly when there is not. Here is my views.py: def submission(request): if request.method == "POST": formset = AuthorFormSet(request.POST) form = thesisForm(request.POST, request.FILES) if form.is_valid() & formset.is_valid(): thesis = form.instance.thesis_id title = form.instance.title form.instance.uploaded_by = request.user # set the user thesis = form.save() # save the form for obj in formset.deleted_objects: obj.delete() for forms in formset: forms.instance.thesis = thesis forms.save() else: form = thesisForm() formset = AuthorFormSet() return render(request,'StudentSubmitProject.html',{'form':form, 'formset':formset,}) And this is my template: <form method="POST" class="mt-5 form-group profile_form" enctype="multipart/form-data"> {% csrf_token %} <h4 class="textmaroon mt-5">Describe the thesis</h4> <p>Define the thesis project</p> <hr></hr> {{form.as_p}} <h4 class="textmaroon mt-5">Add Author</h4> <p>Input the authors of the thesis</p> <hr></hr> {% for forms in formset %} <div class="d-flex flex-wrap justify-content-between">{{forms.as_p}}</div> <hr class="text-muted"></hr> {% endfor %} {{ formset.management_data }} <div class="row mt-5"> <hr></hr> <div class="col-md-12"> <button type="submit" class="btn btn-danger float-end">Submit</button> <button type="reset" class="btn btn-secondary me-2 float-end">Reset</button> </div> </div> </form> -
Django form with Jstree checkbox ( Jquery Array)
I try to use Jstree checkbox in a Django form, but Jquery array is stopped by form is_valid() method : La valeur « 584a6392-8958-40c8-b318-77c1d2df623d,a9f2deec-eda2-4c43-a080-cd070e9ff25f » n’est pas un UUID valide. This code run if i choose only a checkbox HTML <input type="hidden" name="regroupements" id="regroupements" value=""> <div id="kt_docs_jstree_basic"> <ul> <li value="584a6392-8958-40c8-b318-77c1d2df623d"> Groupe 1 </li> <li value="a9f2deec-eda2-4c43-a080-cd070e9ff25f"> Groupe 2 </li> </ul> </div> JS $(function () { $('#kt_docs_jstree_basic').jstree(); $("#kt_docs_jstree_basic").on("select_node.jstree", function(e){ var selected_regroupements = []; var selectedIndexes = $("#kt_docs_jstree_basic").jstree("get_selected", true); $.each(selectedIndexes,function () { selected_regroupements.push(this['li_attr'].value); }); $("#regroupements").val(selected_regroupements) } ); }); ViEWS.PY def post(self, request, **kwargs): context = super().get_context_data(**kwargs) context = KTLayout.init(context) form = forms.UtilisateursAddUpdate(request.POST, request.FILES) choices = request.POST.getlist("regroupements") if form.is_valid(): instance = form.save(commit=False) ... instance.save() for item in choices: instance.regroupements.add(item) I don't understand why this code run with one checkbox "checked" but not with more. How should i change my code ? -
I want to save the content from the ai and show it to the frontend
i am creating an AI using openai in django and have made a basic page, now i awant to save the response and show the response to the front-end, just like a chat bot here is my views.py: from django.shortcuts import render, redirect import openai from django.http import HttpResponse from django.views import View from myapp.models import Chat from myapp.forms import ChatForm from django.contrib import messages # Create your views here. openai.api_key = "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" start_sequence = "\nA:" restart_sequence = "\n\nQ: " def home(request): return render(request, "home.html") def chatbot_response(user_input): response = openai.Completion.create( engine="text-davinci-003", prompt=user_input, temperature=0.7, max_tokens=256, top_p=1, best_of=4, frequency_penalty=0, presence_penalty=0, ) return response["choices"][0]["text"] class ChatbotView(View): def post(self, request): user_input = request.POST["user_input"] response = chatbot_response(user_input) context={ 'response':response, } return render(request, "home.html",context) Here is the models.py: from django.db import models # Create your models here. class Chat(models.Model): question = models.TextField() answer = models.TextField() Here is the forms.py: from django import forms from myapp.models import Chat class ChatForm(forms.ModelForm): # validations can be set here class Meta(): model = Chat fields = ['question', 'answer'] here is the urls: from django.contrib import admin from django.urls import path from myapp.views import chatbot_response, home, ChatbotView urlpatterns = [ path('admin/', admin.site.urls), path('', home, name="home"), path('chatbot/', chatbot_response, name="user_response"), path('user_response/', ChatbotView.as_view(), name="chatbot"), … -
Is it possible to make Django switch model variables based on a language?
I have a model with two columns where one is in English, one is in Bulgarian. Currently I am doing this: {% if L == "bg" %} {{adoption.fields.story_bg|safe}} {% else %} {{adoption.fields.story_eng|safe}} {% endif %} But this is too much code and it is annoying to type and look at. Is there a simpler way of doing this? -
How can I combine 2 different models with union?
I want to combine the results of the queries of two different models with unnion, but my sql code is different, I need your help in this regard. Exception is Unable to get repr for <class 'django.db.models.query.QuerySet'> django.db.utils.ProgrammingError: UNION types numeric and character varying cannot be matched LINE 1: ...order"."update_date", "core_filled"."status", "core_trig.. custom_qs = active_qs.annotate(**{'order_numberx': F('order_number'), 'condition_side': Value('GTE', output_field=CharField()), }).values("order_number", "account_id", "order_type", "price", "buy_sell", "status", "add_date", "update_date", "status", "condition_side", "total_price") filled_qs = trigger_qs.annotate(**{'order_numberx': F('order_number'), 'total_price': Value(0, output_field=DecimalField()) }).values("order_number", "account_id", "order_type", "price", "buy_sell", "status", "add_date", "update_date", "status", "condition_side", "total_price") orders_qs = active_qs.union(trigger_qs) SQL QUERY (SELECT "core_custom"."order_number", "core_custom"."account_id", "core_custom"."order_type", "core_custom"."market_code", "core_custom"."channel_code", "core_custom"."price", "core_custom"."volume", "core_custom"."volume_executed", "core_custom"."buy_sell", "core_custom"."status", "core_custom"."add_date", "core_custom"."update_date", "core_custom"."client_id", "core_custom"."post_only", "core_custom"."status", "core_custom"."total_price", GTE AS "condition_side" FROM "core_custom" WHERE ("core_custom"."account_id" = 1549 AND "core_custom"."status" IN (N, P))) UNION (SELECT "core_filled"."order_number", "core_filled"."account_id", "core_filled"."order_type", "core_filled"."market_code", "core_filled"."channel_code", "core_filled"."price", "core_triggerorder"."volume", "core_filled"."volume_executed", "core_filled"."buy_sell", "core_filled"."status", "core_filled"."add_date", "core_filled"."update_date", "core_filled"."client_id", "core_filled"."post_only", "core_filled"."status", "core_filled"."condition_side", 0 AS "total_price" FROM "core_filled" WHERE ("core_triggerorder"."account_id" = 1549 AND "core_filled"."status" = N)) how can i edit order in sql query Combining the results of two queries and returning. I changed the value rows