Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inject varaible from html to views.py in Django 2?
I tried some ways but none worked. Button should scrape weather from city typed in the text box. All scraping works when i hardcode city name but i don't know how to get that city name from html form to views.py. Thanks or help! html <form method="POST "action="{% url 'weather' %}"> {% csrf_token %} <input type="text" value="{{ city }}"> <button type="submit" class="btn btn-info">Get my weather</button> </form> views.py def scrape_weather(request): old_weather = Weather.objects.all() old_weather.delete() api_adress = "http://api.openweathermap.org/data/2.5/weather?q=" api_key = "&appid=3a99cf24b53d85f4afad6cafe99d3a34" city = input() #city = "warsaw" url = api_adress + city + api_key json_data = requests.get(url).json() new_weather = json_data['weather'][0]['main'] degree_kelvin = int(json_data['main']['temp']) degree = degree_kelvin-273 pressure = json_data['main']['pressure'] new_weather = Weather() new_weather.degree = degree new_weather.pressure = pressure new_weather.weather = new_weather new_weather.save() if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): pass else: form = CityForm() return render(request, "news/home.html", {'form': form}) forms.py from django import forms class CityForm(forms.Form): city = forms.CharField(max_length=30) if not city: raise forms.ValidationError('You have to write something!') -
Passing arguments to dispatch methods
I am relatively new to Python and Django. I am parsing Excel sheets and want to store the data in a DB (MySQL). The information in which table the data is stored is available through the Excel sheet. I'd like to use a dispatch table to decide which Object is stored. The fields needed can vary. I found something that I hoped would work, but unfortunately does not: python: dispatch method with string input func_name_dict = { 'Assay': Assay.objects.get_or_create() } def dispatch(name, *args, **kwargs): return func_name_dict[name](**kwargs) dispatch('Assay', 'name='ChIP-Seq') I would hope that the new object would get stored or fetched and returned to the caller. What seems to happen is that the 3 existing DB records (which all have a different name) are fetched: website.models.MultipleObjectsReturned: get() returned more than one Assay -- it returned 3! -
How to view ads that belong to user, but be able to add a user without ads?
So I am learning the django rest framework and have a simple setup. I have a user model and ads model setup that relationallly mapped to echother. I have the viewset setup when I search up users I can see the ads that are associated with that user. The problem is, when I go to add a user it is requiring that I have enter in ads. I want to be able to add new users without ads associated to them. Here is my UserSerializer class UserSerializer(serializers.ModelSerializer): ads = AdSerializer(many=True, allow_null=True) class Meta: model = User fields = ('username', 'email', 'password', 'ads') extra_kwargs = { 'password': { 'write_only': True }, 'ads': { 'read_only': True } } As you can see I tried adding allow_null and read_only but it still sayds ads cant be blank when adding a new user. Any obvious thing I am missing? Thanks -
migracion erronea ... no se porque me arroga el siguiente error ... ayuda pliss
Dentro del desarrollo de mi aplicación, no puedo aplicar la migración de datos de la base de datos a modo local. Ya he aplicado makemigrations a la app correspondiente y migrate. Ademas he borrado la migración anterior y de todas maneras me arroja el mismo error, espero que me puedan dar alguna información adicional -
Iterate and format dictionary returned by template filter
I'm trying to display metadata about an image in my Django app. The metadata is read from the image's exif header and stored in a dictionary with the image as a key, and returned to the template with a filter. In my template, I display the images, and would like to display the formatted metadata for that image. So far I can only get it to display the dictionary for that image (e.g. {'key1': 'value', 'key2', 'value'}). I would like it to look like key1: value, key2: value. #template.html {% block content %} {% for image in images %} {{ exif|get_item:image }} <p><img src="{{ image.image.url }}" width="500" style="padding-bottom:50px"/></p> {% endfor %} {% endblock %} #views.py def image_display(request): images = image.objects.all() exif = {} for file in images: cmd = 'exiftool ' + str(file.image.url) + ' -DateTimeOriginal -Artist' exifResults = (subprocess.check_output(cmd)).decode('utf8').strip('\r\n') exif[file] = dict(map(str.strip, re.split(':\s+', i)) for i in exifResults.strip().splitlines() if i.startswith('')) context = { 'images': images, 'exif': exif, } @register.filter def get_item(dictionary, key): return dictionary.get(key) return render(request, 'image_display.html', context=context) I thought I could just do {% for key, value in exif|get_item:image.items %} in the template, but that returns an error: VariableDoesNotExist at /reader/image_display Failed lookup for key [items] in <image: … -
Import Error when trying to import models from custom app
I have a django project and I am trying to import a model from my app website to my App_2. That is more or less my folder structure: website website app1 models.py views.py .... app2 models.py views.py .... Now, in my views.py (App2) I'd like to import a method from models.py (app1). The following problems occur: When trying from app1 import models ModuleNotFoundError: No module named 'heatbeat_website.analytics' When trying 'from website.app1 import models' ValueError: attempted relative import beyond top-level package When trying `from ..app1 import models`` ValueError: attempted relative import beyond top-level package So relative and absolute imports fail... I have the feeling I am overlooking something. Any help is appreciated, thank you. -
module 'django.contrib.auth.views' has no attribute 'login'
I run : python manage.py migrate and have this error I assume that for this version of Django you need to rewrite the code, but I don’t understand how. DJANGO 2.2 module 'django.contrib.auth.views' has no attribute 'login' I assume that for this version of Django you need to rewrite the code, but I don’t understand how. Here is my code: File url.py [from django.conf.urls import url, include from django.contrib import admin from KisEats3app import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings urlpatterns = \[ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), Restaurant url(r'^restaurant/sign-in/$', auth_views.login, {'template_name': 'restaurant/sign_in.html'}, name = 'restaurant-sign-in'), url(r'^restaurant/sign-out', auth_views.logout, {'next_page': '/'}, name = 'restaurant-sign-out'), url(r'^restaurant/sign-up', views.restaurant_sign_up, name = 'restaurant-sign-up'), url(r'^restaurant/$', views.restaurant_home, name = 'restaurant-home'), Sign In/ Sign Up/ Sign Out url(r'^api/social/', include('rest_framework_social_oauth2.urls')), /convert-token (sign in/ sign up) /revoke-token (sign out) \] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)][1] -
How to add records from an HTML table data taken from a table model into another table model?
First at all something about me... I'm just a beginner Python and Django developer, so I'm learning and applying what I have learned in my real work project. The problem I'm building an small Pharmacy Management Application for the hospital where I work and I want to make there a medicines availability tracklist where doctors can check if a medicene is available or not in order they can write patient prescriptions. What I have been done? I have a table model for the National Drugs Formulary (Formulario Nacional de Medicamentos), the complete list of all drugs and pharmacologic products used in my country (Cuba) described in my Django models.py as: class FarmMedicamento(models.Model): meddesc = models.CharField(max_length=250) presentacion = models.ForeignKey(FarmPresentacion, models.DO_NOTHING) forma_presentacion = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return ("%s - %s %s" % (self.meddesc, str(self.presentacion).upper(), self.forma_presentacion)) def propiedad_colname(self): return ("%s - %s %s" % (self.meddesc, str(self.presentacion).upper(), self.forma_presentacion)) propiedad_colname.short_description = 'Medicamento' columna_medicamento = property(propiedad_colname) class Meta: managed = False db_table = 'farm_medicamento' verbose_name = "Medicamento" verbose_name_plural = 'Medicamentos' I store the medicine availability in another table model described as: class FarmExistencia(models.Model): medid = models.OneToOneField(FarmMedicamento, models.DO_NOTHING, primary_key=True, verbose_name="Medicamento") disponible = models.BooleanField("Disponible") actualizado = models.DateTimeField(auto_now=True) class Meta: managed = True db_table = 'farm_existencia' verbose_name … -
How to set Email field as lookup_field in DRF?
I need user-detail url endpoint as api/email/user@gmail.com; api/email/user2@gmail.com, but it not works If i add url field to serialiser class, then on user-list page i have exeption: Could not resolve URL for hyperlinked relationship using view name "user-email". You may have failed to include the related model in your API, or incorrectly configured thelookup_fieldattribute on this field. Thats my code: serializers.py class EmailSerializer(serializers.ModelSerializer): """ Профиль пользователя """ class Meta: model = User fields = ('url', 'email', ) read_only_fields = ('email', ) extra_kwargs = { 'url': {'view_name': 'user-email', 'lookup_field': 'email'} } views.py class RetrieveModelViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """ действия просмотр """ pass class EmailViewSet(RetrieveModelViewSet): queryset = User.objects.all() serializer_class = EmailSerializer lookup_field = 'email' urls.py router.register(r'email', views.EmailViewSet, 'email') Also i try clean email field by quote_plus: serializers.py from urllib.parse import quote_plus class EmailSerializer(serializers.ModelSerializer): """ Профиль пользователя """ email = quote_plus(serializers.EmailField(read_only=True)) class Meta: model = User fields = ('url', 'email', ) read_only_fields = ('email', ) extra_kwargs = { 'url': {'view_name': 'user-email', 'lookup_field': 'email'} } but i have error: TypeError: quote_from_bytes() expected bytes -
Django Error in Search Filed in One to Many Relationship - Related Field got invalid lookup: icontains
How can we initiate Multi User Project Management System in Django Framework Balaji Shetty 10:29 PM (0 minutes ago) High Can anyone please suggest me how can we initiate Multi User Project Management System> Scenarios is Like For Example, Suppose we have to develop University management System Level One- University Principal as Super User Level 2 - University May have N Department like Engg, Medical, Pharmacy, Accounting, ....... N Dept Level 3- There are sublevels under every Level like Engineering will have All Engineering Branches like CS, CE, IT , EXTC, MECH, PROD ...... Same is true for other Departments. Level 4 - Same thing get repeated recursively repeated as in Level 3, in Subsequent Level. And User Hierarchy is From TOP to Bottom means Top user can see all Sub Level in Down Section But Bottom user cannot see in TOP section. Most Important Thing is User in One Level May transfer his load to user in another Same Level and We have to keep the log of Every User with respective Task. Can you please suggest me the best way to accomplish the project because User May have many to Many Relationship with Departments also. -
Is it possible to override the error message that Django shows for UniqueConstraint error? (IntegrityError)
Using UniqueConstraint on multiple fields and it is working properly, but I want to override the error message. Have gone through many postings, some of them quite dated, and none seem to specify how to override this particular instance. (IntegrityError) Fields are User and Skill Group. I would like error message to simply say "Skill Group already in use." It currently reads "Skill group with this User and Skill group already exists." Thanks. -
CSRF verification failed. Request aborted when calling Password Reset API with Angular
I am trying to create password reset api using Django Rest Framework and Angular 6. But when I try to do POST call to the password reset url I am receiving error saying "CSRF verification failed. Request aborted" my url.py file includes: url(r'password-reset/', auth_views.PasswordResetView.as_view()), url(r'password-reset/done/', auth_views.PasswordResetDoneView.as_view()), url(r'password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view()), url(r'password_reset_complete/',auth_views.PasswordResetCompleteView.as_view()) For the front end I am using Angular as follows: my forgot-password.html includes: <navbar></navbar> <div class="container-fluid px-xl-5"> <section class="py-5"> <div class="row"> <div class="col-lg-12 mb-5"> <div class="card"> <div class="card-header" style="text-align: center;"> <h3 class="h6 text-uppercase mb-0">RESET PASSWORD FORM</h3> </div> <div class="card-body"> <form class="form-horizontal" #forgotPassword="ngForm"> <div class="form-group row"> <label class="col-md-3 form-control-label">Email Address</label> <div class="col-md-6"> <input class="validate" #email="ngModel" [(ngModel)]="input.email" name= "email" type="email" placeholder="Email Address" class="form-control" [pattern]="emailpattern" required> <div class="alert alert-danger" *ngIf="email.touched && !email.valid">Email is required!</div> </div> </div> <div class="line"></div> <div class="alert alert-success" *ngIf="successMessage">{{ successMessage }}</div> <div class="alert alert-danger" *ngIf="errorMessage">{{ errorMessage }}</div> <div class="form-group row"> <label class="col-md-3 form-control-label"><a routerLink="/login">Back to Login</a></label> <div class="col-md-12" style="text-align: center;"> <button (click)="submitEmail()" type="submit" class="btn btn-primary shadow" [disabled]="!forgotPassword.valid">Send Reset Link</button> </div> </div> </form> </div> </div> </div> </div> </section> </div> and forgot-password.ts file is as follow: import { Component, OnInit } from '@angular/core'; import { UsersService } from 'src/app/services/users.service'; @Component({ selector: 'app-forgot-password', templateUrl: './forgot-password.component.html', styleUrls: ['./forgot-password.component.scss'], providers: [UsersService] }) export class ForgotPasswordComponent implements … -
How to fix `Forbidden` status code in Django Rest Framework app
I am trying to implement the login feature in my Django Rest Framework application. I met with a problem that DRF returns "Forbidden" status code even if the view is opened for everyone. I added decorators @api_view and @permission_classes and tried to change their order /breakdown/views.py @api_view(['GET', 'POST', ]) @permission_classes((permissions.AllowAny,)) def sign_in(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) username = body['username'] password = body['password'] print(username, password) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) res = JsonResponse({"data": "1"}) return Response("Success", status=HTTP_STATUS_OK) else: print("Error. Disabled account") return Response("Disabled account", status=410) else: print("invalid login") return Response("Invalid login", status=400) breakdown/urls.py urlpatterns = [ path('user/surveys', survey.get_list_of_surveys), path('users/authenticate', sign_in), ] src/_services/user.sevice.js function login(username, password) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username, password}) }; console.log(requestOptions); return fetch(`http://127.0.0.1:8000/users/authenticate`, requestOptions) .then(handleResponse) .then(user => { if (user.token) { localStorage.setItem('user', JSON.stringify(user)); } return user; }); } GitHub link: https://github.com/Jlo6CTEP/students_breakdown/tree/mir_trud_may I was expected to redirect to the main page that got Forbidden message and a current page was not change. -
staticmethods with django webservice - unexpected behavior. Should create only 1 instance (singleton)
@staticmethod in django is not working. static method should be executed only one. However, for testing I made 3 calls in parallel, and static method was called 3 times. Following is the code and output: Code: class KafkaReceiver: _kafka_consumer = None def __init__(self, topic): KafkaReceiver._kafka_consumer = self.create_only_one_consumer() @staticmethod def create_only_one_consumer(): if KafkaReceiver._kafka_consumer is None: KafkaReceiver._kafka_consumer = KafkaConsumer(KafkaReceiver._topic) print("Consumer Created......") return KafkaReceiver._kafka_consumer Output: Consumer Created...... Consumer Created...... Consumer Created...... Parallel call code: r1 = grequests.get('http://localhost:5014/message/?message=hello', callback=do_something)#, hooks = {'response' : do_something}) r2 = grequests.get('http://localhost:5014/message/?message=helloworld', callback=do_something)#, hooks = {'response' : do_something}) r3 = grequests.get('http://localhost:5014/message/?message=hellothere', callback=do_something)#, hooks = {'response' : do_something}) grequests.map([r1, r2, r3]) What is expected: For each call to django webservice, django creates (I think) a new thread. However, the class here should not create instance of consumer. Is it a lock issue (I tried lock and RLock, it is not working with django) Second strange thing is on further django calls this static method is not executing. -
What are the options for ways to get Data for my project?
I'm creating a Django project that shows various music festival related info (something like this). The problem that I need data for the database. As you can imagine information regarding festivals is constantly changing and from comes many sources. For this reason I'm trying to think of some way to populate the database without updating festival lineups manually everyday. As I couldn't find any API to use, I tried using BeautifulSoup (user press a button in Django admin site, triggering the scraping process), but a lot of festival websites uses Ajax to populate parts of the DOM. So I wonder, maybe there are better solutions? I would appreciate if anyone would provide ideas/best practices/documentation to read for similar case like this. Thanks. -
How to fix "Django_Jalali" utcoffset(dt) in django models?
I'm using django_jalali as Persian calendar into my Django project and I wanted to add auto_now_add and auto_add for created_at and updated_at variables that hold time. When I add a post from Django admin it will apply correctly with no problem but when I want to update the post it will crash by utcoffset(dt) argument must be a datetime instance or None, not datetime error I tried to remove all and use default argument in jmodels of django_jalali but it will crash the same as above Here it is my Post model: from django_jalali.db import models as jmodels created_at = jmodels.jDateTimeField(auto_now_add=True) updated_at = jmodels.jDateTimeField(auto_now=True) I should tell again that it works first time fine and hold the date correctly but when I save the post again it will crash by the bellow error Request Method: GET Request URL: http://127.0.0.1/admin/post/post/6/change/ Django Version: 2.2 Exception Type: TypeError Exception Value: utcoffset(dt) argument must be a datetime instance or None, not datetime Exception Location: \env\lib\site-packages\jdatetime\__init__.py in utcoffset, line 1220 -
Order of Django Queryset results
I'm having trouble understanding why a Queryset is being returned in the order it is. We have authors listed for articles and those get stored in a ManyToMany table called: articlepage_authors We need to be able to pick, on an article by article basis, what order they are returned and displayed in. For example, article with id 44918 has authors 13752 (‘Lee Bodding’) and 13751 (‘Mark Lee’). I called these in the shell which returns : Out[6]: <QuerySet [<User: Mark Lee (MarkLee@uss778.net)>, <User: Lee Bodding (LeeBodding@uss778.net)>]> Calling this in postgres: SELECT * FROM articlepage_authors; shows that user Lee Bodding id=13752 is stored first in the table. id | articlepage_id | user_id -----+----------------+--------- 1 | 44508 | 7781 2 | 44508 | 7775 3 | 44514 | 17240 …. 465 | 44916 | 17171 468 | 44918 | 13752 469 | 44918 | 13751 No matter what I try e.g. deleting the authors, adding ‘Lee Bodding’, saving the article, then adding ‘Mark Lee’, and vice versa – I can still only get a query set which returns ‘Mark Lee’ first. I am not sure how else to debug this. One solution would be to add another field which defines the order … -
Django and React
I haven't been able to locate anything saying one way or the other, but does anyone know if you can have function based views in django and have react as your frontend? No use of templates. If so, would it look like this? # fad index route def fad_index(request): context = {'fads': Fad.objects.all()} return render(request, 'fad/fad_index.html', context) But instead of fad_index.html, would it just be the route that you want it to take in react? -
Django raises ConnectionResetError: [Errno 104] Connection reset by peer when i want to render video in template
I just want to show video in template. I searched in google about this error, but nothing was about django, it didn't helped me. (everything is okey with URLs etc. so it isn't that simple issue. That's why i provide only template. I suppose it's something with server configuration after research). Here's the code: home.html {% extends 'base_template.html' %} {% block content %} <h1> Welcome to the home jd! </h1> <form action = "{% url 'home' %}" method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} {{ message }} <input type = "submit" value = "add new track"> </form> <h1>Your tracks!</h1> {% for track in tracks %} <ul style="list-style: none;" > <h3> {{ track.title }} </h3> <img src="{{ track.miniature.url }}" style="max-width: 200px"> <li> Created at: {{ track.created_at }} <li/> <li> updated_at: {{ track.updated_at }} <li/> <li> Description: {{ track.description }} <li/> {{ track.audio_or_video.url }} <video src = "{{ track.audio_or_video.url }}" controls></video> </ul> {% endfor %} {% endblock %} Error log from terminal (It's showed a lot of times cause i have loop in my code, so catch important part): <pre>During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/usr/lib/python3.6/socketserver.py&quot;, line 651, in process_request_thread … -
Django - Image won't display
I'm trying to make images load by getting the src from an object within a model but all I get is the default output for an image that can't be found. I'm loading static in the base.html file so all I'm showing below is the image tag in profile.html as that's the only thing relevant from it. Models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images') Profile.html <img class="rounded-circle account-img" src="{{user.profile.profilephoto.url}}" style="min-width: 400px; min-height: 400px"> urls.py for project from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('reviewApp.urls')), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Views.py @login_required def profile(request): return render(request, 'users/profile.html') File Structure Output -
How should I implement reCaptcha v3 if my front and backend live on different domains?
I have several websites (SPAs), each one running on it's own domain. All these SPAs use the same API, which is hosted on another domain. I'd like to implement reCaptcha v3 on my SPAs, but I'm not really sure how exactly the entire validation process would work. Who would be in charge of receiving the callback from Google's service? If the backend, how does the frontend validate itself to the backend? The SPAs are made with Vue and the backend is a Django app with Django Rest Framework. The backend is stateless, so there are no cookies. -
Django TestCase subCase message not displaying
I am running a test using TestCase.subTest but the message is not being displayed in the console. I'm using PyCharm 2018 with Django-tests run/debug configuration Code to the test is this class ViewTest(TestCase): fixtures = ['users', 'contacts'] test_200_urls = [ ("user-detail", resolve_url('user-detail', 1)), ("contact-detail pk: 5", resolve_url('contact-detail', 5)), ("address-detail pk: 2", resolve_url('address-detail', 2)), ] def setUp(self): self.client_stub = Client() def test_views_200(self): for test in self.test_200_urls: name, url = test with self.subTest(name): response = self.client_stub.get(url) self.assertEquals(response.status_code, 200) Running this returns only Failure Traceback (most recent call File (...), line 30, in test_views_200 self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 Destroying test database for alias 'default'... -
ORM Query with multiple LEFT joins
Toy example: Let's say I have the following models: class Person(models.Model) name = models.CharField(max_length=100) lives_in = models.ForeignKey('City', on_delete=models.CASCADE) class City(models.Model) name = models.CharField(max_length=100) part_of = models.ForeignKey('State', on_delete=models.CASCADE) class State(models.Model): name = models.CharField(max_length=100) # Person ---lives_in--> City ---part_of---> State How do I get a list of people who live in a particular state using Django ORM? In regular SQL, it be something like SELECT p.* FROM person p LEFT JOIN city c ON (p.lives_in = c.id) LEFT JOIN state s ON (c.part_of = s.id) WHERE c.name = 'MA' -
Django Page not found (404) polls:detail url issue
While at Django tutorial, it asks us to tweak the view to generic views. Post that, I am able to click on my question "What's up" at index.html but it leads to a page not found error. Below is the code: urls.py(for polls) from django.urls import path from . import views app_name='polls' urlpatterns= [ #ex: /polls/ path('',views.IndexView.as_view(),name='index'), #ex: /polls/5/ path('<int:pk>/',views.DetailView.as_view(),name='detail'), #ex: /polls/5/results/ path('<int:pk>/results/',views.ResultsView.as_view(),name='results'), #ex: /polls/5/vote/ path('<int:question_id>/vote/',views.vote,name='vote'), ] index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} views.py from django.shortcuts import render,get_object_or_404 from django.http import Http404,HttpResponseRedirect from django.urls import reverse from django.views import generic # Create your views here. #from django.http import HttpResponse from django.template import loader from .models import Question, Choice class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' When I click on the link "What's up?" at index.html, it leads me to the following error: Page not … -
How to Write data into one excel files using DataFrame
I am writing a Django app. I have two functions in view.py and each function store the data into DataFrame. I wan to store them in one Excel file. How should i do that?