Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django find object with 2 matching fields
I have an array of id’s: ['ypxiQsnL4Etm', 'eWGzBlgcBy5l', 'ki5H4U4unB2v'] And I have a 'Deal' object that has 2 fields with product 1 and 2. class Deal(models.Model): name = models.CharField(max_length=50, null=True) product1 = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='product1_product') product2 = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='product2_product') I want to loop through that array and see which of those arrays are in the same Deal object. If one of those id’s are in the same object, that is a match. After the match is created, delete the matched id`s from the array. I tried the following: for i in cart: try: product = Product.objects.get(product_id=i) if product.deal_type: product_id = product.product_id combi_products.append(product_id) print(combi_products) except: pass length = len(combi_products) if length > 1: for cp in combi_products: try: deal_1 = Deal.objects.get(product1__product_id=cp) if deal_1: try: print(cp) matched_through = Deal.objects.get(product1__product_id=deal_1.product1.product_id, product2__product_id=cp) print(matched_through) except: pass except: pass -
Which tech stack would someone recommend as a full stack developer? MERN or Django? or it is purposed centered choice? [closed]
Confused between these too full stack development stacks, MERN or Django, formal being JS based later being fully python based. share your reviews/ opinions.... -
i want to send terminal print data to database
enter image description here actually I'm new to Django, I have created selenium project in which It automates mobile recharge. After completion of "recharge successful" I needed to send successful receipt into my database. I used print(order_id.text) to get receipt in my terminal. now I don't know how to send that receipt to m -
Why in some case forms.hiddenInput() with initial value return None and some time the initial value?
I have 2 forms (form 1 RandomizationForm = modelForm and form 2 RallocationForm= form) with the same hidden field with initial value but they do not have the same behavior: form 1 return the initial value in self.cleaned_data['ran_log_sit'] form 2 return None in self.cleaned_data['ran_log_sit'] So I have to had clean_ran_log_sit(self) method to set initial value when self.cleaned_data['ran_log_sit'] return None I don't know why and so I am not sure with my code form 1: class RandomisationForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomisationForm, self).__init__(*args, **kwargs) ... SITE_CONCERNE = Site.options_list_site_concerne_randomization_or_reallocation(self.user,self.user_pays,self.user_site_type,self.language) if self.user_site_type == 'International': self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), required=True, widget=forms.Select, choices=SITE_CONCERNE) elif self.user_site_type == 'National': self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), widget=forms.Select, choices=SITE_CONCERNE) else: self.fields["ran_log_sit"] = forms.ChoiceField(label = _("Randomization site"), widget=forms.HiddenInput(), choices=SITE_CONCERNE, initial = self.user_site, disabled=True) ... # vérification que la randomisation est possible (i.e. au moins une boite d'aspirine et une boite de placebo) def clean(self): cleaned_data = super(RandomisationForm, self).clean() # validation anti-doublon if Randomisation.objects.filter(ran_num = self.data.get('ran_num').upper()).exists(): bras = Randomisation.objects.get(ran_num = self.data.get('ran_num').upper()).ran_bra bras_libelle = OptionDeThesaurus.objects.get(the_id=10,the_opt_cod=bras).the_opt_lab_eng med = current_drug(self.data.get('ran_num').upper()) raise forms.ValidationError(str(_('This patient has already been randomized in arm '))+str(_(bras_libelle))+str(_(' - current box number '))+str(med)+str(_('. Please control patient number.'))) # vérification stock print("cleaned_data['ran_log_sit']",cleaned_data['ran_log_sit']) pays = Site.objects.get(sit_abr = cleaned_data['ran_log_sit']).reg.pay.pay_abr if patient_code_is_valid(cleaned_data['ran_num']) and … -
How do I display image in an object detail view without creating an extra ImageField?
I've it done in admin list display by simple creating a function and adding it to list_display. I want something similar in detail view. Can this be done? models.py class Log(models.Model): created = models.DateTimeField(null=True, auto_now_add=True) model = models.CharField(max_length=100) modified = models.DateTimeField(null=True, auto_now=True) req_endpoint = models.CharField(max_length=800) resp_json = models.TextField(max_length=1000) resp_img_uri = models.CharField(max_length=750) input_image = models.CharField(max_length=750) status_code = models.CharField(max_length=100) elapsed_time = models.CharField(max_length=100) score = models.CharField(max_length=100) request_domain = models.CharField(max_length=100) human_observation = models.CharField(max_length=50, choices = confusion_matrix, editable=True) def __str__(self): return self.human_observation admin.py class LogAdmin(admin.ModelAdmin): list_filter = ('model','human_observation') list_display = ['id','response_img','input_img','model','score','created','human_observation','admin_image'] ordering = ['-id'] def response_img(self, obj): return format_html('<img src="{0}" style=" object-fit: cover; width: auto;height: 60px;" />'.format(obj.resp_img_uri)) def input_img(self, obj): return format_html('<img src="{0}" style=" object-fit: cover; width: auto;height: 60px;" />'.format(obj.input_image)) -
csrf_token verification failed or aborted error with form
I'm getting CSRF verification failed. Request aborted. My index view: def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks,'form':form} return render(request, 'tasks/list.html', context) My list.html template with form: <h3>TO DO</h3> <form method="POST" action="/"> {% csrf_token %} {{ form.title }} <input type="submit" name="" value="Create Task"> </form> {% for task in tasks %} <div> <p>{{ task }}</p> </div> {% endfor %} -
Update model field after saving instance django
I have a Django model Article and after saving an instance, I want to find the five most common words (seedwords) of that article and save the article in a different model Group, based on the seedwords. The problem is that I want the Group to be dependent on the instances of Article, i.e. every time an Article is saved, I want Django to automatically check all existing groups and if there is no good fit, create a new Group. class Article(models.Model): seedword_group = models.ForeignKey("Group", null=True, blank=True) def update_seedword_group(self): objects = News.objects.all() seedword_group = *some_other_function* return seedword_group def save(self, *args, **kwargs): self.update_seedword_group() super().save(*args, **kwargs) class Group(models.Model): *some_fields* I have tried with signals but couldn't work it out and I'm starting to think I might have misunderstood something basic. So, to paraphrase: I want to save an instance of a model A Upon saving, I want to create or update an existing model B depending on A via ForeignKey Thanks in advance for any help or advice. -
How to open a picture as a pop up in the same window as the django template?
I am currently working with django and have encountered a problem whilst translating the original HTML code to fit with django template requirements. The code works just fine for the most part but the problem arises when I try to open a picture that should open as a pop-up. The picture is wrapped in the anchor tag and links to a file in a directory that contains the same picture which I then opened as a pop-up over the existing window. Django interprets the href as a URL and trees to find it in urlpatterns. If I were to add a urlpatter for the picture, or in this case each individual picture alone it would not serve the same purpose as I would have to render a new view and encounter the same problem. Is there a way to open pop-ups in django and do I need to add to the list of urlpatterns: the following are screenshots of the original HTML code and how it should look. <div class="column"> <a href="images/cases/cases1.jpg" data-lightbox="cases" data-title="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Fugiat, dolore!" > and pic1 pic2 -
Manage a class with too many instances in a table Django
I'm new in Django development and I need your help, please. I have a list of 44.000 rows of products (instances of product class).I displayed these products in a table using jquery, but it takes so much time to display them. So I would like to know if there is a way to manage a class with too many instances in a table This is my product class in models.py class Product(models.Model): STOCK_STATE = ( ("Vide", "Vide"), ("Faible", "Faible"), ("Moyen", "Moyen"), ("Satisfaisant", "Satisfaisant"), ("Plain", "Plain"), ) product_name = models.CharField( max_length=60, null=False, blank=False,) image_product = models.ImageField( upload_to=upload_location_image, null=False, blank=False) last_update = models.DateField(null=False, blank=False) price = models.FloatField(null=False, blank=False) num_art = models.IntegerField(null=False, blank=False) stock_state = models.CharField( max_length=60, null=False, choices=STOCK_STATE) #aisle = models.ManyToManyField(Aisle) product_group_code = models.IntegerField(null=False, blank=False) product_group_name = models.CharField( max_length=60, null=False, blank=False) product_subgroup_code = models.IntegerField(null=False, blank=False) product_subgroup_name = models.CharField( max_length=60, null=False, blank=False) def __str__(self): return self.product_name this is my views.py def consult_product_view(request, pk ): product= Product.objects.get(id=pk) anomalies_per_product = product.anomalie_set.all() context = { 'product': product, 'anomalies_per_product': anomalies_per_product} return render(request, 'anomalie/consult_product.html', context) and this is my table.html <script> $('#mydatatable').DataTable({ pagingType: 'full_numbers', }); </script> <div class="container mb-5 mt-3"> <table class="table table-striped table-bordered" style="width: 100%" id="mydatatable"> <thead> <tr> <th>Image produit</th> <th>Nom du produit</th> <th>Num_art</th> </tr> </thead> <tbody> … -
TypeError: object.__init__() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:50083]
I am building a chat app and I am stuck on an Error. When i runserver, it is working fine but when I refresh the browser then it is showing TypeError: object.init() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:50083] settings.py: ASGI_APPLICATION = 'brain.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I will really appreciate your Help. tHANK yOU iN aDVANCE. Best Regards -
Django: How To Remove Invalid Dates From DateField
My form allows users to input invalid dates like 31 of febuary, is there a way to exclude certain dates in a range? models: release_date = models.DateField(null=True, blank=True, default=None) froms: YEARS = [x for x in range(1900,2030)] class NewPost(forms.ModelForm): release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) -
How to extend custom error page template in Django?
I have the following layout for custom error pages: {% extends 'base.html' %} {% block title %}[TITLE]{% endblock title %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'page.css' %}"/> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="container"> <h1> [MAIN-TITLE]</h1> <h2> [SUB-TITLE]</h2> <div class="message"> [MESSAGE] </div> </div> </div> </div> </div> This means that I have the same html for each status code (400.html, 500.html and so on). I want to make error_page.html and each one of the status codes (400.html, 500.html and so on) will extend it. The only difference between the pages is the blocks I marked with []. How can I do such thing in Django? -
How to insert data in multiple tables from single html form using Django and MySQL?
I have created one HTML form for adding Class_name, Subject_name, Topics and Questions for creating Question Paper Set. All tables are interconnected to each other using Foreign Key in my Models. Now I want to insert these data into different tables named as Classes, Subjects, Topics etc from dropdown in HTML form. These are my code below: models.py class Classes(models.Model): options = (('JEE', 'JEE'),('IEEE', 'IEEE')) className = models.CharField(max_length=200, choices=options, null=True) status = models.CharField(max_length=50) class Subjects(models.Model): options = (('Physics', 'Physics'),('Chemistry', 'Chemistry'), ('Maths', 'Maths')) classes_id = models.ForeignKey(Classes, max_length=200, null=True, on_delete=models.CASCADE) subjectName = models.CharField(max_length=500, choices=options, null=True) status = models.CharField(max_length=50) class Section(models.Model): options = (('Sec1', 'Sec1'),('Sec2', 'Sec2'), ('Sec3', 'Sec3')) classes_id = models.ForeignKey(Classes, max_length=200, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subjects, max_length=200, null=True, on_delete=models.CASCADE) sectionName = models.CharField(max_length=500, choices=options, null=True) status = models.CharField(max_length=50) views.py def createQuestionPaper(request): if request.method == 'POST': Class = request.POST['Class'] Subjects = request.POST['Subjects'] Sections = request.POST['Sections'] Topics = request.POST['Topics'] createClass = Classes.objects.create(className=Class, status=1) classId = Classes.objects.latest('id') createSubjects = Subjects.objects.create(subjectName=Subjects, classes_id_id=classId, status=1) subjectId = Subjects.objects.latest('id') createSections = Section.objects.create(sectionName=Sections, classes_id_id=classId, subject_id_id=subjectId, status=1) sectionsId = Section.objects.latest('id') return redirect('/showPaper') else: return render(request, 'exams/createQuestionPaper.html') createQuestionPaper.html <form action="" name="paper" method="POST"> {% csrf_token %} <select name="Class" class="form-control"> <option selected="" name="Class">Class</option> <option value="JEE"> JEE </option> <option value="IEEE"> IEEE </option> <option value="PET"> PET </option> … -
Serve interactive 360 video on Django
I'm trying to build a website with Django where you can view different 360 videos. The videos are created with a software (3dVista) that generates a web build folder with an index.htm file and some javascript code and other media files. In order to view the web build I have to open the index.htm file. The problem is that inside the index file are referenced multiple javascript and media files like this: href="main.js?v=23182178412", so I have to substitute all the references with the Django syntax {% static 'path/to/main.js' %}. This is very tedious and sometimes it doesn't work because I cannot find all the references within all the files. \ Is there a way to avoid this in Django? Or is it better to host the web builds on another server? -
How to resize django ckeditor inside the form model
I need to use django-ckeditor in various part of my project, so for each part need to resize it. But I know that I can resize it by adding this definitions in settings as below: INSTALLED_APPS = [ 'ckeditor', ] CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', 'height': 70, 'width': 430, }, } however, as I mentioned above, I am using several editor in different parts, so need to resize them differently. How to reside in different form.fields? class proForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) class Meta: fields = ('__all__') -
Why is custom serializer save() method not called from view?
I have a view like this: class MyViewSet(ModelViewSet): # Other functions in ModelViewset @action(methods=['post'], url_path='publish', url_name='publish', detail=False) def publish_data(self, request, *args, **kwargs): new_data = util_to_filter_data(request.data) serializer = self.serializer_class(data=new_data, many=True) serializer.is_valid(raise_exception=True) serializer.save() # This is calling django's save() method, not the one defined by me return Response(serializer.data) And my serializer: class SomeSerializer(ModelSerializer): # fields def create(self, validated_data): print("in create") return super().create(validated_data) def save(self, **kwargs): print("in save") my_nested_field = self.validated_data.pop('my_nested_field', '') # Do some operations on this field, and other nested fields obj = None with transaction.atomic(): obj = super().save(kwargs) # Save nested fields return obj When I'm calling my serializer's save() method from my view (see the comment in view code), the save() method of django is called instead of the one defined by me, due to which I'm having issues that were handled in my save() method. This is the traceback: File "/home/ubuntu18/Public/BWell/path_to_view/views.py", line 803, in publish_data serializer.save() File "/home/ubuntu18/Envs/bp_env/lib/python3.7/site-packages/rest_framework/serializers.py", line 720, in save self.instance = self.create(validated_data) I wanted to perform some actions in save() before calling create(), but my flow is not reaching the save() method. What am I doing wrong here? P.S.: This is happening only when I am providing many=True in serializer constructor. -
Unique token using uuid is generating same codes
im using uuid token to activate users account , so every client created have their own code in the Client model , but when i create new client it generate always the same Token as others , i have used the uuid 4 , is their anyother ways to generate unique client code to activate their account or some other method then uuid , or just im missing a point on how to generate uuid on models , their is my model and client creation codes : Model.py : def generateUUID(): return str(uuid4()) class client(models.Model): name = models.CharField(max_length=45, unique=True) email = models.EmailField(max_length=85) date_of_birth = models.DateField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True , blank=True) created_at = models.DateTimeField(auto_now_add=True) picture = models.URLField(null=True ,blank=True) affiliation = models.ForeignKey(User, on_delete=models.CASCADE, related_name="client_coach") reference = models.OneToOneField(User, on_delete=models.CASCADE, null=True , blank=True) is_active = models.BooleanField(default=False) token = models.CharField( max_length=85, default=generateUUID()) def __str__(self): return self.name def getname(self): return self.coach.name view.py: if request.method == 'POST' and request.POST['action'] == 'client': form = ClientForm(request.POST) print(form) name = request.POST.get('name') email = request.POST.get('email') #client_code = code.objects.create() new_client = client.objects.create(name = name, email = email, affiliation = request.user) new_client.save() return JsonResponse({'client': model_to_dict(new_client)}, status=200) -
JSON Exception Handling Syntax unclear to me -- JSONDecodeError
I am using JSON to get some data from an API and if the entered URL is wrong(which is very possible) the JSON file returns: "Unknown symbol" The error message is as follows : (don't be scared a lot of it is just relevant information, scroll down to the bottom I have highlighted the main error.) Environment: Request Method: POST Request URL: http://127.0.0.1:8000/buy/ Django Version: 3.1.2 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\VARDHAN\Desktop\python websites\trading_website\accounts\views.py", line 116, in buy json_data = requests.get(url).json() File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json_init_.py", line 348, in loads return _default_decoder.decode(s) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /buy/ … -
Online result search aplication first html page should render the form and second page will show the data. Help Appricated?
Django, I have two HTML pages first is index.html which shows the home page along with the search field and the second HTML form is the result which shows the desired result which is search by the user. I have already written code that is working fine on only one page but I want to redirect the home page once the user fillup the details it should go to the next page called result.html. modles.py from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Windows 10', 'Windows 10'), ('Windows 8', 'Windows 8'), ('Linux', 'Linux'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) level = models.CharField(max_length=30) program = models.CharField(max_length=30) semester = models.CharField(max_length=20) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) subject2_code = models.CharField(max_length=40) subject2_title = models.CharField(max_length=40) subject2_credit_hour = models.TextField() subject2_grade_point = models.TextField() subject2_grade = models.TextField() subject2_remarks = models.CharField(max_length=20, null=True, blank=True) subject3_code = models.CharField(max_length=40) subject3_title = models.CharField(max_length=40) subject3_credit_hour = models.TextField() subject3_grade_point = models.TextField() subject3_grade = models.TextField() subject3_remarks = models.CharField(max_length=20, null=True, blank=True) subject4_code = … -
Django - Validation Errors not displayed using Ajax
I have a contact form and i'm using Ajax to submit the form. However i have a problem i cannot figure out how to display error messages, to notify user that has entered wrong data. For example name field accepts only letters, also i'm using PhoneNumberField to check phone. <p id="error_1_id_name" class="invalid-feedback"><strong>Wrong First Name, use only letters</strong></p> Enter a valid phone number (e.g. +12125552368). When submitting the form with invalid data for example enter name with numbers i'm getting When entering correct data everything works as expected. Any help is appreciated. views.py def contact(request): form = ContactForm(request.POST or None) data = {} if request.is_ajax(): if form.is_valid(): form.save() data['name'] = form.cleaned_data.get('name') data['status'] = 'ok' return JsonResponse(data) context = { 'form': form, } return render(request, 'pages/contact.html', context) main.js const alertBox = document.getElementById('alert-box') const form = document.getElementById('contact') const name = document.getElementById('id_name') const email = document.getElementById('id_email') const phone = document.getElementById('id_phone') const subject = document.getElementById('id_subject') const budget_range = document.getElementById('id_budget_range') const message = document.getElementById('id_message') const csrf = document.getElementsByName('csrfmiddlewaretoken') console.log(csrf) const url = "" const handleAlerts = (type, text) =>{ alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } form.addEventListener('submit', e=>{ e.preventDefault() const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('name', name.value) fd.append('email', email.value) fd.append('phone', phone.value) fd.append('subject', subject.value) … -
Python correlation in DJango
I am making a website on Django with Python. Index.html page has a form with 10 rows each row has six inputs which are price, review, rating, voucher, first review(date input) & shipping. User will input data in HTML from there I am converting that data in Pandas data frame. In Pandas dataframe there are two additional columns "current date" and "days". These two new columns are meant to calculate number of days between first review and current date. Based on the dataframe columns when I run Python correlation function .corr() It is only showing two columns with NaN values. Can someone help me to show complete correlation values in powershell? NOTE: THE CODE RUNS FINE WITH JUPYTER NOTEBOOK My views.py code is as follows Views.py def index(request): if request.method == "POST": qsPrice1 = request.POST.get('price1') qsPrice2 = request.POST.get('price2') qsPrice3 = request.POST.get('price3') qsPrice4 = request.POST.get('price4') qsPrice5 = request.POST.get('price5') qsPrice6 = request.POST.get('price6') qsPrice7 = request.POST.get('price7') qsPrice8 = request.POST.get('price8') qsPrice9 = request.POST.get('price9') qsPrice10 = request.POST.get('price10') qsReview1 = request.POST.get('review1') qsReview2 = request.POST.get('review2') qsReview3 = request.POST.get('review3') qsReview4 = request.POST.get('review4') qsReview5 = request.POST.get('review5') qsReview6 = request.POST.get('review6') qsReview7 = request.POST.get('review7') qsReview8 = request.POST.get('review8') qsReview9 = request.POST.get('review9') qsReview10 = request.POST.get('review10') qsRating1 = request.POST.get('rating1') qsRating2 = request.POST.get('rating2') qsRating3 = … -
Change Page owner in Wagtail admin
We have a Wagtail site where various people contribute to a news item before its published and the person who creates the page is not necessarily the main author. I'm looking for way to edit the Page.owner in the Wagtail admin. In the model class I've added: content_panels = Page.content_panels + [ ... FieldPanel('owner') ] Which shows all the site's users in a dropdown but this doesn't get saved. I was wondering if there was a more 'Wagtail' way of doing this, aside from overriding the save() definition. -
How to turn off a django model field validation?
I have a model as below: from cities.models import City class Post(models.Model): location = models.ForeignKey(City, default='', blank=True, null=True, on_delete=models.CASCADE) and in the template: <form id="dropdownForm" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ wizard.form.media }} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} <div class="content-section-idea-detail-1stpage mt-4 text-center"> <label for="selectorlocation" class=""><h4><b>Select your location:</b></h4></label><br> {{ wizard.form.location }} </div> {% endif %} <input id="id_sub_post_details" class="btn btn-sm btn-primary ml-2" type="submit" value="{% trans 'submit' %}"/> </form> But the problem is that, I am not able to leave location field empty as it verifies the field before submit. However, I expect blank=True disables the validation. Do you know where is the problem happening? -
How does Python import packages and files with the same name?
I have a Django project and the directory is as follows. There are a Python file named permissions.py and a module name permissions.I want to import permissions.helpers but it raises ImportError and the error message is cannot import name helpers. The first element in sys.path is the project directory(the parent directory of myapp) as I expected.I thought Python Interpreter should try to find modules or files from sys.path but it seems to search in the current module first.Am i wrong and how can i import permissions.helpers without using absolute_import? -
Full text mysql database search in Django
We have been using a MYSQL database for our project and Django as the backend framework. We want to support a full text search on a particular table and return the Queryset in Django. We know that Django supports full text search on a Postgres database but we can't move to another database now. From what we have gathered till now - Using inbuilt search functionality - Here we check on every field if the value exists and then take an OR to combine the results. Similar to the link (Django Search query within multiple fields in same data table). This approach however straight forward may be inefficient for us because we have huge amounts of data. Using a library or package - From what we have read Django haystack is something a lot of people are talking about when it comes to full text search. Django Haystack - https://django-haystack.readthedocs.io/en/master/tutorial.html#installation We haven't checked the library completely yet because we are trying to avoid using any library for this purpose. Let us know if you people have worked with this and have any views. Any help is appreciated. Thanks.