Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to block user after 3 login attempts using Django rest-framework
I'm using djngo-rest-framework for my projects and django-oauth-toolkit to authentication users through the api I wanted to when a users intend to login and get access token if user enter wrong username or password for three time their accounts get deactivated. -
How do I include a Background picture in a css file for django usage?
I'm trying to include a background picture into one of my css files which is then loaded into a html file using djangos compressor module. The project looks as follows: djangoproject |-myproject (with setup.py etc) |-statics |-images |-css |-templates |-index.html In the index.html i used {% load static %} {% load compress %} {% compress css %} <link rel="stylesheet" href="/static/css/style.css"> {% endcompress %} and in this style.css, I would like to include a background picture from statics/images/bg.jpg. I tried to do this as follows: background: url('../images/bg.jpg') 50% 0 repeat-y fixed; but the picture wont appear. So does anyone know how to refere the url here? Because outside of django, this way works well. Thanks for any advie and sorry for my bad english skills (just ask if you are not able to understand something because of bad word choice etc.)! Thanks! -
Which one makes more sense, writing models in django or creating a table then auto-generating the models?
We have designed our ER diagram for our database design but I don't know if it makes more sense to write models in Django from scratch or create tables in Postgres then use inspectdb. What are the disadvantages of the latter and which one is most commonly used in projects? -
Store ALL Django errors in a Model?
I was wondering if there is a way to store every and all errors in a Django Model? Let's say I have a function that connects to an API and that API returns 404. Similarly, I have a model that people add their attendances to, if there's something wrong in a Model, it doesn't let the User proceed with what they're doing but I want it to log that error as well, not locally, but in a Model. Consider a model of a similar structure: class ErrorLog(models.Model): error = models.CharField(max_length=255) message = models.TextField() #Then date and time etc. I understand that for my function I'd need to use a try and except block but what would I do for the models to automatically log the error inside a model? -
consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused
This is my project structure myproj β βββ app1 βββ __init__.py βββ tasks.py |---gettingstarted βββ __init__.py βββ urls.py βββ settings.py β βββ manage.py |-- Procfile In gettingstarted/settings: BROKER_URL = 'redis://' In Procfile: web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker --app=app1.tasks.app In app1/tasks.py from __future__ import absolute_import, unicode_literals import random import celery import os app = celery.Celery('hello') @app.task def add(x, y): return x + y When I run "celery worker" it gives me: consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. -
handle forms in python django
today i have a challenge for my customer's site ... in this site we have a form that contains some radio and checkbox to get information from clients i want when client complete the form and clicked on Submit button , information send to admin of the site and when admin confirmed the POST the form information send to the other page that designed by front-end developer as post ... like this ... client side : <form action="#"> <input type="text" placeholder="Enter Your Name :"><br><br> Genger :<br><br> <input type="radio" name="GDR">Male<br> <input type="radio" name="GDR">Female<br><br> Select Your Skils :<br><br> <input type="checkbox">HTML5<br> <input type="checkbox">CSS3<br> <input type="checkbox">JavaScript<br> <input type="checkbox">ES6<br> <input type="checkbox">Django<br> <input type="checkbox">NodeJS<br><br> <input type="submit"> </form> now is the time that admin confirm the post : for example completed form is : my name is : Hassan Raji I'm : Male And my skills are : HTML5 , CSS3 and JavaScript i want to show this information in other page as post like this : .STL{ background-image : linear-gradient(#000 , #555 , #000); padding:25px; border-radius:15px; border: 5px solid red; color:white; } h4{ color:red; } <div class="STL"> <p>Name : Hassan Raji</p> <h4>Gender</h4> <p>Male</p> <h4>Skills:</h4> <p>HTML5</p> <p>CSS3</p> <p>JavaScript</p> </div> the back end is by Django Please Help β¦ -
django AdminDateWidget: Uncaught ReferenceError: quickElement is not defined
I am trying to use AdminDateWidget in my application, I get below javascript error, tried different options available on the internet still couldn't solve. FYI, my admin url is "/newadmin" I have properly include the form.media, where am I making mistakes? Console error; DateTimeShortcuts.js:259 Uncaught ReferenceError: quickElement is not defined at Object.addCalendar (DateTimeShortcuts.js:259) at init (DateTimeShortcuts.js:46) My template looks like; {% block style %} <script type="text/javascript" src="/newadmin/jsi18n/"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="/static/myn/starter.css" rel="stylesheet"> <script type="text/javascript" src="/static/myn/starter.js"></script> {{ form.media }} {% endblock %} Form; from django.contrib.admin.widgets import AdminDateWidget #class YourForm(forms.ModelForm): # from_date = forms.DateField(widget=AdminDateWidget()) class EventForm(ModelForm): class Meta: model = Event fields = ['title', 'ondate', 'photo', 'desc'] widgets = { 'title': TextInput(attrs={'size': 70}), 'ondate': AdminDateWidget(), } -
Stripe cancellation of subscription is not working with Django
I'm trying to create a cancellation page to remove a subscription of monthly payment. However, I still cannot retrieve the customer information with Stripe API. The customer and subscription is already succeeded to create when I saw the Dashboard of Stripe. Here is my views.py: def charge(request): if request.method == 'POST': form = CustomUserForm(request.POST) try: user = form.save() plan = 'plan_xxxxxx' customer = stripe.Customer.create( card=customer.stripe_id, email=user.email, plan=plan) charge = stripe.Subscription.create( customer=customer.id, plan=plan, ) user.stripe_id = customer.id user.save() return render(request, 'charge.html') Here is cancel the subscription in views.py: def cancel_subscription(request): try: customer = stripe.Customer.retrieve(request.user.stripe_id) customer.cancel_subscription(at_period_end=True) return redirect('home') except Exception as e: print(e) return render(request, 'accounts/cancel.html') Here is cancel the subscription in model.py: class CustomUser(models.Model): username = models.CharField(max_length=255) email = models.EmailField() stripe_id = models.CharField(max_length=255) plan = models.CharField(max_length=50, default='xxxxxxx') Here is cancel the subscription in form.py: class CustomUserForm(ModelForm): class Meta: model = CustomUser fields = ("username", "email", "stripe_id") def show_error(self, message): # pylint: disable=E1101 self._errors[NON_FIELD_ERRORS] = self.error_class([message]) This is the error that I get: 'User' object has no attribute 'stripe_id' I think that it could not save stripe_id to form and not retrieve from form. How should I edit it ? -
Render different date format depending on time that passed - either |timesince or |date
Good morning. What I would like to achive is that when user posted sooner than 24h from now, I would like to have for example: Posted: 4h ago, but when it's more than 24h, it would be nice to have: Posted: November 10. First approach is doable by using: {{ post.date_posted|date:"F d, Y" }}, second one: {{ post.date_posted|timesince }}, but is there a way to "mix" them? Is is possible in Django? -
django how to make custom url
hey guys i have been learning Django for about 3 week now and i am just curious is there anyway to set custom url for main page(the first page shown when starting the server) because i try to do it like the code below but still it give me error if anyone know please help if not hmm...maybe that how Django operate i think haha. Thanks // Django api from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('account/',include("useraccount.urls")), ] //useraccount from django.urls import path from . import views urlpatterns = [ path('login',views.login,name="login"), ] -
Clickable EDIT button inside a popup window and on clicking the button it performs action
I have created a simple page. In that I have a VIEW button so on clicking that view button I am able to open a popup window. So I want a button called "EDIT" to be inside the popup window and on clicking that EDIT button it should edit the JSON data which is coming from the URL in the popup window. ** This is my Base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Operations Performed</title> <script> function calc() { var n1 = parseFloat(document.getElementById('n1').value); var n2 = parseFloat(document.getElementById('n2').value); var oper = document.getElementById('operators').value; if (oper === '+') { document.getElementById('result').value = n1+n2; } if (oper === '-') { document.getElementById('result').value = n1-n2; } if (oper === '*') { document.getElementById('result').value = n1*n2; } if (oper === '/') { document.getElementById('result').value = n1/n2; } } </script> </head> <body bgcolor='cyan'> {% block content %} {% endblock %} </body> </html> ** This is my Home.html {% extends 'base.html' %} {% load static%} {% block content %} <h1>Hello {{name}}...!!!></h1> <form action="add" method="POST"> {% csrf_token %} <select id="operators"> <option value="+">Addition</option> <option value="-">Subtraction</option> <option value="*">Multiplication</option> <option value="/">Division</option> </select><br> <br> <br> <br> <br> Enter 1st no: <input type="text" name="num1" value='{{val1}}' id="n1"><br> Enter 2nd no: <input β¦ -
Django: Getting FieldError While Using Slug in URL
I am a beginner in Django. Right now, I am building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get FieldError error. It looks like this: FieldError at /details/galaxy-note-10 Cannot resolve keyword 'slug' into field. Choices are: date_published, id, link, phone_model, review_article When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error. Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = β¦ -
Bootsrap collapse not working in Jinja template
I need to add multiple rows of data from backend to a table and toggle the div in which the table belongs onclicking the parent div of the div in which the table belongs. So I included a for loop in jinja template and after doing this bootstrap collapse doesn't seems to work and when i click over the heading the table div collapses but opens again ? Following is the jinja template : {% if leads.get_shortlisted_colleges %} <div class="card"> <div class="card-header"> <h5 class="card-title">Shortlisted Colleges</h5> </div> <div class="card-body"> {% for institute in leads.get_shortlisted_colleges %} <div class="box"> <div class="row"> <div class="col-xl-6"> <h1>{%if institute.institute%}{{institute.institute.name}}{% endif %} <a href="#" class="moreinfoinstitute" data-toggle="modal" data-institute8-id="{{institute.id}}" data-target=".clg-detail">More Info</a></h1> <p>{% if institute.institute.city %}{{institute.institute.city.name}},{% endif %} {%if institute.institute.state %}{{institute.institute.state.name}}{% endif %}</p> <p> L3 Assigned : <strong> {% if l3_assign_to %} {{l3_assign_to}} {% else %} None {% endif %} </strong> | Status : <span class="badge badge-pill badge-secondary"> {%if institute.status%} {{institute.status.name}} {% endif %} </span> | CAF : <a href="#">Not Available </a> </p> </div> <div class="col-xl-6 detail-btn text-right"> <button class="btn btn-outline-dark btn-sm viewtrail" data-toggle="modal" data-institute-id="{{institute.id}}" data-lead-id = "{{leads.id}}" data-target=".trail">View Trail</button> <button class="btn btn-outline-dark btn-sm visitcampus" data-toggle="modal" data-institute2-id="{{institute.id}}" data-target=".visit-campus">Visit Campus</button> <a href="#" class="btn btn-primary btn-sm">User Form Details</a> <button class="btn btn-danger btn-sm updatestatus" β¦ -
Error when I upload.csv file in Django Admin
I get an sqlite3.IntegrityError: NOT NULL constraint failed: stores_product.quantity when I try to upload a csv in Django Admin panel this is my csv file Here is my admin.py file from django.contrib import admin from .models import Product from import_export.admin import ImportExportModelAdmin @admin.register(Product) class ViewAdmin(ImportExportModelAdmin): pass Here is the error Line number: 1 - NOT NULL constraint failed: stores_product.quantity , Oreo Biscuits, Cadbury, 100, 20, Cookies, 5 -
How to autocomplete input in field Django
I have a product model. I need to autocomplete product name into input field. class Product(models.Model): product_name = models.CharField(max_length=255) product_detail = models.TextField(blank=True, null=True) product_price = models.FloatField(blank=True) category = models.CharField(max_length=30) product_image = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=255, blank=True, null=True) product_amount = models.IntegerField(blank=True, null=True) del_flag = models.BooleanField(default=False) def __str__(self): return self.product_name -
Django View Contained Within Template
This is hard to explain, but what I want to be able to do is have a search view which operates independently from all of my other views. I would like to have multiple templates with a search box embedded which will search and return results independent of the view that is being rendered. At the moment the only way I can think of to do this is to create a separate form instance for every single function based view. I would like to have the search self contained. Can someone advise me on what I need to look at to do this as I have no idea where to start. I was looking at class based vies, but I still can't separate the search function from the template. -
On executing python manage,py runserver is not showing any output on terminal
While executing python manage.py runserver is not showing any output on terminal and process exist without showing any error. Don't know how to fix it ??. I am new to djano. -
Use Rosetta on production site
We are looking for a way to help users translate our website. As developers, we sometimes edit the .PO files manually, but we also love Rosetta. The UI for Rosetta would also suit our translators. Is Rosetta also intended for use in a production environment by external users? Are there any examples of Rosetta running on a production site? If so, what strategy do you use to get the translations back into your repository? -
pip install django mysqlclient 'path should be string, bytes, os.PathLike or integer, not NoneType' on windows
I am new in python and django and want to install mysqlclient on windows.When command pip install django mysqlclient in cmd it throws this error : File "d:\myprojects\python\mytestdjangoprj\myproject\lib\genericpath.py", line 30, in isfile st = os.stat(path) TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType please help me. -
How to Sort a Django ListView on Button Click
I'm making a website which has a bunch of Event posts (Parties, Get-Togethers, Fundraisers etc.). I want the user to be able to sort the posts by the date those event posts were created (created_date) and by the date that event post takes place (start_date) on button click. There are exactly 2 ways the user can sort the ListView (by created_date or by start_date according to my models.py) so I want the button to be a toggle, where clicking it once would filter by start_date and clicking the button once more (after the page refreshes) would filter by created_date. My home.html contains the button and a for loop to show the posts: <!-- THE EVENT FEED --> <div class="feed"> <h2>Event Feed</h2> <!--BUTTON TO FILTER EVENT FEED--> <div style = "border-top: solid 1px #eee; width:100%;align-items: center;display: flex;flex-direction: column;"> <a href="{% url 'whsapp-home' %}?ordering={% if ordering == 'created_date' %}-start_date{% else %}-created_date{% endif %}"><button>Filter by Event Date</button></a> <!--<button data-text-swap="Filter by Event Date"></button>--> </div> <div class="chat"> {% for post in posts %} <div class="your messages"> <div class="message"> <b>{{ post.title}}</b> </div> </div> {% endfor %} </div> </div> And here is my class based view for the posts: class PostListView(ListView): model = Post template_name = 'whsapp/home.html' β¦ -
If you see valid patterns in the file then the issue is probably caused by a circular import
'C:\Users\huihuiqian\mys ite\posts\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. mysite.urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/', include('posts.urls')), ] post.urls.py from django.conf.urls import url from . import views urlpartterns =[ url(r'^$',views.index, name='index') ]; -
Searching in Django, a few words in one object
I have an app where a user can look for recipes by inputing ingredients. I am wondering how to make it in query that django will know that "Juice of lemon" is one ingredient, now after inputing "Juice of Lemon" it shows as well "Juice of citron". So when a user input "juice" it should show all ingredients which contains juice, but when a user will input whole ingredient name "Juice of citron" it should show only recipes containing this ingredient. def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__contains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) Models: class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) -
Search results are not being displayed
I have created a model named Product consisting of these fields ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type'), so whenever I use the search bar to search the name of the company it doesn't display the products Here is my views.py file(contains only the search view) from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import * from .forms import * class SearchResultsView(ListView): model = Product template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') items=Product.objects.filter(Q(company__icontains=query)) return items base.html file containing the searchbar <form class="form-inline my-2 my-md-0" action="{% url 'search_results' %}" method="get"> <input class="form-control" name="q" type="text" placeholder="Search"> </form> search_results.html file {% extends 'base.html' %} {% block body %} <br> <br> <table class="table table-hover"> <thead> <tr> <th>Sr. No.</th> <th>Product Name</th> <th>Company</th> <th>Quantity</th> <th>Price</th> <th>Units</th> <th>Product Type</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{item.pk}}</td> <td>{{item.prod_name}}</td> <td>{{item.company}}</td> <td>{{item.quantity}}</td> <td>{{item.price}}</td> <td>{{item.units}}</td> <td>{{item.prod_type}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} urls.py file from django.conf.urls import url from django.urls import path from .views import * urlpatterns=[ path('search/', SearchResultsView.as_view(), name='search_results'), ] Here's how it looks once I search for something -
Django contact form: display users email as sender in mailbox
I have got a contact form on my website where the user enters his/her email, a subject and a message. This is how my contact view looks like: def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['my.name@mydomain.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "account/contact.html", {'form': form}) And these are my E-Mail settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my.name@mydomain.com' EMAIL_HOST_PASSWORD = **************** EMAIL_PORT = 587 Everything works fine and I get an email from my.name@mydomain.com to my.name@mydomain.com with the subject and message. But I don't see the users email to reply. I can append it to the message but is there a way to change the senders email to the users email so that I can respond by clicking reply in my mailbox? -
KeyError: 'video_fps' with moviepy ffmpeg
I am writing a Python script to convert a video (.MP4) into an audio file (.MP3) on a Django server. To achieve this, I am using the Moviepy library but when I run the script, I get the following error: Internal Server Error: /test/ Traceback (most recent call last): File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\shoe\musicsite\main\views.py", line 29, in test video = VideoFileClip(os.path.join(basePath + ".mp4")) File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in init self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt, File "C:\Users\etsho\AppData\Local\Programs\Python\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 34, in init self.fps = infos['video_fps'] KeyError: 'video_fps' [15/Nov/2019 23:49:43] "POST /test/ HTTP/1.1" 500 80909 There's practically no information about this error or how to solve it that I could find, so any help or insight would be much appreciated. Here is my Python script (views.py): import pyodbc, json, pytube from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import parsers import os from moviepy.editor import * @csrf_exempt def test(request): if request.method == 'POST': filePath = 'C:\\Users\\etsho\\Music\\' #retrieve url from app body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) β¦