Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count every hit with django-hitcount
Is there a way to make Django hitcount module count every hit? Currently, it counts once for a single IP but I want it to every hit. How can I achieve this? -
django getting values from form
I need to filter the table by column and value, nothing better comes to my mind (I'm new in django) view def get_queryset(self): column = self.request.GET.get('column') condition = self.request.GET.get('condition') queryset = Table.objects.all() if condition == 'contains' and column == 'title': queryset = Table.objects.filter( title__icontains=self.request.GET.get('title') ) elif condition == 'greater' and column == 'quantity': queryset = Table.objects.filter(quantity__gt=self.request.GET.get('title')) elif condition == 'greater' and column == 'distance': queryset = Table.objects.filter(distance__gt=self.request.GET.get('title')) elif condition == 'lower' and column == 'quantity': queryset = Table.objects.filter(quantity__lt=self.request.GET.get('title')) elif condition == 'lower' and column == 'distance': queryset = Table.objects.filter(distance__lt=self.request.GET.get('title')) elif condition == 'equals' and column == 'quantity': queryset = Table.objects.filter(quantity__exact=self.request.GET.get('title')) elif condition == 'equals' and column == 'distance': queryset = Table.objects.filter(distance__exact=self.request.GET.get('title')) return queryset i knew it looks like **** please give me more elegant idea) there my table the idea is as follows, the user selects a column and the condition by which the table will be filtered thanks -
try to implement the live search by using django and AJAX
I am new to the Django and AJAX. I am trying to implement "live search" function by using django framework and the AJAX. This function will search the applications by using the name. The application model has its title. Then user can use search bar to make live search, which will show up results when you type the title. However, I did not figure out how it works. Hopefully someone can give me a hint. It will be appreciated if someone can help. JQuery $('document').ready(function(){ $('#search').keyup(function(e){ let csrftoken = '{{ csrf_token }}'; $.ajax({ type : 'POST', headers:{'X-CSRFToken':csrftoken}, url: "{% url 'search' %}", data: { 'search_text': $('#search').val() }, success: function(data){ console.log(data); $('html').load(data); } }); }); }); View.py @login_required(login_url='login') @allowed_users(allowed_roles=['student']) def search(request): data = dict() if request.method == "POST": search_text = request.POST["search_text"] if search_text is not None: applications = Application.objects.filter(user=request.user, title=search_text) data['result'] = applications print(data) return JsonResponse(data) However, in the view.py , the "data" cannot print out Also, is there another way to pass "applications" to the HTML and update the webpage? Since this code does not work for the live search -
django can't reverse match url from template
I ma having difficulty reverse matching a url, getting the error: NoReverseMatch at /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ Reverse for 'treatment_detail' with no arguments not found. 1 pattern(s) tried: ['patient/(?P<patient_id>[^/]+)/$'] The url is: /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ (the string is the 'apatient_id' and changes each time the user submits the 'add' page) urls.py is app_name = "patient" urlpatterns = [ path( route='add/', view=views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] html <form action="{% url 'patient:treatment_detail' %}" method="get"> <input type="submit" class="btn btn-primary" value="get_doc" name="get_doc"> </form> views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context If I have 'patient:patient_add' instead of 'patient:treatment_detail' it works fine so the issue seems to be about the route="<patient_id>"/ In urls.py -
Django-Filter Nested Serializer MultipleObjectsReturned
I have created an drf app and which includes nested relations. enter image description here As shown below I put the relations in my parent serializer.Then I am using it as an list and retrieve method supported by modelviewset enter image description here -
Django Filter on Distinct with orderby created at
How can I filter with distinct and order by IncomingCallRecording.objects.filter( ).order_by("lead_id","-created_at").distinct("lead_id") Problem Order by is not working with created at Is there an alternative solution that might help -
OSError('Tunnel connection failed: 403 Forbidden')))
Am trying to initiate a request to an API (https://theteller.net/documentation#theTeller_Standard) but i keep getting this error. The idea is that will take details of the user and pass it to my views.py to send a request to to make payment and be redirected back to my website. This is the error ProxyError at /vote/test/robert-yenji/ HTTPSConnectionPool(host='test.theteller.net', port=443): Max retries exceeded with url: /checkout/initiate (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden'))) this is my code views.py def nomination_payView(request, slug): if request.method == 'GET': model = get_object_or_404(Nomination, slug=slug) template_name = 'Payment.html' context = { 'nomination': model } return render(request, 'Payment.html', context) elif request.method == 'POST': amount = (str(int(request.POST['amount']) * 0.5) + '0').replace('.', '') zeros = '0' * (12 - len(amount)) amount = zeros + amount email = request.POST['email'] desc = request.POST['desc'] url = 'https://test.theteller.net/checkout/initiate' transaction_id = random.randint(100000000000, 999999999999) data = { "merchant_id": "TTM-00000740", "transaction_id": transaction_id, "amount": amount, "redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}", "apiuser": "halotech5d525bfd6ead3", "API_Key": "ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=", "email": email, # you would need to change this to the actual users email "desc": desc, # this as well... } encoded = base64.b64encode( b'halotech5d525bfd6ead3:ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers).json() … -
Django date field enable/ highlight only certain dates
My files are as below : Forms.py class FilterDaywiseNew(forms.Form): search_Day = forms.DateField(widget=NumberInput(attrs={'type': 'date'}),required=True,initial=datetime.date.today) Views.py def DayWiseFilterPage(request): form = FilterDaywiseNew() return render(request, 'agelist.html',{'form': form}) agelist.html <form method="post" action="SearchDisplay" id="searchFilterForm"> <div class="form-row"> <div class="col-md-8 mb-0"> {{ form.search_Day|as_crispy_field }} </div> </div> </form> My rendered html is like this <div id="div_id_search_Day" class="form-group"> <label for="id_search_Day" class=" requiredField"> Search day<span class="asteriskField">*</span> </label> I have a bunch of dates, that I would want to populate the datefield with, so that only these dates are enabled/ highlighted/ can be selected, like this Solutions given use JQuery to do this. I dont want to use JQuery. Is there a way this can be achieved? Thanks, -
Case insensitive search doesn't work on Django (Postgres) with non-latin characters
PostgreSQL 13.4 Django 3.2 MacOS 11.2 I try to implement a search function for finding a model instance by the "name" field. models.py class LatestConfiguration(models.Model): # Primary key name = models.CharField(verbose_name='Имя', max_length=150, unique=True, primary_key=True) Database encoding is UTF8: ➜ ~ psql <DB_NAME> -c 'SHOW SERVER_ENCODING' server_encoding ----------------- UTF8 (1 row) Database contains records, eg: Бухгалтерия для Казахстана, редакция 3.0 I try to search a model instance like that: LatestConfiguration.objects.filter(name__icontains='Бух') the output is ok: >>> LatestConfiguration.objects.filter(name__icontains='Бух') <QuerySet [Бухгалтерия для Казахстана, редакция 3.0]> I lower-cased the first letter in 'Бух' to 'бух' and repeated the search >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> so now I get an empty queryset but I shouldn't I also tried Q-objects: Q(name__istartswith='бух') but didn't get any results Tried to use postgres full text search by adding: 'django.contrib.postgres', to INSTALLED_APPS in settings.py and repeated searching this way: >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> Anyone else got the same error? -
Heroku can't load my css file because its a mimetype
I deployed my website it all works and main css loaded but for some reason my another css refusing to load in the console it say Refused to apply style from '......' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. This is my setting.py Am i missing something ? MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR / 'media', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp') -
how to write django view testcases that use regex
i have my url patterns in regex format see below two examples re_path(r'^all/labwork$', av.all_labwork, name='all-labwork'), re_path(r'^patient/labwork/(?P[0-9A-Za-z-]+)/$', av.new_labwork, name='labwork') I am trying to write testcases to test them, just need a little direction to get started for example a testcase 'HomePageTest' class HomePageTests(TestCase): def test_home_page_status_code(self): response = self.client.get('labwork/')) self.assertEquals(response.status_code, 200) The issue is the arguement 'labwork/' passed to client.get() above will not work with the urlpatterns i have used, in normal conditions the routes all work, i figure i have to pass a regex into the get function. help needed and appreciated -
django settings default time zone
here is a question i can use django time zone for utc and it worked fine but when i switch the default time zone to 'Asia/Tehran' it wont work and i get the error ValueError: Incorrect timezone setting: ASIA/TEHRAN the actual code in settings.py is: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True and it is on django time zone list i checked it the system is ubuntu 20 and django version is 3.2 -
How can I integrate React Template Folder with Django Project
I bought a template for my news & magazine website and website maked With django. So I want to integrate react folder and app in my django project. How can I do it? This is template Folder Structure -
Generate Django Model Fields
I want to add the field according to the type chosen. Suppose if I choose Charfield I want to have option name as Char and if DateFied is chosen I want to have a Date field in my model. Is is possible to do it in Django? class Options(models.Model): TYPE= ( ('Charfield','Charfield'), ('Integerfield','Integerfield'), ('Datefield','Datefield'), ) optiontype = models.CharField(max_length=20, choices=TYPE) optionname= models.CharField(max_length=50) -
How to automate Django - React app deployment
I have Django as backend and React as frontend, my current deployment process is I use WinSCP to transfer react build to django backend and then with Putty I use python manage.py collectstatic. Then I update git repo at aws, do migrations (if any) manually. I want to automate this in way that There is no need to build and copy react to backend also not to pull current repo changes or use WinSCP or Putty etc. I just want simple script or any standard way by which, whenever I update code in my production branch at backend and frontend, deployment will be done automatically. Pls suggest me the way. TIA -
meta tags shows in <body> While Should be placed in the <head>
I have a website based on the django framework. I want to add meta tags to the website With conditions : """Definition of models.""" from django.db import models class Pages_Meta(models.Model): Page_name = models.TextField(null=False) Page_meta = models.TextField(null=False) page_title = models.TextField(null=False) And html page is: <html> <head> <title> {{ title }} - Farhad Dorod </title> {{ meta }} </head> </html> <body> ... </body> And urls.py is: path('index/', LoginView.as_view( template_name='app/index.html', extra_context= { 'title': Pages_Meta.objects.get(id = 1).page_title, 'meta' : Pages_Meta.objects.get(id = 1).Page_meta, }), name='index') result: all meta tags shows in body While Should be placed in the head enter image description here -
Django does not redirect after receiving POST request
After taking google credentials through POST request, I want Django to log the user in and redirect to home page from google.auth import jwt def google_login(request): if request.method == "POST": credential = request.body profile_info = jwt.decode(credential, verify = False) email = profile_info["email"] user = User.objects.filter(email = email) if user: login(request, user.first()) print("---------------login success") return HttpResponseRedirect(reverse("index")) else: return render(request, "network/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "network/login.html") login success is printed but the page is not redirected nor refresh. The terminal doesn't show much ---------------login success [22/Sep/2021 16:05:59] "POST /google_login HTTP/1.1" 302 0 [22/Sep/2021 16:05:59] "GET / HTTP/1.1" 200 13957 [22/Sep/2021 16:06:03] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 [22/Sep/2021 16:06:10] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 My code in the front end is liked this const csrftoken = Cookies.get('csrftoken'); function handleCredentialResponse(response) { fetch(`/google_login`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, body: response.credential }) } -
getting button to perform function in django
I am wanting webpage where the user clicks a button to produce a word document. Currently, however, when the user clicks the button, the page simply reloads and appends '?get_doc=get_doc#' to the url. Instead I would like a prompt for the user to download the generated document urls.py app_name = "patient" urlpatterns = [ path('add/', views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context def get_doc(request): print('running9') # if(request.GET.get('get_doc')): if 'get_doc' in request.GET: print('running') document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # Prepare document for download # ----------------------------- f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response html {% extends "base.html" %} <!-- {% block title %}Patient: {{ patient.name }}{% endblock %} --> {% block content … -
Django: Dependency on swappable model (lazy reference)
Disclaimer, I have read the following posts, and they did not provide a helpful answer for my case: lazy reference: doesn't provide model user? django custom user model gives me lazy reference error django-swappable-models I have written a reusable app that handels authentication methods and user management. In its core, it overrides the AUTH_USER_MODEL (lets call the model CustomUser and provides a swappable model Person, which has O2O field to a CustomUser: class CustomUser(AbstractUser): def save(self, *args, **kwargs): if not self.pk or hasattr(self, 'person') is False: super().save(*args, **kwargs) get_person_model().objects.create(birthdate=None, user=self) else: super().save(*args, **kwargs) class AbstractPerson(models.Model): user = models.OneToOneField(settings.MY_APP_PERSON_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='person') birthdate = DateField(null=True, default=None) class Meta: abstract = True class Person(AbstractPerson): class Meta(AbstractPerson.Meta): swappable = 'REUSABLE_APP_PERSON_MODEL' To create the migrations in my reusable app, I have setup a "dummy" django project which includes this app, and sets REUSABLE_APP_PERSON_MODEL to reusable_app.Person. This works flawlessly, in my real django project, I can set REUSABLE_APP_PERSON_MODEL to a model that inherits from reusable_app.AbstractPerson. The problem arises, when my reusable app has another model that holds a foreign key to REUSABLE_APP_PERSON_MODEL: class Invite(models.Model): email = models.EmailField() person = models.OneToOneField(settings.REUSABLE_APP_PERSON_MODEL, on_delete=models.CASCADE, null=False, related_name='+') code = models.CharField(max_length=5) Again, I created a migration for this model … -
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead python django template error how to fix
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead. this is my code: views.py: from django.shortcuts import render from django.http import HttpResponse def home_page(request): # return HttpResponse('Hello world') render(request, 'leads/home_page.html') and here's the urls.py: from django.contrib import admin from django.urls import path from leads.views import home_page urlpatterns = [ path('admin/', admin.site.urls), path('', home_page), ] and here's the template: -
How to handle multiple Django forms in a request.POST
Let's say I have a form that contains the following values after I submit the form: print(request.POST): <QueryDict: {'csrfmiddlewaretoken': ['3oveeCkYroBwKNSLw8wOr8dtURYGcO9AtOKYfPoNbf8q3L5Az7aEAnJaQldYmnaG'], 'user': ['1'], 'reset': ['false'], 'project': ['100001'], 'contents': ['test'], 'amount': ['3'], 'currency': ['JPY'], 'expense_date': ['09/22/2021'], 'store_company_client_name': ['test'], 'expense_category': ['Staffing payments'], 'note': ['fdv']}> What if I have multiple inputs and I get a request.POST like this: <QueryDict: {'csrfmiddlewaretoken': ['xbdRWXh4LdKTTJoCMJa7O53lApbY03byXBsBXalTv4hNcHBrPIOXXkz2wTqgaCcE'], 'user': ['1','1','1'], 'expense_date': ['09/22/2021', '09/21/2021', '09/20/2021'], 'project': ['100001', '100002', '100002'], 'expense_category': ['Staffing payments', 'Staffing payments', 'Staffing payments'], 'expense_type': ['Salaries', 'Salaries', 'Salaries'], 'contents': ['test', 'test', 'test'], 'currency': ['1', '1', '1'], 'amount': ['12', '1', '4'], 'store_company_client_name': ['customer1', 'customer2', 'customer3'], 'note': ['lorem ipsum', 'lorem ipsum', 'lorem ipsum']}> How can I process it in the back-end? Right now for a simple form I have this view: def new_expense(request): data = { 'title': "New Expense", } data['projects'] = Project.objects.filter(is_visible=True).values('id') data['expense_category'] = dict((y, x) for x, y in EXPENSE_CATEGORY) data['expense_type'] = dict((y, x) for x, y in EXPENSE_TYPE) form = ExpenseForm() if request.method == "POST": print(request.POST) reset = request.POST['reset'] form = ExpenseForm(request.POST) if form.is_valid(): form.save() if reset == 'true': form = ExpenseForm() data['form'] = form return render(request, "expense/new_expense.html", data) And I want to create a new view capable of doing exactly the same thing as new_expense but just for … -
How to display data in model formset for foreign key to manytomanyfield as readonly text with prefilled data that passes validation?
I have a problem displaying data in a form as readonly text. My model: class SalesPlan(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT) date = models.DateField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.RESTRICT) quantity = models.FloatField(default=0) My form: class SalesPlanForm(forms.ModelForm): # product = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'})) class Meta: model = SalesPlan fields = '__all__' widgets = { 'customer': forms.HiddenInput(), 'date': forms.HiddenInput(), } The form in prefilled with initial data and this works fine for input and save of the formset. Problem is, users can change product, since it is a dropdown of their portfolio and I want to change that behavior. Customer class: class Customer(models.Model): code = models.CharField(max_length=6, primary_key=True, unique=True) name = models.CharField(max_length=100) belongs_to_sales_channel = models.ForeignKey(SalesChannel, on_delete=models.RESTRICT) portfolio = models.ManyToManyField(Product) date_created = models.DateTimeField(auto_now_add=True, null=True) If I uncomment the product in SalesPlanForm, I display correct data, but the form does not save with error: ValueError at /sales/create/100022/2028/1/1/ Cannot assign "'product_1'": "SalesPlan.product" must be a "Product" instance. Notice the DOUBLE quotes and SINGLE quotes for variable. If I insted assign widget for 'product' in the dict in Meta, I can save the form, but data displayed in rendered form is just 1, 2, 3, 4 for every form in formset instead of product object name. Is there a way … -
Conflicting 'news' models in application 'articles': <class 'articles.models.news.News'> and <class 'apps.articles.models.news.News'
I have my django apps inside apps folder. Due to multiple article types I decided to split my models.py for the articles app and put it inside the models folder where each modelname.py file points to a model. Problem: configuring syndication framework (as described in https://docs.djangoproject.com/en/3.2/ref/contrib/syndication/) causes a runtime error Conflicting 'news' models in application 'articles': <class 'articles.models.news.News'> and <class 'apps.articles.models.news.News'>. Note: Before adding syndication framework functionality everything works just fine. I tried: Adding app_label to the News model. apps folder structure: ├── articles │ ├── admin.py │ ├── apps.py │ ├── feeds.py │ ├── __init__.py │ ├── models │ │ ├── __init__.py │ │ ├── articles.py │ │ ├── categories.py │ │ ├── news.py │ │ ├── reviews.py │ │ └── tags.py │ ├── tests.py │ ├── urls.py │ └── views │ ├── __init__.py │ ├── news.py ├── conftest.py ├── education ├── __init__.py ├── users /apps/articles/models/news.py: from django.db import models class News(models.Model): // // Model Fields // class Meta: ... app_label = 'articles' ... def __str__(self): return self.title def get_absolute_url(self): return reverse("articles:news_detail", kwargs={"slug": self.slug}) /apps/articles/feeds.py: from django.contrib.syndication.views import Feed from django.utils.translation import gettext_lazy as _ from .models.news import News class NewsEntriesFeed(Feed): title = _("News") link = "/news/" description = … -
Invalid Django formset
I have a django formset, when I enter just one row of data it works. If I try to enter two or more rows of data, when I submit the form I get the error: ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. Reading similar questions it seems missing the management_form but in my code is present..any ideas? This is my code: models.py and forms.py #models.py from django.db import models class Station(models.Model): id_station = models.IntegerField(blank=False) station_name = models.CharField(max_length=30, blank=False) unity_name = models.CharField(blank=False, max_length=10) id_sensor = models.IntegerField(blank=False) sensor_name = models.CharField(max_length=50, blank=False) class Meta: db_table = 'station' def __str__(self): return self.name # forms.py from django import forms from .models import Station from django.forms import formset_factory class StationForm(forms.Form): id_station = forms.IntegerField(label='id della stazione') #, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Book Name here'})) station_name = forms.CharField(label='nome stazione', max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome stazione'})) unity_name = forms.CharField(label='nome unita', max_length=10, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome unita'})) id_sensor = forms.IntegerField(label='id sensore') sensor_name = forms.CharField(label='nome sensore', max_length=50, widget=forms.TextInput(attrs={'placeholder': 'nome sensore'})) StationFormset = formset_factory(StationForm, extra=1) views.py from django.template import RequestContext from django.shortcuts import render, redirect from .forms import StationFormset from .models import Station def new_station(request): context = RequestContext(request) template_name = 'station.html' heading_message = 'Add a new … -
'function' object has no attribute 'lastname' [duplicate]
I Couldnot Resolve this problem please help me. Whenever I try to fetch data it always show this message views.py `from django.http import request from django.shortcuts import render from .models import * # Create your views here. def Profile(request): mydata = PersonalDetail.objects.all mycskill = CoddingSkills.objects.all wskill = AdditionalSkill.objects.all print(mydata.lastname) return render(request,'index.html', {'mydata':mydata,'mycskill':mycskill,'wskill':wskill})` admin.py from Efolio.settings import DATABASES from django.db.models.base import Model from django.db.models.fields import CharField from django.db import models # Create your models here. class PersonalDetail(models.Model): fistname = CharField(max_length=100) lastname = models.CharField(max_length=100) age = models.CharField(max_length=3) designaton = models.CharField(max_length=300) aboutme = models.CharField(max_length=100) addressfrom = models.CharField(max_length=300) addressnow= models.CharField(max_length=300) gender = models.CharField(max_length=20)` *Plz I AM STUCK HER HELP ME *