Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to search for the object of a foreign key django
I am creating an Task Completion Queue where people create Projects then add Posts to that specific Project, kind of like comments on a blog post. I am creating a detail view for the Project model, and I want to search all of the posts using the Project as a parameter because I only want posts that pertain to that specific Project. The problem is I cant figure out how to use the model currently being used as a search parameter in a Detail view Here's my models.py class MyProjects(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=140) class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() project = models.ForeignKey(MyProjects, on_delete=models.CASCADE, null=True, default=None) And here is my views.py class ProjectView(DetailView): model = MyProjects def get_context_data(self, **kwargs): CurrentProject = get_object_or_404(MyProjects, title=self.kwargs['MyProjects']) completed = Post.objects.filter(status='Completed', project= CurrentProject) inProgress = Post.objects.filter(status='InProgress', project= CurrentProject) posts = Post.objects.filter(project= CurrentProject) Features = Post.objects.filter(ticket_type='Features', project= CurrentProject) context = super().get_context_data(**kwargs) context['posts '] = posts context['Features '] = Features context['completed '] = completed context['inProgress '] = inProgress context['projects'] = projects return context -
I want to change product name in Django/admin panel. So that it will show the product name instead of "Product object (number)" [duplicate]
How can I change the product name from Django pannel so that it will show me a particular product name instead of showing just a number as it shows in below attached screenshot. It will help a lot as same product name has been used in the 'Order_item' module as well. model.py from django.db import models from django.contrib.auth.models import User from phone_field import PhoneField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = PhoneField(blank=True,E164_only=False, help_text='Contact phone number') def __self__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() detail = models.CharField(max_length=500, null=True) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null= True, blank= True) def __self__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = "" return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_order = models.DateTimeField(auto_now_add = True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __self__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) … -
Django App interacts with outside models.py
├── API #app │ ├── apps.py │ ├── models.py # models.py inside 'API' app, we aim to not use this. │ ├── serializer.py │ └── views.py ├── __init__.py ├── MY_PROJECT #Project │ ├── asgi.py │ ├── settings.py │ ├── SUB_FOLDER │ │ ├── conn │ │ │ ├── sqlDatabase.py │ │ │ └── static_data.py │ │ ├── MODELS_FODLER │ │ └── models.py # models.py inside the root project, USE THIS. │ ├── urls.py │ └── wsgi.py ├── manage.py Currently, we are doing a Django project called 'MY_PROJECT'. Somewhere in the root folder, we create a models.py to connect to our MySQL on Google Cloud (CloudSQL). We create an app called 'API' to, as the name suggests, expose our end for the world to interact with our database. However, I'm not really sure how to make the API interact with models.py in 'MY_PROJECT' instead of the models.py in 'API'. -
How to pass in value from a text box to this function and have it print the output out on html page?
So basically I have a text box and button and I want to be able to enter text into the textbox which will pass to the text to the WebOutput object and then I want to print those results from the function to the HTML page. Is this possible? Here is some code to get a better understanding. The function that I want to be able to pass in my text from the textbox to. As you can see the object takes user input which would be the text I enter into the textbox. DatabaseInteractor.py def match_tweet_for_website(self): output= WebOutput.WebOutput(input("Enter Tweet ")) print(output.impWords) info = ', '.join(output.impWords) self.cursor = self.connection.cursor(buffered=True) print(', '.join(output.impWords)) query= f"SELECT DISTINCT company_name FROM CompanyKeywords where keyword IN ({info})" self.cursor.execute(query,(info)) result = self.cursor.fetchall() print(result) index.html Code for basic text box and submit button <form action="/external/" method="post"> Input Text: <input type="text" name="param" required<br><br> <br><br> <input type="submit" value="Check tweet"> </form> url.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.output), ] views.py from django.shortcuts import render from subprocess import run, PIPE import sys def output(request): return render(request,'index.html') -
code coverage is high for zero test cases
I have a simple Django app that doesn't contain any test cases and I tried to get the test coverage using coverage. The result was surprising, coverage run --omit '*.virtual_env/*' ./manage.py test && coverage report System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Name Stmts Miss Cover -------------------------------------------------- django2x/__init__.py 0 0 100% django2x/settings.py 20 0 100% django2x/urls.py 7 2 71% manage.py 12 2 83% music/__init__.py 0 0 100% music/admin/__init__.py 1 0 100% music/admin/actions.py 6 2 67% music/admin/filters.py 12 5 58% music/admin/model_admin.py 13 0 100% music/admin/register.py 7 0 100% music/filters.py 7 0 100% music/forms.py 6 0 100% music/migrations/__init__.py 0 0 100% music/models.py 28 4 86% music/pagination.py 3 0 100% music/serializers.py 54 18 67% music/tests.py 1 0 100% music/urls.py 9 0 100% music/views.py 30 1 97% -------------------------------------------------- TOTAL 216 34 84% Why I have got 84% test coverage from zero tests? -
Django appending %20 to URL causing 404 error
I am having an issue with pagination during filtering/ordering when I try to go to page 2. The URL Django is creating when going to page #2: https://example.com/accounts/?page=2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&q=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&ordering=-date_joined Pagination looks like this: <a class="btn btn-default mb-4 m-1" href="?page=1{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"> First</a> <a class="btn btn-default mb-4 m-1" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}"> Previous</a> View: class AccountStatusListView(AccountSearchMixin, ListView): model = Employee template_name = 'employees/account_list.html' paginate_by = 15 def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', '-is_active') return ordering def get_queryset(self, *args, **kwargs): queryset = super(AccountStatusListView, self).get_queryset() queryset = queryset.filter(Q( supervisor__exact=self.request.user)) | queryset.filter(Q( supervisor__isnull=False)) | queryset.filter(Q( is_active__exact=False)) ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset -
How to fix "object of type 'NewsletterUser' has no len()" error for a Newsletter app in Django
I have created a new Newsletter to send emails when status is Published but I keep getting TypeError at /control/newsletter/ object of type 'NewsletterUser' has no len() Because of this error probably I am not receiving the emails I don't know what is the reason for this error and how to fix it, I have selected an email but still Here is the models.py: class Newsletter(models.Model): EMAIL_STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) subject = models.CharField(max_length=250) body = models.TextField() email = models.ManyToManyField(NewsletterUser) status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) def __str__(self): return self.subject Here is the views.py def control_newsletter(request): form = NewsletterCreationForm(request.POST or None) if form.is_valid(): instance = form.save() newsletter = Newsletter.objects.get(id=instance.id) if newsletter.status == "Published": subject = newsletter.subject body = newsletter.body from_email = settings.EMAIL_HOST_USER for email in newsletter.email.all(): send_mail(subject=subject, from_email=from_email, recipient_list=[ <----- error this line email], message=body, fail_silently=False) context = { "form": form, } template = 'control_newsletter.html' return render(request, template, context) here is the urls.py from newsletters.views import control_newsletter, control_newsletter_list, control_newsletter_detail, control_newsletter_edit, control_newsletter_delete app_name = 'newsletters' urlpatterns = [ path('newsletter/', control_newsletter, name="control_newsletter"), -
subprocess used in python django does not working when django was host in IIS
I have using the subprocess package in my django web, when i run local on server or publish using apache, it work without causeing any issue BUT when I host my django web on IIS, this subprocess does not work. Below is my subprocess code: files = subprocess.check_output("dir /b " + path, shell=True).decode() p_pcat=subprocess.Popen(['java', '-cp', str(PARSER_JAR), 'parsePCAT.ParsePCAT', str(pcat_file_name)],stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) This both function not working when hosting at IIS (version 10.0.14393.0), anyone have idea on this? -
Password expiry django-user-accounts not work
I have followed the instructions django user accounts. However I have a problem with the password expiry and password history. I have been setup to 60 seconds for password expiry but nothing happens for the new sign up user. Did I miss something ? Thanks -
access file from static folder with template tags inside javascript code
appreciate if anyone can help. I have a app which creates file location from submit button - json_path = os.path.join('json', request.POST['submit'], '.json' ) This gives the file location under \static\json\ folder. I am sending this using dictionary to template render_dict = { 'json_path':json_path, } Inside javascript, I have following - map.addSource('locationData', { type: 'geojson', data: "location of the json file needs to be provided here" }); can anybody suggest if this can be done through template taging? -
django + jquery Ajax + CORS = empty JSON response sent to server
I'm running my webapp on another domain via an iframe. This page can produce ajax POST called to the db. When these happen, the variables that I'm passing to the view that processes the ajax arrive empty (or not at all). When I run the ajax call, there are no errors. In other words, I don't beleive this is related to Csrf token as I'm passing that into the ajax view. I was previously getting errors related to the CSFR token, but I think I've resolved that. No, the ajax view just fails silently by not passing the required data back to the server. In trying to get this setup, I've done the following: 1) I'm including the csrf_token on the data I'm sending to my backend via ajax. 'csrfmiddlewaretoken': '{{ csrf_token }}', 2) I've installed django-cors-headers and set CORS_ORIGIN_ALLOW_ALL = True in settings.py 3) I've set CSRF_COOKIE_SAMESITE = None in settings.py 4) I've got the following standard code to support ajax requests $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie … -
How to setup Django every time you use it? (i.e. using **source bin/activate** and ** python manage.py runserver**)
I am a beginner with Django, and I am very confused as to how to consistently setup Django everytime you are opening a new terminal. Whenever I do so, I have to always restart and do the following: Change directory (cd) to my trydjango directory where I start the virtual environment (source bin/activate) After the terminal has the automatic (trydjango) at the furthest left of (trydjango) ismodes-MacBook-Air:trydjango ismodes$ I know that I have the virtual environment enabled. Then, I go to the src directory through the terminal where I enter python manage.py runserver I am running into consistent errors (e.g. AttributeError) whenever I enter the runserver step (step 3). Am I doing something wrong? The following is the full Traceback of the error (trydjango) ismodes-MacBook-Air:src ismodes$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d5a6b90> Traceback (most recent call last): File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/ismodes/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Django Query Values from a List of names
Is it possible to do a query from a list (or string) of desired values in Django? v = ['a', 'b', 'c'] // or could be a sting like v = '"a","b","c" qs = Data.objects.all().values ( v ) I am getting errors like: AttributeError: 'list' object has no attribute 'split' Thank you. -
Django: add records to multiple tables via one ModelForm (or Form?)
When I update the data in the Project table using ProjectForm, I need to write the changes to the Log table. As I understand it, I need to use Form instead of ModelForm. How can I implement this? -
Django Key Error - Passing Data Through Session
I am printing the below list: manifestData = form2.cleaned_data print(manifestData) the output of that is: [{'ProductCode': <Product: 1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: 2>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}] Then in my view I have the below. I am trying to pass this variable through session data but I have to make the ProductCode JSON serializable...: product = data.pop('ProductCode') When the above line runs, I get a KeyError which states "Exception Value: ProductCode". Full traceback below. Any thoughts on how I can resolve this? Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/quote/ Django Version: 1.11.29 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Poseidon', 'crispy_forms'] 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: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/andrews/Desktop/WBU2/Poseidon/views.py" in QuoteView 639. product = data.pop('ProductCode') Exception Type: KeyError at /create/quote/ Exception Value: 'ProductCode' -
Really weird behaviour when running a function, coding it in shell works, importing the function doesn't
I have no idea what's happening here. ​ I have a class that looks something like, ​ class Scrape: def __init__(self, session, headers, proxies): self.session = session self.headers = headers self.proxies = proxies self.response = None def post(self, url): self.response = self.session.post(url, headers=self.headers, proxies=self.proxies, verify=False) def get(self, url): self.response = self.session.get(url, headers=self.headers, proxies=self.proxies, verify=False) Then I have this function in another file, import requests from .config import * from .scraper import Scrape from .serializer import * import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def run(): scrape = Scrape(requests.session(), headers, PROXIES) scrape.post(url) save = [] for obj in scrape.parse_response(): ....... Now this works perfectly in my development environment, but when I deploy it, I get this. urllib3.connection.HTTPConnection object at 0x7f69ccf34710>: Failed to establish a new connection: [Errno 110] Connection timed out',))) Now at first I thought my server had whitelists and stuff, BUT if I do this, In [10]: from bots.roku.config import * In [11]: import requests In [12]: r = requests.session().post(url, headers, PROXIES) In [13]: r Out[13]: <Response [200]> IT WORKS? This doesn't though, In [5]: import requests In [6]: scrape = Scrape(requests.Session(), headers, PROXIES) In [7]: scrape Out[7]: <bots.roku.scraper.Scrape at 0x7f69ccfaff60> In [8]: scrape.get("http:\\www.google.com") ProxyError: HTTPConnectionPool(host='170.130.63.178', port=8800): Max retries exceeded with url: http://www.google.com/ … -
Best way to render HTML to PDF in Django site
I have pretty complicated css in my HTML and I tried to render it to PDF using xhtml2pdf but it does not support my css. So I tried to use reportLab but then it might take times because I have to do the design all over again (also I'm not sure how can I insert my fetch data from db into the pdf using it). So in my case what is the best way to render HTML to PDF in Django ? -
Django foreign key form
I have two models Order and a date model. Order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.date = date_instance order.save() context = { 'order':order,'form':form } else: … -
Preventing users writing foul language in the comment section
I don't want users to be able publish offensive comments on my posts. I know a way of censoring out s***, f***, c*** etc. But if you apply a blanket ban to offensive words then you may unintentionally end up banning a word such as Scunthorpe (a place in the UK) because it contains an offensive substring. In forms.py I want to set the comment active property to false if the comment potentially contains an offensive word. Therefore I could manually check any potentially controversial posts. models.py class Comment(models.Model): #The foreign key is linked to the ID field in the Post model #id = models.IntegerField(primary_key=True, blank=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') nameid = models.ForeignKey(User,on_delete=models.CASCADE,related_name='commentsid') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=True) forms.py I have tried setting active to false in at least 4 different ways but have so far had no luck. Does anyone have any suggestions? def clean_body(self): body = self.cleaned_data.get("body") if "f***" in body or "s***" in body : self.data['active'] = False self.fields['active'].initial = False self.cleaned_data.get("active")=False form.fields['active'].initial = False return body -
Django Does Not Detect Tests Ran 0 tests in 0.000s
I run the python manage.py test and also tried app specific tests for my app blog but it is not detected. Is there an error in my test.py? I don't know why the tests are not being detected. from django.contrib.auth import get_user_model from django.test import Client, TestCase from django.urls import reverse from .models import Post class BlogTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='testuser', email='test@email.com', password='secret' ) self.post = Post.objects.create( title='A good title', body='Nice body content', author=self.user, ) def test_string_representation(self): post = Post(title='A sample title') self.assertEqual(str(post), post.title) def test_post_content(self): self.assertEqual(f'{self.post.title}', 'A good title') self.assertEqual(f'{self.post.author}', 'testuser') self.assertEqual(f'{self.post.body}', 'Nice body content') def test_post_list_view(self): response = self.client.get(reverse('home')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Nice body content') self.assertTemplateUsed(response, 'home.html') def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000/') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') -
Saleor production deploy
Im trying to deploy a saleor instance on my local network, but im having trouble accesing it if im not in the localhost, storefront shows no pictures, but Network Error: failed to fetch, i cant log in either, dasboard shows unespected error and don't log in My common.env file is in the attached photo -
im having trouble Django materialize css form when a render the form i get the variable does not exist from field.html from django-materializecss-form
I'm new to Django. whenever I render the form I get "Exception has occurred: VariableDoesNotExist Failed lookup for key [required_css_class] in " . I don't understand this error if anybody explain or tell me what I'm doing wrong will be much appreciated thank you in advance this is my view def considerations(request): if request.method == "POST": form = B2bConsideration(request.POST) v = form.is_valid() if form.is_valid(): instance = form.save(commit=True) #adding date to instance from request not in table but a good idea #instance.date = request.date instance.save() return HttpResponseRedirect(reverse('b2b:TypeOfTitle')) else: return HttpResponse(form.errors) else: form = B2bConsideration() return render(request, 'b2b/B2B_notes.html',{'form':form} ) this is my modelform class B2bConsideration(ModelForm): CHOICES = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),] under_name_title = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Consideration fields = ['under_name_title','salvage_title','is_title_paidoff'] this is my model under_Name_choices = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),] salvage_title_choices =[('yes_salvage_title','yes'),('no_salvage_title','no'),] is_title_paidoff_choices = [('yes_title_paidoff', 'yes'),('no_title_paidoff','no'),] class Consideration (models.Model): under_name_title = models.CharField(max_length=21, choices=under_Name_choices) salvage_title = models.CharField(max_length=18, choices=salvage_title_choices) is_title_paidoff = models.CharField(max_length=21, choices=is_title_paidoff_choices) here is where the error points to. this is what it said "Exception has occurred: VariableDoesNotExist Failed lookup for key [required_css_class] in " <label class="control-label {{ classes.label }} {% if field.field.required %}{{ form.required_css_class }}{% endif %}">{{ field.label }}</label> this is my HTML {% load static %} {% load materializecss %} <!DOCTYPE HTML> … -
how to include html file in another to avoid repeating code?
I code with django and when I am working with django template, I do the below to avoide repeating code. I illustrate it with an example: Suppose I have two pages in my website: 1) home 2) about In django I code as below: I first build a base.html : <!DOCTYPE html> <html> <head> </head> <body> <h1>this is my site</h1> {% block body %}{% endblock body %} </body> </html> I then build home.html: {% extends 'base.html' %} {% block body %} <h2>This is home</h2> {% endblock body %} I talso build about.html: {% extends 'base.html' %} {% block body %} <h2>This is about</h2> {% endblock body %} I now want to do the same without having a backend. I have a static website. How can I do the same without having a backend like django or php, etc. -
AttributeError: module 'pages.views' has no attribute 'home_view'
I was following a beginner's Django tutorial word-for-word creating a project called 'Pages' when all of a sudden my computer gave me an error (AttributeError) when I tried to access the localhost page (http://127.0.0.1:8000/) that was supposed to say 'Hello World.' Instead of seeing the statement, a 'This site can’t be reached' page was there. I am completely confused as to why this happened because I was following the instructor word-for-word yet got a different result. If anyone can help that would be very much appreciated! Here are my files views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home_view(*args, **kwargs): # args, kwargs return HttpResponse("<h1>Hello World</h1>") # string of HTML code urls.py """trydjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin … -
Cross origin ajax requests with iframe resulting in 403 error
I'm attempting to run my webapp on another domain via an iframe. I'm using jquery ajax POST requests to my server with this webapp. I'm getting the following error: Forbidden (403) CSRF verification failed. Request aborted. So far, I've taken the following steps: 1) I'm including the csrf_token on the data I'm sending to my backend via ajax. 'csrfmiddlewaretoken': '{{ csrf_token }}', 2) I've installed django-cors-headers and: - added the middleware to the top of my list of middleware ('corsheaders.middleware.CorsMiddleware',), - added 'corsheaders' to the list of installed apps - set the following variable in my settings: CORS_ORIGIN_ALLOW_ALL = True 3) I've got the following code running to support ajax requests $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) …