Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending mail before 3 days of the end date and should display those details in html page
sending mail before 3 days of the end date and should display those details in html page .for example if the end_date is 05/10/2019 then i need all details of the promotion of date 02/10/2019 in html page def index1(request): dests = promotion.objects.filter(end_date=date.today()) print(dests) return render(request, 'proindex.html', {'dests': dests}) def email(request): dests = promotion.objects.all() for j in dests: date = j.end_date - datetime.timedelta(days=3) if date == date.today(): print(j.email) print("sent") email_sen = j.email email_user = '@gmail.com' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email_user, 'password') message = 'hello' server.sendmail(email_user, email_sen, message) return HttpResponse('Mail sent successfully') -
Design django Relation to save data easily later
I have 2 csv's according to which I have to design database. first one is And my 2nd csv is And My django model code till now is class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(null=True, upload_to='Restaurant') RestaurantName = models.CharField(max_length=50, null=False, blank=False) Location = models.TextField(max_length=100, null=False) Logo = models.ImageField(null=True, upload_to='Logo') NumberOfTables=models.IntegerField(default=0) Availability=models.CharField(max_length=100 , choices=Availability_CHOICES ) def __str__(self): return str(self.RestaurantName) class Ingredient(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True) def __str__(self): return str(self.name) class Categories(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True) def __str__(self): return str(self.name) class ArticlesOptionsChoices(models.Model): articleoption = models.ForeignKey(User, on_delete=models.CASCADE) optionname = models.CharField(max_length=255) choice = models.CharField(max_length=255) def __str__(self): try: return str('optionname={0}, choice={1}'.format(self.optionname, self.choice)) except: return str(self.optionname) class ArticlesOptions(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ManyToManyField(ArticlesOptionsChoices,max_length=255) min = models.IntegerField() max = models.IntegerField() choice=models.ForeignKey(ArticlesOptionsChoices, on_delete=models.CASCADE , related_name='user_choice_option') choice_price=models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.name) class Articles(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) articlename = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Categories, on_delete=models.CASCADE) pickuptax = models.FloatField(null=True, blank=True, default=None) dineintax=models.FloatField(null=True, blank=True, default=None) description = models.CharField(max_length=500, null=False) ingredient = models.ManyToManyField(Ingredient) #done articleoption = models.ForeignKey(ArticlesOptions , on_delete=models.CASCADE) def __str__(self): return str(self.articlename) I am assuming a restaurant as a User. So Real issue is now how I will manage Article Options into first … -
Unable to import Modules in Python for Django Oscar
I have installed Django AND Oscar by running the commands in given order: virtualenv eshop_env eshop_env/Scripts/Activate pip install django-oscar django-admin.py startproject eshop cd eshop manage.py migrate The settings.py file in eshop directory has these two lines a the top: import os from oscar.default import * The os module is importe without any error. However, there is a red wavy line under from. I am using Visual Studio Code. When I hover over the line, it says unable to import oscar.default. The same error appears on all my import statement involving django and oscar. This also results in the follwing error in Command line after i run the migrate command: ModuleNotFoundError: No module named 'oscar.default' I tried running pip install oscar.default pip install oscar but both of them show an error. However, I was able to successfully run the pip install django-oscar command again. But, he error about the module does not change. What am I doing wrong? This is my project directory structure: D:\Python Websites\Example\eshop\ D:\Python Websites\Example\eshop_env\ D:\Python Websites\Example\eshop\manage.py D:\Python Websites\Example\eshop\eshop\settings.py, urls.py etc. The import error occurs with all other modules as well: from django.apps import apps from django.urls import include, path # > Django-2.0 from django.contrib import admin from … -
How do I set user access in django [duplicate]
This question already has an answer here: How to restrict access to pages based on user type in Django 4 answers I would like to ask the idea/way to have two different user access in django. For example, the admin is able to view all the pages. But if user of the system should only be able to view 1 page out of 4 pages. I have no idea how to start to implement this. -
How can I use Ajax to trigger views.py function?
Whenever a user selects a team within the sidebar of my dashboard, the corresponding team_id is assigned to a variable (that works). Now I would like the dashboard to update accordingly by fetching the new dashboard data for the selected team via an API (that works as well, but not for the assigned team_id). Where I run into issues is to use the assigned variable team_id for the API requests. The application is built on Django, hence I use view functions to fetch the API data. Now the key questions is, how to use the team_id variable for the API requests to get the correct data in return (replacing the id '72' in below example with the js variable)? Furthermore, do I then need to use a success function for Ajax additionally to the views function that will render the frontend? This is my code so far: views.py def team_update(request): response = requests.get('http://www.api-football.com/demo/api/v2/teams/team/72') team_data = response.json() teams = team_data.get('api', {}).get('teams', []) if teams and len(teams) == 1: teams = teams[0] return render(request, 'index.html', { 'name': teams['name'], 'country': teams['country'], 'founded': teams['founded'], 'logo': teams['logo'], 'venue_capacity': teams['venue_capacity'], }) js: $('ul.subbar li a').on('click', function(e) { // Start function when user clicks on a team … -
How to create a model instance object in Django without a form
New to django here. I am following this documentation link to create an instance of a model https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects and I am missing something. Here is my code #models.py class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): print('print title:') print(title) book = cls(title=title) # do something with the book return book #forms.py book = Book.create("Pride and Prejudice") print('printing DJANGO--------------') print(book) #console output print title: Pride and Prejudice printing DJANGO-------------- Book object (None) I have literally copied the code from the tutorial and haven't changed a thing. What am I doing wrong? Thanks -
No known parent package
I made an app called calc in the project wolverine. I tried this code on urls page of calc app from django.urls import path from . import views urlspattern = [ path('',views.home, name= 'home')] Then I got an ImportError File "c:\Users\Anmol\projects\wolverine\calc\urls.py", line 3, in from . import views ImportError: attempted relative import with no known parent package -
string formatting in Html
I am creating a template in HTML {% for product in products %} <tr> <td>{{ product.id }}</td> <td>{{ product.product_name }}</td> {% for i in quantities %} {% if forloop.counter == forloop.parentloop.counter %} <td id="q1">{{ i }}</td> {% endif %} {% endfor %} {% endfor %} How can I assign a different id to each item in quantities? Can I use .format just like we do in python? -
Self not defined?
I have a login view that checks if login users are either a client or pilot and redirect them appropriately but i keep getting self not defined error. Any help will be appreciated. views.py def signin (request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) messages.success(request, 'You are now logged in') if user.role == 'client': def ef (self): return redirect(reverse('dashboard', kwargs={"pk": self.pk})) else: return redirect(reverse('pilot_dashboard', kwargs={"pk": self.pk})) else: messages.error(request, 'Invalid Credentials') return redirect ('login') else: return render (request, 'accounts/signin.html') -
Django or Spring. Which is better for a system analyzing huge data?
I have to develop a system for data analysis and showing the report. Size of data is huge and increasing continuously. Data analytics and Machine learning algorithm will be used. Which framework will be better for me ? DJango or Spring ? -
how to create a validation on detailview class?
i'm trying to show the Post Details only for the User who wrote this post this is view class PostDetailView(PermissionRequiredMixin,DetailView): model = Post this is the form class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] my model class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) how can i check on my view if the user is the one who wrote the post ? -
Using Whitenoise but still can not serve static files
I'm trying to serve static files in my product review website, and I'm using Whitenoise, but It didn't work (can not find the files in /static) (when I test on local with DEFAULT = False, it still works) I've tried to config wsgi file instead of using whitenoise middleware This is my some code in my settings file to serve static. DEBUG = False MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangobower.finders.BowerFinder', ) Can you show me how to fix it? Pardon for my English -
Does creating django objects in a loop burn memory?
I have code like this: for row in PageURL.objects.all(): r = requests.get(row.url) ss = Snapshot() ss.html = r.text ss.pageUrl = row ss.save() I am running out of memory. I believe that the "ss" variable isn't being cleared when looping 1000s of times. Would garbage collection not handle it? It runs fine on my Mac but on Centos 7 it uses more memory, oddly. -
Cannot render a list in template from django view
All my views are being rendered properly but when i try to render a list using iteration nothing is displayed on the page, without error. the view: from django.shortcuts import render from haleys_chemist.models import anti_bacterials from django.http import HttpResponse from .table import anti_bacterials_Table from django_tables2 import RequestConfig from datetime import datetime from django.http import HttpResponseRedirect from .forms import notepadform from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView,ListView class retriever(TemplateView): template_name='index.html' def expiry_days(self,request): expired_drugs= anti_bacterials.objects.all() args={'expired_drugs':expired_drugs} return render (request, self.template_name,args) template(index.html): <h6><i>Drugs about to expire</i></h6> {%for expired_drug in expired_drugs%} <ul> <li>{{expired_drug.Drug_name}}</li> <li>{{expired_drug.expiry_date}}</li> </ul> {%endfor%} </div> model: class anti_bacterials(models.Model): Drug_id= models.IntegerField(primary_key=True); Drug_name= models.CharField(max_length=50); expiry_date= models.DateField(); Price_per_mg= models.DecimalField(decimal_places=2, max_digits=20) i need to list the expired drugs on the left bar. i know i have queried for all objects on the view but still i should get a list of all the objects names and expiry dates. -
How do I translate a url link into a path link in django when creating a dynamic link in an HTML template?
I'm super new at all of this. I'm following a tutorial (this one to be exact: https://www.youtube.com/watch?v=qgGIqRFvFFk) and it uses url() to create the urls and everything. However, the version of django that I downloaded uses path() and I've done pretty okay with translating everything over, but I'm trying to create a dynamic link in my HTML template so that I don't have any links hardcoded into the template. I keep getting an error though. This is my code: <form action="{% path 'music.favorite', album.id %}" method="post"> It's giving me an error saying 'Invalid block tag' and highlighting everything between the {% %} like there's something wrong with the python. I've been staring at this for so long. Someone save me. -
Heroku: ModuleNotFoundError: No module named 'lending'
It pushes successfully, but it doesn't run once I go to the website. My full error is here. My Procfile is web: gunicorn p2plending.p2plending.wsgi:app My requirements.txt is psycopg2==2.7.6.1 djangorestframework==3.9.2 Pillow==6.0.0 requests==2.21.0 factory_boy==2.11.1 django-filter==2.1.0 django-rest-auth==0.9.5 django-heroku gunicorn -
Django user not defined errors
I still can't understand why i am getting NameError: name 'User' is not defined. I am using a custom user model with settings.py updated appropriately with AUTH_USER_MODEL = 'accounts.User' models.py from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): username = models.ForeignKey(User, on_delete= models.CASCADE) class User(AbstractUser): role = models.CharField(max_length=50) But strangely when i use: from django.contrib.auth import get_user_model User = get_user_model() i get the error: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed -
How to handle login/logout flow for multi users working on the same hardware computer
We have a classic web application accessed from physical shop with their computer, using browser. We build user role (owner and staff) and credentials so far normal web application. But we notice that lot of shop don't use it the way we except. They create one owner account and everybody use the same account. As main shops have only one computer and staff don't want to logout and type their login/password each time they take an order or need to search for information. I know that POS system have code bar reader and staff can scan their code-bar before registering an order but for our web application we don't have this hardware. So I wonder if there's some best practice, library, example or idea on how to handle this case. Thanks for reading. -
Serving static files with digitalocean
I am using DigitalOcean to serve my static files for my website. I have used Django and Postgres for database. I deployed my site with a DigitalOcean droplet, uploaded my static files in the DigitalOcean Spaces (I verified that they are indeed there), and updated my settings.py code to update my database information. CDN is enabled and CORS is configured. I tested the site using gunicorn (step 7 of tutorial), but my website is still simply html text with no css styling from my static files. When I clicked "inspect element > sources" I can see that href is indeed https://[my DigitalOcean Spaces information] What else do I need to update to be able to serve my static files? Tutorial link:https://www.digitalocean.com/community/tutorials/how-to-set-up-a-scalable-django-app-with-digitalocean-managed-databases-and-spaces -
Django AttributeError: module 'cal.views' has no attribute 'index'
I have a problem to create a calendar with django, this code is similar a tutorial, but the problem is in folder cal/views my code with django detects attribute errors and I no longer know what could be wrong, I already checked the files in the "cal" folder pls help me in my code :( this is the code in descubretepic/cal/views from datetime import datetime from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.utils.safestring import mark_safe from .models import * from .utils import Calendar class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('day', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) return context def get_date(req_day): if req_day: year, month = (int(x) for x in req_day.split('-')) return date(year, month, day=1) return datetime.today() my code in descubretepic/cal/urls from datetime import datetime from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.utils.safestring import mark_safe from .models import * from .utils import Calendar class CalendarView(generic.ListView): … -
Is it possible to use inline CSS to reference dynamic images in Django?
Sorry if the title was a bit unclear, I couldn't think of any other way to phrase it. So I want to know if it's possible to use inline CSS (<div class="" style="background-image: url();" and put the dynamically created images in there. So if I want a user to upload a banner, I want the background image of the div to be the image. Is this possible? So for example The user uploads a photo and it goes to /media/ Then normally to reference it, I would do <img class="user-image" src="{% user.userprofile.image.url %}"> However, what if I wanted to set it as a background image. In the CSS document, I want to do this: .user-image-div { background-image: url({% user.userprofile.image.url %}) } However, this doesn't work. So my question is, is it possible to use inline CSS in the HTML document to get around this? So like <div class="user-image-div" style="background-image: url({% user.userprofile.image.url %};)"> <!-- code here --> </div> Would this work? I don't have access to Django at the moment, so I will be able to test it out in a few days -
Comparing javaScript values then redirect to another url if true
problem on comparing values and redirecting to another page ,, values are string and integer "CharFields" .. else statement works fine but the if statement when i type it correct the page just refreshes and nothing happens.. and if possible i want to make that commented img replace the button,, thx any way :) i made java function to get variables from a user input trcode and made django print the model in an input value those two works fine i tested them with printing ,, the problem is in comparing the values and redirecting to the another url function readText () { var value1 = document.getElementById("trcode").value; var value2 = document.getElementById("trfcode").value; if (value1 === value2) { location.href="http://127.0.0.1:8000/myposts";} else { alert("You typed: " + "Wrong Password");} }``` ``` ### tried to use=> if (value1.equals(value2)){ #### NOTHING CHANGED SAME PAGE REFRESH ### }### ``` ```html <form onsubmit="return readText();"> <tr><td height="18" class="subheaderboldtext"> Enter Code: <input id="trcode" maxlength="8" class="box"> <input class="submit" type="submit" value="SUBMIT"> {# <img src="/static/guest/images/querybutton.png" alt="Query Button">#} </form></td></tr> <button id="trfcode" value="{{ user.profile.trf_code }}">z</button> when the user type wrong password alert appears and when he write it right he get redirected to a certain page on the site -
Safe filter Still Displays HTML Tags
I have added CKEditor to my django project, but the text is still showing HTML tags. Despite the fact that I have the safe filter inserted following my content variable. Am I missing the reason that this will not escape the HTML tags? Here is my model: class Post(models.Model): title = models.CharField(max_length = 100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='post_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Here is my form template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class='border-bottom mb-4'>New Post</legend> {{ form.media }} {{ form | crispy }} </fieldset> <div class="form-group"> <button type="submit" class="btn btn-outline-info">Upload</button> <a type="submit" class="btn btn-outline-secondary" href="/">Cancel</a> </div> </form> Here is my post detail template: <article class="media content-section"> <img src="{{ post.author.profile.image.url }}" alt="profile photo" class="rounded-circle article-img"> <div class="media-body"> <img src="{{ post.image.url }}" class="post-img"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:'F d, Y'}}</small> {% if object.author == user %} <div> <a href="{% url 'post-update' object.id %}" class="btn btn-outline-secondary btn-sm mt-1 mb-1">Edit</a> <a href="{% url 'post-delete' object.id %}" class="btn btn-outline-danger btn-sm mt-1 mb-1">Delete</a> </div> {% endif %} </div> <h2 class='article-title-detail'>{{ object.title }}</h2> <p class="article-content">{{ … -
Website suddenly stopped loading 'Incomplete response received from application'
I am new to using Django and have recently put a website on a cloud managed server. Everything has been working fine for about a month or so. However, a day or so ago it is no longer loading and comes up with the error 'Incomplete response received from application'. In the console of my browser it also says it is a 502 error. I have looked and tried a few things online, but it seems that this problem can be caused by a few different things. I also tried looking at the passenger error.log file, but that didn't come up with anything. I was wondering if anyone has any tips, or can send me in a good direction to find out whats going on, as I haven't touched the files since they were uploaded. Thanks in advance. -
good practices of VBC views
I have a question about class-based views. I have the following view: class UserCourseListView(ListView): model = User template_name = 'courses/user_course_list.html' def get_queryset(self): user_inscriptions = self.request.user.get_inscriptions.all() courses = [inscription.course for inscription in user_inscriptions] return courses The purpose of the view is to obtain a list of the courses in which the user who logged in at that time has registered. And be able to access that data in context (in the template). The doubt I have is the following: The model class attribute is theUser model and in the get_queryset estoy method returning instances of theCourse model, which does not make much sense. And my question is, is it good practice to do this? Is there another better way to do it with class-based views? Another way I came up with it and that is more consistent is with a function-based view, but it doesn't convince me much: def user_course_list(request): user_inscriptions = request.user.get_inscriptions.all() courses = [inscription.course for inscription in user_inscriptions] return render('courses/user_course_list.html', {'courses': courses}) Since Django documentation recommends that we use class-based views as much as possible.