Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with MONGO DB using DJONGO
I'm using MongoDB on Django for now i trying to use the DJONGO, but I'm struggling to build the same SCHEMA I already created at my database on MongoDB for Django. Follow below one example from my DB schema. { 'stock': 'Microsoft', 'code': 'msft', 'result': { '2020': { 'item1': 123, 'item2': 456, }, '2019': { 'item1': 987, 'item2': 456, }, } }, { 'stock': 'Facebook', 'code': 'fb', 'result': { '2011': { 'item1': 999, 'item2': 555, }, '2015': { 'item1': 753, 'item2': 159, }, } } To access the first line it's pretty simple has you guys can see bellow, but the difficulty start when need access the embedded sub-documents. class Stocks(models.Model): stock = models.CharField(max_length=255, verbose_name='Stock name:') code = models.CharField(max_length=255, verbose_name='Stock code:') I tried several solutions and could find nothing to help. If someone know anything or can give me a hand on this, I will be pleased! Thanks! Cid -
PYTHON PACKAGE OVERRIDE Django-Machina App error if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class
First and foremost, I appreciate all the help you guys have given me by just reading the forum. I have a problem that iv been trying to figure out for a while. I have two django frameworks that i am trying to merge together. The two systems are one of mine and Django-Machina which is forum. Each of the frameworks has 2 "accounts models". Im probably not setting this up correct. Any ideas how to set this override up? I need the Accounts.User model to feed its data into Forum_member model. The Documentation for Django-Machina says to create a python package to override its native model with one of my interest. So im attempting to override the Machina forum-member application with my own accounts models. I get this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class (base) Zeitgeists-MacBook-Pro:backend zeitgeist$ Here … -
Django migration duplicate operation
I'm using Django for the backend of my application and everything is fine except a little problem with my migrations. I'm using a custom User model by inheriting from AbstractUser and I have something like the following : class User(AbstractUser): class Meta: verbose_name = "User" # Fields and methods here # ... which results in this part of the migration in my 0001_initial.py migration file : options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', 'abstract': False, }, The thing is, when I run makemigrations later on, it creates an automatic migration with this little part in it : migrations.AlterModelOptions( name='user', options={'verbose_name': 'User'}, ), I do not understand why it tries to apply this modification a second time. Can someone help me ? I could let it as it is but I try to keep my migration files as clean as possible. Thanks in advance. -
csv + Kafka + Spark streaming + MLlib + Django Dashboard
I have a (personal) project where i need to develop a big data pipeline starting from an upgradeable csv. The final goal is to build a dashboard that allow to monitor and make real time forecast based on the csv file. I would like to show the dashboard from a django web app. From what i've seen one kind an infrastructure that might be suitable includes: kafka ---> spark ---> PostgreSQL -->django--->dashboard. Does anyone have any advice or faced a similar problem? -
Django NameError: name 'Instractor' is not defined
I have two apps in Django project . one is "accounts" another is " Courses " I have a model in accounts app class Student(SoftDeleteModel): user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='student_info') name = models.CharField(null=True, blank=True, max_length=250) course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True) trx_id = models.CharField(max_length=20) date_of_birth = models.DateField(null=True, blank=True) education_qualification = models.CharField(null=True, blank=True, max_length=250) institution_name = models.CharField(null=True, blank=True, max_length=250) image = models.ImageField(upload_to='photos/%y/%m/%d',null=True, blank=True) address = models.CharField(null=True, blank=True, max_length=250) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.email class Instractor(SoftDeleteModel): user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='instractor_info') name = models.CharField(null=True, blank=True, max_length=250) degination = models.CharField(null=True, blank=True, max_length=250) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is model for accounts and Course Model is: from accounts.models import * class Courses(models.Model): title = models.CharField(max_length=200,blank=True,null=True) image = models.ImageField(null=True,upload_to="photos/course/") category = models.ForeignKey(Category,on_delete=models.CASCADE) instractor = models.ForeignKey(Instractor, on_delete=models.CASCADE,blank=True) total_student_enrolled = models.IntegerField(null=True,blank=True) price = models.IntegerField(blank=True,null=True) course_length_in_hour = models.IntegerField(blank=True,null=True) course_length_in_weeks = models.IntegerField(blank=True,null=True) programming_language = models.CharField(max_length=500,null=True,blank=True) course_requirements = models.TextField() course_description = models.TextField() what_you_will_learn = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now_add=True) is_published = models.BooleanField(default=False) slug = models.SlugField(null = False, blank = True) def __str__(self): return self.title I have import courses.model but it showing that Instractor not Defined. But if i remove course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True) course_enrolled field from accounts model the error is not showing :/ I don't get … -
Getting KeyError when using request.session['value'] in django
I am trying to write session and want to read session from another view function in django. I am using django 3.1.5. Here is my views.py code, I set a session after user is logged in request.session['value'] = 'istiak' def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) request.session['value'] = 'istiak' return redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'library_site/login.html') And In this view I tried to get this session data. Code-> usern = request.session['value'] def bookprofile(request): usern = request.session['value'] return render(request, 'library_site/bookprofile.html') But I am getting error KeyError: 'value' . Here is full error Traceback (most recent call last): File "C:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "B:\django\Django_Project\Library\library\library_site\views.py", line 31, in bookprofile usern = request.session['value'] File "C:\python\Python38\lib\site-packages\django\contrib\sessions\backends\base.py", line 65, in __getitem__ return self._session[key] KeyError: 'value' -
Django Filter for Model function
I am trying to filter through a TextField where I have stripped it of its HTML tags. However, it gives me this error: "Cannot resolve keyword 'search' into field." Here is my code: models.py class Entry(models.Model): body = models.TextField() def search(self): tags = re.compile('<.*?>') cleantext = re.sub(tags, '', self.body) return cleantext views.py from django.db.models import Q ... def search_list(request, query=None): search = "search" entrys = Entry.objects.filter(status="publish").filter(Q(search_body__icontains=search)).distinct() Is there a way to do this? -
Error while fetching values from list of dictionaries inside a dictionary
I need to fetch values from product_name which is a key in the list of dictionaries inside a dictionary. [{'id': 53, 'loc_latitude': 19.036798, 'loc_lonitude': 72.8424038, 'address1': 'Paradise Cinema, Mahim(west)', 'address2': 'Mumbai 12345', 'pincode': '400016', 'address_category': None}] {'order_id': 'helit', 'user_id': 75, 'wallet_amount': None, 'payable_amount': None, 'payment_status': False, 'payment_mode': None, 'order_status': 'book', 'delivery_status': 'In process', 'order_delivery_type': 'Delivery', 'get_cart_total_discount': 0.0, 'get_cart_total_GST': 0.0, 'get_cart_total': 81.0, 'get_cart_sub_total': 56.0, 'get_cart_quantities': 2, 'get_cart_items': 1, 'deliveryCharges': 25.0, 'subscription_type': False, 'subscriptionId': None, 'products': [{'product_id': 'NNPTA', 'product_name': 'CHASS 200 ML', 'product_description': 'The secret recipe of butter milk from Punjab Sind Foods is a refresher any time! an excellent source of probiotics and a must have with every meal for better digestion.', 'product_images': '/images/productImages/Masala_Chass_yGg9K92.png', 'product_price': 28.0, 'gst': 0, 'product_status': None, 'discount': None, 'rating': None, 'product_quantity': 2, 'get_product_total': 56.0, 'get_product_total_gst': 0.0}]} What I've tried Assuming products is a variable containing all the data products = product_data['products'] product_name = [x for x in product_price['product_name']] Doing this would give me tuple indices must be integers or slices, not str -
How to formulate an ajax url in an external js file in Django?
I have a registration form for my student user where I ask him to enter an email address. On keyup, I want to verify whether that user exists in the database. If yes, I will prevent him from submitting the form. How do I achieve this? Here are my files. P.S: username=email urls.py urlpatterns = [ path('', views.home, name="home"), path('login/', views.login, name="login"), path('signup/', views.signup, name="signup"), path('validate_stud_username', views.validate_stud_username, name='validate_stud_username'), ] views.py def validate_stud_username(request): username = request.GET.get('stud_email', None) response = { 'is taken': User.objects.filter(username__iexact=username).exists() } return JsonResponse(response) signup.html <form action="{% url 'signup' %}" id="stud_registration_form" method="POST" > {% csrf_token %} <div class="form-group col-md-6 col-sm-6 col-xs-12"> <input type="email" id="stud_email" style="color: black;" name="stud_email" value="" placeholder=" Email" autocapitalize="none" required> <span style="color: red;" class="error_form" id="stud_email_err"> </span> <div class="login_btn_wrapper register_btn_wrapper login_wrapper "> <button class="btn btn-primary btn-block login_btn" type="submit" style="padding: 2% 0;"> Sign Up </button> </div> </form> form_validations.js $("#stud_email").keyup(function () { $.ajax({ data: $(this).serialize(), url: "/validate_stud_username/", success: function (response) { if (response.is_taken == true) { $("#stud_email").addClass("invalid"); } else { $("#stud_email").addClass("valid"); } }, }); check_stud_email(); }); -
How to simulate a Django form error in Javascript
I have a form where I want to do some extra confirmation (via a modal) in a certain case. Since this is based on an email field, I'd like to validate that field before dropping into the modal. I'm doing this in JS: const newEmailField = document.getElementsByName('new_email')[0] const newEmailError = document.createElement('p') newEmailError.innerHTML = '<strong>Enter a valid email address.</strong>' newEmailError.classList.add('invalid-feedback') newEmailError.id = 'new-email-error' Then setting the new element after the field (in the event the validation fails): newEmailField.after(newEmailError) This actually works if I look at the inspector. The HTML looks pretty much like it would if I'd submitted an invalid email, with the exception of the id, which is slightly different, but it's just not displayed on the page at all! What am I missing here? -
Django way to represent languages of users
I have the Follower class class Follower(models.Model): language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) and the Lang class: class Language(models.Model): code_name = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return self.code_name Where looking for negative value e.g user_langugae != 'ar I get the following lookup: SELECT * FROM "instagram_data_follower" WHERE NOT ("instagram_data_follower"."id" IN (SELECT U1."follower_id" FROM "instagram_data_follower_language" U1 INNER JOIN "instagram_data_language" U2 ON (U1."language_id" = U2."id") WHERE U2."code_name" = ar))) Which takes so longggggg over 20 minute sometimes. Lookup for equal is much faster. I think I need to redesign the schema so languages will be kind of bitmap. Can you suggest a better way to look up on negative condition for one to many field ? Most of my lookups are user_langugae != 'ar AND user_langugae == 'he' I Saw this: https://github.com/disqus/django-bitfield btw -
How to use Docker Image in Django?
I made a docker image and I want to use this image in Django like a url. I always find examples about how to set up docker to django but I want to use it with a single line of url. I found a flask code but I really don't know how to convert it. So here is my flask app.py file: @app.route("/index", methods=['POST']) def index(): url = "http://localhost:5000/index" #this is my link to docker file payload = {"text": request.form["input_text"]} response = json.loads(requests.request("POST", url, json=payload).text) return jsonify(response) How can I write this code with Django? -
Django: Abstract base class for managing db_table
I'm trying to build my second django (and python for that matter, my first project being the django tutorial :)) project. since this is supposed to be something real i'd like to be thorough and build a good code structure before i go into the meat of the project. I have a couple of simple models like this class Task(models.Model): name = models.CharField(max_length=50, null=False) description = models.CharField(max_length=255, null=True) dueDate = models.DateTimeField() I'm using PostgreSQL and i set up my models to use the app label as a database schema by defining the meta class of each model like this class Meta: managed = True db_table = 'app_name\".\"modelname' This works well. But i have to do this for every single model. I want to keep it DRY though. So what i'm trying to do now is to have an abstract base class that does this automatically so i tried the following: class SchemaModel(models.Model): class Meta(): abstract = True managed = True db_table = AppConfig.label+'\".\"'+self.__class__.lower()+'s' (the base class was then inherited of course and i took the nested Meta class out of the normal models) this didn't work though because self isn't accessible in Meta after consulting the documentation i tried this: … -
How to reference S3 bucket inside views within a Django project?
I'm using an S3 to deliver static content. I only use Django as a RESTful API, my frontend is built using React. I do however use one HTML file as a template. The HTML file is only used as part of the HTML content of an email message sent by my server. I plan on moving this HTML file to my S3 Bucket. I'm trying to wrap my head around how I may reference such file within my S3. Normally to reference a standard HTML template in django, it can look something like this: html = render_to_string('email/email_confirm.html', context) email being the name of the folder inside templates. I know how to work with pathing within an S3, but how can I pull up and reference that object directly within my view below? I have already configured all my S3 settings class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: # GENERATE EMAIL CONFIRMATION TOKEN user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token # GENERATE EMAIL CONFIRMATION TEMPLATE current_site = get_current_site(request).domain relative_link = reverse('users:email-verify') # CHANGE TO HTTPS in PRODUCTION absurl = 'http://'+current_site+relative_link+"?token="+str(token) email_body = 'Hi '+ user.username+', Please use … -
django passing id of the first saved form to the second form
My model has one to many relationships, when the user saves the first forms he will navigate to another form and the user should be able to fill up the second form and save it. Because it is a one-to-many relationship I want to pass the id instance of the first saved entry to the second form. However, when I fill up the second form and try to save it the data for the second form is not saved. I am not sure what I am doing wrong causes the data on the second form not to be saved. view.py that saves the first forms ef add_bank_form(request): if request.method == 'POST': form = BankForm(request.POST) natural_person_form = NaturalPpersonPform(request.POST, request.FILES) OwnShares = OwnSharesInOtherCompanyForm(request.POST, request.FILES) if form.is_valid() and natural_person_form.is_valid(): form = form.save() natural_person = natural_person_form.save(commit=False) natural_person.domesticbank = form natural_person.save() share = OwnShares.save(commit=False) share.domesticbank = form share.save() return HttpResponseRedirect('/add_source_of_income') else: form = BankForm() natural_person_form = NaturalPpersonPform() OwnShares = OwnSharesInOtherCompanyForm() return render(request, 'add_domestic_bank.html', {'form': form, 'natural_person_form': natural_person_form, 'OwnShares': OwnShares}) view.py that saves the second form def add_source_of_income(request): if request.method == 'POST': get_bank_id = DomesticBank.objects.order_by('-pk')[0] form = SourceOfIncomeForm(request.POST, request.FILES, instance=get_bank_id) if form.is_valid(): form.save() return HttpResponseRedirect('/DisplayBankRisk') else: form = SourceOfIncomeForm() return render(request, 'add_income_source.html', {'form': form}) -
Django - set model's `CharField` primary key from processed `ImageField` data
This is maybe a poor way to ask this question, as I haven't yet tried anything since I'm not sure if it's even possible without a bunch of custom JS added to the admin. Given a model such as: class MyModel(models.Model): sku = models.CharField('SKU', max_length=20, primary_key=True) bar_code = models.ImageField(upload_to='images/barcodes') I want the user to select an image which will be a photo of a product's barcode. The image then needs to be processed to scan for the barcode (I'm using pyzbar) and this value should be saved to the primary key field sku. Since I can't save the model without a primary key, and I need to upload the image field to scan the barcode to discover the value to be used for the primary key, I'm thinking that the only way to do this would be to use some client side JS in the admin to upload the image to a temp location using a DRF endpoint (or similar), read the barcode and return that value to the client which could then set the value of sku with some basic javascript. Then the model can be saved and image uploaded (a second time). Is there a more straightforward way … -
ParentalManyToManyField in Wgarail works with normal model but not with orderable
Hello everyone I used the ParentalManyToManyField like described in here in the first step https://www.accordbox.com/blog/wagtail-tip-1-how-replace-parentalmanytomanyfield-inlinepanel/ and it worked, but after that I needed to use it in an Orederable Model like this: class GalleryCategory(models.Model): name = models.CharField(max_length=50) panels = [ FieldPanel("name"), ] def __str__(self): return self.name class GalleryMedia(Orderable): category = ParentalManyToManyField("gallery.GalleryCategory", blank=True) gallery = ParentalKey( "gallery.Gallery", on_delete=models.CASCADE, related_name="media", null=True ) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.CASCADE, related_name="+", null=True, blank=True ) video_url = models.URLField(blank=True) video = models.ForeignKey( "wagtailvideos.Video", related_name="+", null=True, blank=True, on_delete=models.SET_NULL, ) show_large = models.BooleanField(default=False) show_on_homepage = models.BooleanField(default=False, verbose_name="Show on HomePage") panels = [ ImageChooserPanel("image"), FieldPanel("video_url"), VideoChooserPanel("video"), FieldPanel("show_large"), FieldPanel("show_on_homepage"), MultiFieldPanel([FieldPanel("category", widget=CheckboxSelectMultiple),]), ] class Gallery(Page): content_panels = Page.content_panels + [ InlinePanel('media', label=_('Gallery Media')) ] I registered the Category Model in the admin dashboard like this: class GalleryCategoryModelAdmin(ModelAdmin): model = GalleryCategory menu_icon = "edit" menu_order = 300 add_to_settings_menu = False exclude_from_explorer = ( False ) list_display = ("name",) search_fields = ("name",) modeladmin_register(GalleryCategoryModelAdmin) I can add the categories just fine, and they are displayed correctly in the admin dashboard Gallery page as checkboxes, but when I choose a certain category for some Media and then publish the page, all the categories check boxes that I checked are gone! Anyone knows why? -
Django3: accounts/password_reset does not use admin.site.site_header
I have an app main/ ├── asgi.py ├── celery.py ├── __init__.py ├── settings.py user/ ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── ... ├── models.py ├── tests.py ├── urls.py └── views.py In admin.py the admin page title is set like this: from django.contrib import admin admin.site.site_header = settings.HOME_TITLE Which works on localhost:8000/admin/. But http://localhost:8000/accounts/password_reset/ still shows the standard Django Administration title. Is there a way to change that consistently or would I have to create my own template for this? -
How to make this model?
I am creating a Calorie Log website using Django. One creates an account, and can start logging the amount of calories he consumed and burnt on a particular date, then it shows whether on that day he consumed or burnt more calories.The User can store frequently eaten food and frequent exercise that he does so that when he adds the data he can use that item class Food(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) food_name = models.CharField(max_length=50, null=True, blank=True) calories = models.IntegerField(null=True) food_pic = models.ImageField(default="default_food.jpg", null=True, blank=True) def __str__(self): return f"{self.food_name}" class Exercise(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) exercise_name = models.CharField(max_length=100, null=True, blank=True) calories = models.IntegerField(null=True) exercise_pic = models.ImageField(default="default_exercise.png", null=True, blank=True) def __str__(self): return f"{self.exercise_name}" Porblems > How do I make the model in which I can store the data of food eaten and exercises done on that particular day. I tried making a model and the creating its inlineformsets but it did'nt work, at this point it is very messy. The web page will compose of the section where user will be able to select a food item and the amount he consumed on that particular day. Same for the exercises, that data is what I want to store. I … -
Using Python Libraries in Django
invoice python script Hello! I would appreciate if someone could help me with a doubt I have about using Python libraries in Django. I will try to be as clear as possible so here it goes: In my job I work with invoices that are all saved in a specific directory (PDF files). In my job I am interested in only one specific value in a row which is a number. My job is to extract that value from all the invoices and sum them all. So, I made a python script in which I use the libraries Pandas, os and PDFplumber and it works great. In code.png, you can see the loop I use to extract the row and value that I want by using PDFplumber and then sum all these values. In invoice.png you can see how PDFplumber divides the invoice in rows and in columns. So, here is the thing: I want to deploy a Django App so that other people in the enterprise can use the python script I use ( they don't know anything about Python programming). So, I would want to deploy a Django app in which they can upload the directory with all … -
Unresolved attribute reference 'count' for class 'ManyToManyField'
Hey Guys i m stuck in pycharm 'models.py' def total_likes(self): return self.likes.count() pycharm is giving me 'Unresolved attribute reference 'count' for class 'ManyToManyField' this error what to do? -
Take my data from my computer and Verify that data is not stolen
As a Python programmer recently I received a small project to edit and add some functions. (the project is Python/Django) But while I was working on it, I noticed something unusual, which is the presence of some python libraries(hashlib and others), which can take my data(Gmail accounts, passwords, chrome bookmarks . . .) from the computer. This Script is an example from the code. import hashlib import logging import re import pandas as pd from file import reader logger = logging.getLogger(__name__) def load_data(user_id, project_id, columns: dict): group_files = {} df = pd.DataFrame(None) for id_, column in columns.items(): group = column['group'] if group not in group_files: df_file = reader.load_file(user_id, project_id, group) group_files[group] = df_file if group_files[group] is not None: if column['content'] in group_files[group].columns: df[column['content']] = group_files[group][column['content']] return df def get_hash(string: str): return hashlib.md5(string.encode()).hexdigest()[:5] My question is: How can I know if they are taking my data from the computer or not? Thanks in Advance. -
django-filter and django-tables2 only show rows were boolean = true
I've been trying to figure out how to only show rows in my table where a column value is set to true using Django-filter and Django-tables2 but I can't seem to get the code working. I am able to generate the table and generate the filters, but depending on who is signed into the app, I only want to show records where an 'is_reviewed' column is set to true. I thought I had it working using the following line in my views.py file but then discovered it was not applying the filter at all to my queryset: # only show scenarios that have been reviewed and published, or scenarios that the user submitted. # self.table_data = self.table_data.filter(Q(is_reviewed=True) | Q(submitter = request.user)).order_by("-id") https://github.com/alexandroidii/cst8333 This is what I have so far: Views.py class FilteredScenarioListView(SingleTableMixin, FilterView): model = Scenario template_name = "rlcs/scenario_list.html" table_pagination = {'per_page': 5} ordering = '-id' def get(self, request, *args, **kwargs): is_reviewer = request.user.groups.filter(name='reviewer').exists() or request.user.is_superuser if is_reviewer: self.table_class = ReviewerScenarioTable self.form_class = ReviewerScenarioFilterForm self.filterset_class = ReviewerScenarioFilter elif request.user.is_authenticated: self.table_class = SubmitterScenarioTable # only show scenarios that have been reviewed and published, or scenarios that the user submitted. # self.table_data = self.table_data.filter(Q(is_reviewed=True) | Q(submitter = request.user)).order_by("-id") self.form_class = SubmitterScenarioFilterForm self.filterset_class … -
Django Bad Request (400) Debug=False
I'm trying to publish my site, i configured all settings (nginx & gunicorn) This settings works well DEBUG=True ALLOWED_HOSTS = ['localhost','127.0.0.1','domain.com','www.domain.com'] However, when i edit the DEBUG=True to False DEBUG=False i got this error on browser Bad Request (400) i also tried these setttings ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['domain.com','www.domain.com'] (before posting this question i checked this answer Django gives Bad Request (400) when DEBUG = False ) -
Form Validation Method for Class-based form views
I hope you guys could tell me how to use validation methods in my forms.py for a single field. My view is a generic.FormView and my form is forms.Form. Here is my view: class ClassSetupView(OrganisorAndLoginRequiredMixin, generic.FormView): template_name = "leads/class_setup.html" form_class = ClassSetupForm def get_success_url(self): return reverse("class-setup-sucess-page") def form_valid(self, form): # Some Other Code return super(ClassSetupView, self).form_valid(form) Here is my form: class ClassSetupForm(forms.Form): date = forms.DateField(help_text="Year-01-01",) I read some other websites that show an example of their form validation as: class RenewBookForm(forms.Form): renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") def clean_renewal_date(self): data = self.cleaned_data['renewal_date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data The website's example has a view that is a function and not a class-based view(FormView) like mine. This method seems pretty simple and straightforward to me. However, I don't know if I can use clean_date(self): for my form, since I have …