Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting "type object 'About' has no attribute 'objects'"
I am new to Django and I am making a search bar and which I added the logic in views.py, it threw this error "type object 'About' has no attribute 'objects'" I can't figure out why from django.views.generic import TemplateView, ListView, DetailView from .models import About #views class Home(ListView): """docstring for Home""" template_name = 'home.html' model = About recents = About.objects.all() context_object_name = 'recents' class BiographyDetail(DetailView): """docstring for BiographyDetail""" model = About template_name = 'details.html' class About(TemplateView): """docstring for BiographyDetail""" template_name = 'about.html' model = About class Contacts(TemplateView): """docstring for BiographyDetail""" template_name = 'contact.html' model = About class Projects(TemplateView): """docstring for BiographyDetail""" template_name = 'projects.html' model = About class Search(ListView): """docstring for BiographyDetail""" template_name = 'search.html' model = About def get_queryset(self): # new query = self.request.GET.get('search') searches = About.objects.filter( Q(name__icontains=query) ) return searches This is my models.py folder #models.py from django.db import models from django.utils import timezone import datetime # Create your models here. TYPE = ( ('politician','POLITICIAN'), ('poet','POET'), ('author','AUTHOR'), ('actor','ACTOR'), ) class About(models.Model): name = models.CharField(max_length = 200, default ='') quote = models.CharField(max_length = 200, default ='') born = models.DateField(verbose_name = 'Born on', null = True) born_at = models.CharField(max_length = 200, default ='') died = models.DateField(verbose_name = 'Born on', … -
Unable to include a template in a child template in Django
I have a layout.html where I am setting the general layout for my project and then for each page I want to render different HTML based on the layout.html For my home page I want to render a slider that provides a welcome message to the page, nice pictures etc, I only want this displayed on the home page. The issue I am having is that when I I have {% include "slider.html" %} on my layout.html, the slider renders fine, but when I move it to my home.html which extends layout.html the slider is not rendered. How can I do this so teh slider is only rendered when the user goes to home? home.html {% extends "layout.html" %} {% include "slider.html" %} {% block content %} <div class="container clearfix"> <div class="heading-block topmargin-lg center"> <h2>My super blog</h2> </div> </div> {% endblock %} layout.html {% load static %} <!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="SemiColonWeb" /> <!-- Stylesheets ============================================= --> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,400i,700|Raleway:300,400,500,600,700|Crete+Round:400i" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css" /> <link rel="stylesheet" href="{% static 'css/swiper.css' %}" type="text/css" /> <link rel="stylesheet" href="{% static 'css/dark.css' %}" … -
Svg files are not rendered in Vue Template using webpack_loader Django
I try to render svg files while coming from vue template in django when using webpack_loader but instead I get a console error: Unsafe attempt to load URL http://localhost:8080/img/icons.4d372dc7.svg from frame with URL http://localhost:8000/. Domains, protocols and ports must match. I try to render svg file in my vue template <svg class="olymp-magnifying-glass-icon"> <use xlink:href="../assets/svg-icons/magnifying-glass-icon.svg"></use> </svg> my vue.config.js I tried both with vue-svg-loader only protocol error is not shown but still the browser does not render svg: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://localhost:8080/", outputDir: './dist/', chainWebpack: config => { // const svgRule = config.module.rule('svg') // svgRule.uses.clear() // // add replacement loader(s) // svgRule // .use('vue-svg-loader') // .loader('vue-svg-loader') config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') .set('__MEDIA__', 'media') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://localhost:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) },}; how can I get my svg files rendered? Thanks -
Django rest filters aggregation
Here is my custom filter class class CarFilter(FilterSet): pickup_date = NumberFilter(method='filter_pickup_date_timestamp') dropoff_date = NumberFilter(method='filter_dropoff_date_timestamp') class Meta: model = Car fields = ['area_coverage', 'is_published', 'owner'] def filter_pickup_date_timestamp(self, queryset, name, value): pickup_date = datetime.fromtimestamp(float(value)) for car in queryset: if len(Reservation.objects.filter( dropoff_date__gte=pickup_date, is_active=True, item_type='car', item=car.item, )) > 0: return None return queryset.filter() def filter_dropoff_date_timestamp(self, queryset, name, value): dropoff_date = datetime.fromtimestamp(float(value)) for car in queryset: if len(Reservation.objects.filter( pickup_date__lte=dropoff_date, is_active=True, item_type='car', item=car.item, )) > 0: return None return queryset.filter() Is it possible to create such method, that will filter by both arguments pickup_date and dropoff_date? Because know I have to filter through Reservation model twice -
Python social-auth-django Authentication Cancelled error AuthCanceled on Instagram login
I a having the following error when attempting to authenticate via Instagram on my test Django application. I'm using social-auth-app-django. Originally, I had an error from Instagram upon logging in that said 'invalid scope', with an empty list. I solved this error by specifying in my settings.py file to ask for user profile in the scope: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'insta_auth', 'social_django', ] ##added from DigitalOcean article on social authentication AUTHENTICATION_BACKENDS = [ 'social_core.backends.instagram.InstagramOAuth2', 'django.contrib.auth.backends.ModelBackend', ] ##Facebook/Instagram AUTH SOCIAL_AUTH_INSTAGRAM_KEY = "2339011986402798" #Client ID SOCIAL_AUTH_INSTAGRAM_SECRET = "27ceda3a396eea1ad3d71a8e4fbab9ff" #Client SECRET SOCIAL_AUTH_INSTAGRAM_EXTRA_DATA = [('user', 'user'),] SOCIAL_AUTH_INSTAGRAM_AUTH_EXTRA_ARGUMENTS = {'scope': 'user_profile'} ##Disable authtication process cancelled error SOCIAL_AUTH_RAISE_EXCEPTIONS = False SOCIAL_AUTH_BACKEND_ERROR_URL = '/' ##Added from DigitalOcean article on social authentication ##Redirect URLS LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_URL = 'logout' LOGOUT_REDIRECT_URL = 'login' When the login link is clicked, it redirects to Instagram and shows the following page as expected: I click continue, and an Authentication process cancelled / AuthCanceled error message is displayed. Request Method: GET Request URL: https://www.mywebaddress.io/social-auth/complete/instagram/?code=AQBrKauQP5YweNo_2fvP6S-k9TeKKw0XaSgiVxWe9WAGvO3gxZhYacakB2tBG6Ytmcj-Zbsdm10Mjfw7HqmoF52Vg1QhdXLNYwwVcnGqj0EEDeh-aq5pgTW1m4KgbRBfQFSoa1jZfuKBb71YvJazaz82_bTaUtsgdmUCqY5aI0vxmS76pccNURmCwJRWAxTgUiInS5jvR30TjHxWD5zZDmVtlV5pDaZ7iubsyS3-58zwFA&state=ccQtV6QEV1Zu713qyDpFHPgNIWkItdqu Django Version: 3.0.6 Python Version: 3.7.3 Installed Applications: ['blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'insta_auth', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent … -
How can I convert a field in list in django template?
please anyone can help me ? How can I convert a field string to list ? I have a field called Size, it means that the field contains somthing as : "XXL, XL, X, SM". So I want to get something as : <form class="form-control" action="index.html" method="post"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="taille"> <label class="custom-control-label" for="taille">SM</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="size"> <label class="custom-control-label" for="size">XXl</label> </div> <div class="customenter code here-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="size"> <label class="custom-control-label" for="size">XL</label> </div> </form> What's your recommandations guys ? -
Auto submit Google Form via google Forms API and Google App scripts
I want users to answer google form quizzes through a third-party app. I want to set a timer to quiz and auto submit the Google form after the time limit exceeds. Is there a way to do via using Google Forms API & Google App scripts? -
How to push notification in django rest api for implementing it in mobile app?
I am working on django api project and kind of stucked in pushing notification can anyone give me idea how do i push notification by saving it into my database? For example, If a user followed another user then the followed user should be notified that he/she is being followed by certain user. -
Django + Gunicorn with gevent workers, with asyncio in the views
I have a django project, served by Gunicorn with gevent workers. In some views, I have to make two long running external calls. These are IO-bound class FooView(View): def post(self, request): slow_call_one() slow_call_two() do_some_work return HttpResponse(...) There is no reason for which these two slow calls cannot run concurrently. Would there be any issue with running these as asyncio co-routines? I'm asking mainly regarding the interplay between asyncio and the gevent gunicorn workers. My naïve understanding, based on the research that I've done is: asyncio allows single requests to finish more quickly, by not sitting and waiting for IO bound tasks gunicorn + gevent workers allow multiple requests to run 'concurrently' (I am aware that it's not true concurrency). My concerns are that gevent might already be transparently swapping to process a different request during the IO bound calls made by the original request, and that this might, at worst, screw up the process, or at best, not actually result in a performance improvement. -
Django doesn't put /media/ in front of image url outside of admin section
In the admin area of Django, the image is well served because django automatically puts '/media/' in front of the image url. But in the public part of my website, when I do this : <img class="card-img-top" src="{{ article.image_desc }}" alt="Card image cap"> The image is not. served because the url is not complete. How to easily fix this issue ? I could do this : <img class="card-img-top" src="/media/{{ article.image_desc }}" alt="Card image cap"> But it's not convenient at all. -
How to link using jinja in django with the {% url 'index' %}? Constant errors
After adding the jinja script I get a TypeError at line 0 The file about.html {% extends 'base.html' %} {% load static %} {% block content %} <section id="showcase-inner" class="py-5 text-white"> <div class="container"> <div class="row text-center"> <div class="col-md-12"> <h1 class="display-4">About BT Real Estate</h1> <p class="lead"> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur! </p> </div> </div> </div> </section> <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="**{% url 'index' %}**"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active">About</li> </ol> </nav> </div> </section> Error during template rendering In template C:\Users\Sam\Coding\Udemy\Python Django\btre_project\templates\base.html, error at line 0 'set' object is not reversible {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}" /> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" /> -
Ajax stuff are not running with Django Infinite Scroll
I have used this tutorial and implemented infinite scrolling in django and that loads the pages. However my Ajax calls are working only in first page load and are not working in consequent lazy loads. I have followed this answer to using $items.each.... block of code. But after using the above method, now the waypoint does not load the pages anymore and I am getting stuck on the first page itself(the Ajax call is working). Upon removing the code, the lazy loads is able to load consequent pages. I am using Bootstrap 4 with Django 3. Any suggestions? I am adding the script that's blocking the lazy load. <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); $items.each(function(){ $(this).find('.like').on('click', likecommentevent); } } }); </script> -
How to use filter in views.py in Django?
I'm building a hospital management system using Django. I want to create multiple users like doctor, patient and HR. But I'm not using the user authentication system provided by django. Instead I'm trying to create registration and Login forms simply using Html and bootstrap. I'm using a model.objects.filter() function to compare the input through forms and that of the database. But I'm getting desired result. This is my login function in views.py. def login(request): if request.method=="POST": user = request.POST.get('user', '') pass1 = request.POST.get('pass', '') val=request.POST.get('val','') if(val[0]=='Patient'): abc = Patient.objects.filter(username=user,password=pass1) n = len(abc) if n>0: print("hii") return HttpResponse("<h1>Invalid Credentials</h1>") else: return render(request, 'home/p_portal.html') else: efg =Doctor.objects.filter(username=user, password=pass1) if len(efg)==0: return HttpResponse("<h1>Invalid Credentials</h1>") else: return render(request, 'home/d_portal.html') return render(request, 'home/login.html') Login Form: <form method="post" onsubmit="return validate()" action="/home/login/">{% csrf_token %} <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="s1" value="Patient" name='val'> <label class="form-check-label" for="s1"> Patient </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" id="s2" value="Doctor" name='val'> <label class="form-check-label" for="s2"> Doctor </label> </div> </div> <div class="form-group col-md-6"> <label for="exampleInputEmail1">Username</label> <input type="text" class="form-control" id="exampleInputEmail1" name='user'> <!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>--> </div> <div class="form-group col-md-6"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="'pass"> </div> <button type="submit" class="btn btn-primary">Login</button> </form> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384- … -
How to recover files in git deleted via command git clean -xdf without any commits [duplicate]
I mistakenly have deleted all the files in the local repository via command git clean -xdf which did not commit for once since the creation. One of my codes was not working. It prompted me to use git clean -xdf. It removed all the files and my data. Is there any way to recover these? -
How to show foreignkey attributes django admin fields?
This question is similar with others but it is a different one actually ! So, I have 3 models such as (I have deleted some unnecessary things for shorter code): class Category(models.Model): category_title = models.CharField(max_length=200) category_content = models.TextField() category_slug = models.CharField(max_length=200) class Classes(models.Model): classes_title = models.CharField(max_length=200) classes_content = models.TextField() classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT) class Subjects(models.Model): subject_title = models.CharField(max_length=200) subject_content = models.TextField() subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT) So let me give an example. I can have 2 categories and in those categories I can have "same named" classes. Lets think about maths is a class for both categories. When I want to add a new subject to maths I see 2 same named maths in admin page. So I want to know which one belongs to which category in admin page. So I can add my subject to right class. class KonularAdmin(admin.ModelAdmin): fields = ('subject_title', 'subject_content', 'subject_class',) I have this in my admin page. What I want to add in fields something like subject.classes_category to just see which class belongs to which category. So is there a way for me to do it ? -
A django authentication ambiguity
The problem is ,i have a model structure like this:- from django.db import models from django.urls import reverse from django.contrib.auth.models import User import datetime from django.contrib.auth.base_user import AbstractBaseUser # Create your models here. class Doctor (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(blank=True , null=True) gender = models.CharField(max_length=1,blank=True , null=True) address = models.CharField(max_length=20,blank=True , null=True) department= models.CharField(max_length=10, blank=True, null= True) attendance = models.IntegerField(blank=True, null= True) salary = models.IntegerField(blank=True, null= True) status = models.CharField(max_length= 10,blank=True, null= True) def __str__(self): return self.user.username class Patient (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(blank=True , null=True) gender = models.CharField(max_length=1,blank=True , null=True) address = models.CharField(max_length=20,blank=True , null=True) blood_group = models.CharField(max_length=4,blank=True,null=True) #cases_paper = models.IntegerField(auto_created=True,editable=False) def __str__(self): return self.user.username class Receptionist (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return self.user.username class Hr (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return self.user.username class Appointments(models.Model): date = models.DateField() time = models.TimeField() doctor = models.ForeignKey(Doctor,on_delete=models.CASCADE,related_name='appointment_doctor') patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='appointement_patient') status = models.CharField(max_length=13) and i want to register a doctor or patient using single form with radio choice selection which i am successful with but how to log into a doctor if … -
Opening Django Application in Heroku: Code H10 "App crashed"
I'm following the Mozilla Developer tutorial for Django and am on the last section where we upload our "local library" app to Heroku. I'm running into difficulty when trying to open the website, after we push it to the Heroku server. I receive the following log messages: 2020-05-24T15:06:43.736333+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=rocky-wildwood-74309.herokuapp.com request_id=73f165da-1b27-4913-ad21-2389cc20c85d fwd="134.41.17.152" dyno= connect= service= status=503 bytes= protocol=https 2020-05-24T15:06:43.949773+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=rocky-wildwood-74309.herokuapp.com request_id=db8d9d2a-db63-417e-9230-90f1b7bec01e fwd="134.41.17.152" dyno= connect= service= status=503 bytes= protocol=https I've looked around at various answers and can't seem to find what the error is. It seems like the issues are commonly found in the Procfile and wsgi.py files but I'm not sure what changes I should make. I tried editing these files in a previous project directory and it only seemed to make things worse. I'll copy the code from these files below: Procfile web: gunicorn django_local_library.wsgi --log-file - wsgi.py """ WSGI config for locallibrary project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_local_library.settings') application = get_wsgi_application() requirements.txt appdirs==1.4.4 asgiref==3.2.7 distlib==0.3.0 dj-database-url==0.5.0 Django==3.0.6 filelock==3.0.12 gunicorn==20.0.4 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 … -
How to sent GET request with some parameters?
Can I see an address of a machine which sends a GET request to my web server (everything in the local network)? How can I send some data back to the same machine after receiving the GET request? [ ] <--- GET (with IP?)--- [ ] [ server ] [ machine ] [ ] ------- ANSWER ---> [ ] I use django. best, -
Django import-export how to handle blank Charfield
I'm trying to import some data with django import-export module. I'm having a problem and can't find any solutions to it despite the fact that it seems to be a very basic use of the import... I'm trying to import some CharFields. These fields are not mendatory and as recommended by Django community, they are defined with blank=True in my model but not null=True. Example: description = models.CharField(max_length=2000, blank=True ) The problem is simple: When I try to import this field with an empty value, I get the error "NOT NULL constraint failed" on that field. I don't understand how to solve this. Should I add null=True even if it's not usually recommended? Is there an option I don't know about? Thanks for your help. -
Search functionality in Django
I am working on a search functionality. I am trying to query multiple fields from database using django 3.0. Whenever I run the code I am getting 'No results found for: "" '. What could be wrong with my code? Here is my code: views.py def search(query=None): queryset = [] queries = query.split(" ") for q in queries: posts = AdPost.objects.filter( Q(category__icontains=q), Q(sub_category__icontains=q), Q(detail__icontains=q), ).distinct() for post in posts: queryset.append(post) return list(set(queryset)) def home(request): context = {} query = " " if request.GET: query = request.GET['q'] context['query'] = str(query) ad_posts = sorted(search(query), key=attrgetter('date_updated'), reverse=True) context['ad_posts'] = ad_posts user = request.user if not user.is_authenticated: return redirect('login') form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.author = user obj.save() form = PostForm() context['post_form'] = form return render(request, 'posts/home.html', context) home.html <div class="content"> {% if ad_posts %} {% for post in ad_posts %} <div> {% include 'snippets/post_link.html' with ad_post=post %} </div> {% endfor %} {% else %} <div> {% include 'snippets/post_link.html' with query=post %} </div> {% endif %} </div> snippets/post_link.html {% if ad_posts %} <div class="card"> <p><b>{{post.author.name}}</b> {{post.date_published}}</p> <p>{{post.detail}}</p> </div> {% else %} <div class="card"> <h4>No results found for: "{{query}}"</h4> </div> {% endif %} search form is located … -
why my user can't be authenticated after register,but can after login
I started an app named 'blogs' as a programming book required,when I finished the 'register' function which can register a user and login with it.I found that the user can be added to database normally,but it can't be authenticated.but when I used the username login normally,it can work!I checked my codes for many times,but I can't find the fault.Please give me some help,thank you very much! Here are my codes: users:views.py: def register(request): if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() authenticated_user = authenticate(username=new_user.username, password=request.POST['password1']) login(request,authenticated_user) return HttpResponseRedirect(reverse('blogs:index')) context = {'form':form} return render(request,'users/register.html',context) users:register.html: {% extends "blogs/base.html" %} {% block content %} <form method="post" action="{% url 'users:register' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">register</button> <input type="hidden" name="next" value="{% url 'blogs:index' %}" /> </form> {% endblock content %} blogs:base.html: Welcome to blog - {% if user.is_authenticated %} hello,{{ user.username }} - <a href="{% url 'users:log_out' %}">logout</a> {% else %} <a href="{% url 'users:register' %}">register - </a> <a href="{% url 'users:login' %}">login </a> {% endif %} {% block content %}{% endblock content %} -
How do I post data from a model unto a Django template if each field is different and needed at a different point of the template?
Essentially, I'm trying to find a way to pass the data within one of models to a template without using a for loop, like some of the other answers I've seen on here suggest. If it helps, here's a snippet of incorrect code that captures what I'm trying to do: {% extends "rollingStone/layout.html" %} {% block title %} A Record A Day {% endblock %} {% block body %} <div class = "container" id = "pageBody"> <div class = "row"> <h1 class = "rollingText">#{{entry.rank}}: {{entry.title}}</h1> </div> <div class = "row"> <div class = "col-sm"> <img src = "{{entry.cover }}" alt = "Single Cover"> </div> <div class = "col-sm"> <p> <strong>{{entry.releaseInfo}}</strong> <br> <br> <strong>Artist: </strong> {{entry.artist}} <br> <strong>Writer(s): </strong> {{entry.writer}} <br> <strong>Producer(s): </strong> {{entry.producers}} <br> {{entry.description}} </p> </div> </div> </div> {% endblock %} Where "entry" is just the name of whatever structure I'm using to pass the model's info to the template and the dot notation refers to the field within the model. The biggest issue I'm running into is that when I try and use the values() function to get data from an instance of my model, it returns a QuerySet which I'm not sure how to transfer to a … -
why request.GET.get() returns 'None' and value of html element is not visible in URL
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HELLO</title> </head> <body> <form action="/removepunc", method="get"> <input type="text",name='text' value="Hello,Django" /> <input type="submit"> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,'index.html') def removepunc(request): print("Text is :"+request.GET.get('text','default')) return HttpResponse("Hello") urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('removepunc',views.removepunc,name='rempunc') ] This is first screen after run the code When I click on submit in Url it did not show "hello django" Also in terminal it print default not "hello django" -
Adding a textbox and a combobox in Django CMS
I've just started using Django CMS so my understanding of the tool is very limited, but I've been trying to do something that I assumed would be very simple, yet, I couldn't find a way of doing it. I'm currently looking to add some textboxes and comboboxes on a webpage. I couldn't find these controls in the content section of the CMS. There are many choices like buttons, maps, videos, pictures, etc. but I didn't find textbox or combobox. How can I create these? As a starting test, I would like to create for instance two textboxes and one button that would trigger some code and simply add the values of these boxes. How could I do that? Thanks! -
Unable to install 'mysqlclient' on linux shared hosting server. 'Failed to build mysqlclient'
I have locally developed a Django App (django version - 3.0.5, python version 3.8.2, OS - Windows 10). I used mysql via phpmyadmin as db engine. on my local server I installed 'mysqlclient' using below command. python -m pip install mysqlclient App is fully functioning on my local server. then I purchased a shared hosting for the production deployment. It is a linux server.I installed django,python on virtualenv but unable to install 'mysqlclient'.I used below command. pip install mysqlclient showed error as below: $ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/testdev/virtualenv/test/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-l6dot083/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-l6dot083/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-y99lbq6b cwd: /tmp/pip-install-l6dot083/mysqlclient/ Complete output (34 lines): /bin/mysql_config: line 8: rpm: command not found /bin/mysql_config: line 8: rpm: command not found /bin/mysql_config: line 8: rpm: command not found /bin/mysql_config: line 8: rpm: command not found /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb …