Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Highlight only the row of the specific player
I am developing a game using python and django templates. In the first step, each player enters his/her name(they are playing on different laptops). In the second step, a value. After that, they get the whole input displayed as a dataframe, sorted by their values. Since they should not know about the names of the others, I was thinking of dropping the name collumn using df1 = df.drop(['Position'], axis=1) However, the players should still know which value they inserted, which is why I want to highlight their specific row. Means Player A sees only his row in green, Player B sees only his row in green etc. The highlight would be based on df.style.apply(lambda x: ['background: lightgreen' if x.name == ????? else '' for i in x], axis=1) with x is the amount of players. However, I am not able to connect the specific entered name to the highlight functions I create a form field using django template and python code class Welcome(Page): form_model = 'player' form_fields = ['name'] The entered Name is then saved in the variable self.player.name. -
django - how to download uploaded files through a link
I am uploading a file and saving it on a folder outside the media folder. I want to add a download link in a template to be able to download the file directly. i am not sure what to add in the url,if i shoud add something i tried this in the template it says url not found <a href="{{data.tar_gif.url}}"> Download File</a> views.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') html page <tbody> {% for data in dataset %} <tr> <td>{{data.path_id}}</td> <td>{{ data.tar_gif }}</td> <td> <a href="{{data.document.url}}"> Download File</a> </td> </tr> {% endfor %} </tbody> -
How to change the AJAX - Views workflow in terms of url mapping
I have a working AJAX function and a working views function (to make API calls). But I don't get them work together. I guess that something is wrong with my web applications workflow / sequence of actions. So now the problem is as follows: When i visit http://127.0.0.1:8000/ everything shows up as intended and the team_id gets assigned correctly to the javascript variable when i click any team in the sidebar. When i visit http://127.0.0.1:8000/dashboard/ I get a TypeError, because the views function doesn't know about the required team_id for the API call (because so far nobody selected a team). Thus, the API return is a empty dic which ends up in a TypeError and the page doesn't render. The goal is that a user lands on http://127.0.0.1:8000/dashboard/ and clicks different teams in the sidebar without a page_refresh to update the dashboard accordingly to the fetched data. But to be able to select a team at all, he needs a rendered frontend.. Currently I have the following url mapping structure: from dasocc_app import views from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^$', views.render_landing_page, name='landing_page'), url(r'admin/', admin.site.urls), url(r'about/', views.render_about), url(r'dashboard/', views.team_update, name='team'), url(r'dasocc_app/', include('dasocc_app.urls')) ] This … -
Why migration is not working after pulling from git?
I'm working collaboratively with some members on a Django project. They're working on Windows whereas I'm working on Ubuntu. My problem is, every time I pulled from git and apply python manage.py migrate, and suggest me to enter python manage.py makemigrations --merge. Followed by the suggestion,entered python manage.py migrate, But it showed the following errors: django.db.utils.ProgrammingError: column "first_name" of relation "account_appuser" does not exist django.db.utils.ProgrammingError: column "login_id_id" of relation "account_appuser" does not exist For 1st error, from the migrations file, I delete those addfield operations and for 2nd error,from the migrations file, I delete removefield operations Now, I have to check every migrations file where this kind of problem occurred. On the other hand, other team member didn't face such kind of problem, they only apply python manage.py makemigrations --merge and python manage.py migrate. Is this happening because of different Operating systems? and any alternative solution for this problem. I am new on this site, So please help me by suggestion.Thanks -
Docker Image `httpd` with libapache2-mod-wsgi-py3
I'm currently creating a Dockerfile with a base image httpd:2 And I manually installed libapache2-mod-wsgi-py3 is there a way I can use mod-wsgi for my Django Application on another container? -
creating custom middleware not working in django?
Here I am trying to update user's last time visit by using the custom middleware. But this is not working.It is not updating the last_visit time in the database. What am i doing wrong here ? models.py class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) last_visit = models.DateTimeField(default=now(), blank=True) views.py class CheckUserLastVisitMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: Staff.objects.filter(pk=request.user.pk).update(last_visit=now()) response = self.get_response(request) return response settings.py MIDDLEWARE = [ 'organization.views.CheckUserLastVisitMiddleware', -
Isn't the html of the form Django displays on the screen?
Django shows you forms when you do basic coding, right? Where is the html of the automatically generated form in windows? So instead of looking for a template folder, once the developer writes the url or views code, he finds the location of the skeleton-only html that Django shows. In my opinion, it looks like it's built somewhere like an "anaconda/envs" contains a separate virtual environment, but I can't find it. Please help. Thank you for reading. work hard. End. nothing. unneccessary. it's maybe path? -
Manipulate Django ManyToManyField() according to category selected in the same model
I have these two models, first having category and second having size related to particular category class MasterCategory(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class MasterSizes(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) category_size = models.CharField(max_length=2) def __str__(self): return self.category_size This is product model where I want to fetch sizes related to selcted category AND let user select multiple sizes at a time. class Product(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) # subcategory_name = models. product_brand = models.CharField(max_length=50) product_title = models.CharField(max_length=50) product_summary = models.CharField(max_length=200) product_description = models.TextField() original_price = models.FloatField() # discount_rate =models.IntegerField(null=True, blank=True) related_size = MasterSizes.objects.filter(category_name=category_name) available_sizes = models.ManyToManyField(related_size,related_name='category_sizes') discount_price = models.FloatField() product_image = models.ImageField() product_size = models.ForeignKey(MasterSizes, on_delete=models.CASCADE) favourite = models.BooleanField(default=False) def __str__(self): return self.product_title How do I filter the ManyToManyField() with the selected category related sizes only ** Right Now** It shows all the sizes in available_sizes But I want to get sizes only related to category selected. -
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