Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the best practice for holding secrete files in django?
I'm trying to access a secret JSON file within my module. How can I locate the path of this file in Django? Is holding files within the application folder considered a good practice? from pathlib import Path from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials def report_generator(): SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = Path('./clientSec.json') VIEW_ID = '123456789' START_DATE = '2020-10-01' END_DATE = 'today' credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES) # Build the service object. analytics = build('analyticsreporting', 'v4', credentials=credentials) # Calling API's response = analytics.reports().batchGet(body={ 'reportRequests': [{ 'viewId': VIEW_ID, 'dateRanges': [{'startDate': START_DATE, 'endDate': END_DATE}], 'metrics': [ {"expression": "ga:pageviews"}, {"expression": "ga:avgSessionDuration"} ], "dimensions": [ {"name": "ga:deviceCategory"} ] }]}).execute() This is my folder structure. -
How can I delete all cache of one fragment_name
Hi I have a django blog and I am using fragment cashing. I want to delete fragment cache but I have many cache. For example I have many article and I dont know how many of there article articleid#1 article articleid#2 article articleid#3 article articleid#4 I want to delete all the cashe of article objects I am using this code : from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key # cache key for {% cache 500 sidebar username %} templatetag key = make_template_fragment_key('article', [article.id]) cache.delete(key) # invalidates cached template fragment -
I want to retrieve the data to match values
I want to retrieve the data to match username and password. So I try this but it doesn't work Here my code in views.py username = request.POST['username'] password = request.POST['password'] conn = mariadb.connect(host="localhost",user="django",password="1234",database="mydatabase") cur = conn.cursor() res = cur.execute("SELECT user_username FROM store_users WHERE user_username = username") conn2 = mariadb.connect(host="localhost",user="django",password="1234",database="mydatabase") cur2 = conn2.cursor() res2 = cur2.execute("SELECT user_password FROM store_users WHERE user_password = password") if res is not None and res2 is not None: return render(request,'index.html') else: messages.error(request,"Username หรือ Password ไม่ถูกต้อง") return redirect("/login") -
broken image icon in django template
My image and my background image will not load. I've tried many things and cant figure It out. I always get the broken image icon instead and the background wont load... this is my settings import os from pathlib import Path . . . . . . STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'reviews/static') This is my urls.py from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.index, name='index') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is my template called home.html {% load static %} <center> <html> <head> {% load static %} <link rel="stylesheet" href="home.css"> </head> <body> <div class="container"> </div> </body> <h2>WELCOME </h2> <img src="{% static 'logo.jpeg' %}" > <a href="http://localhost:8000/shop">SHOP</a> <a href="http://localhost:8000/reviews/">REVIEW</a> <div id="overlay"></div> <title>yorleì</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <style> body,h1 {font-family: "Raleway", sans-serif} body, html {height: 100%} .bgimg { background-image: url('/static/reviews/Background.jpeg'); min-height: 100%; background-position: center; background-size: cover; } </style> <body> <div class="bgimg w3-display-container w3-animate-opacity w3-text-black"> <div class="w3-display-topleft w3-padding-large w3-xlarge"> </div> <div class="w3-display-middle"> <h1 class="w3-jumbo w3-animate-top">COMING SOON</h1> <hr class="w3-border-grey" style="margin:auto;width:40%"> <p class="w3-large w3-center">35 days left</p> </div> </div> </center> </body> </html> and i always get a broken image! HELP ME PLEASE! Also the file isn't connecting to … -
Django If statement not working in template
i am adding this code to my template while using the django authetication system (USER) and the entry is a model with the entry_author field but its still didnt show me the resulr {% if user.username == entry.entry_author %} <p class="btn btn-primary btn-sm">Delete Post &rarr;</p> {% endif %} -
Django FormMixin and ForeignKey
I am quite new to django. This is my issue: I have been able to create a form in order to let the user create a client 'index card'. I have been able to create a DetailView to render the element entered by the user I have been able to create an additionnal form in the DetailView to let the user add additional elements related to his client. However, my Foreign_key that is supposed to link the additional elements to the client (I call it collection) is still empty when I check in admin. There is something I don't understand and that I do wrong... Any help would be welcome ! models.py : class Collection(models.Model): name = models.CharField(max_length=300) image = models.ImageField(default='tgt_default.jpg', upload_to='tgt_pics') description = models.TextField(null=True) created_by = models.ForeignKey(User, related_name="collections", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return str(self.id) def save(self, *args, **kwargs): super(Collection, self).save(*args, **kwargs) img = Image.open(self.tgt_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.tgt_image.path) class ImportantFacts(models.Model): collection_important_facts = models.ForeignKey(Collection, related_name="has_important_facts", on_delete=models.CASCADE, null=True) note = models.TextField(max_length=400) forms.py class ImportantFactsForm(forms.ModelForm): class Meta: model = ImportantFacts fields = ['note'] views.py class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView): model = Collection form_class = ImportantFactsForm template_name = 'taskflow/collection_detail.html' success_url = None def … -
How To Solve "No Reverse Match" With Django
What I am trying to do is allow for a user to click on a product, be taken to the product page and then be able to add a review to that product page. The reviews are appended to the product as users are adding the reviews. I'm not sure if this is the best approach to use. I have been running into issues with this error for the last few days after editing a form. Please let me know if you have any solutions. Thank You! Models.py class Beach(models.Model): name = models.CharField(max_length=80) location = models.CharField(max_length=200) video = models.FileField(upload_to='beachvideo', blank=True) beachPic = models.ImageField(default='default.jpg', upload_to='beachphotos', blank=True) datetimeInfo = models.DateTimeField(auto_now=True) lat = models.FloatField() lon = models.FloatField() info = models.TextField() def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return f'{self.name}' class Review(models.Model): RATING = ( ('1', 'Avoid'), ('2', 'Not Great'), ('3', 'Decent'), ('4', 'Awesome'), ('5', 'The Best'), ) beach = models.ForeignKey(Beach, on_delete= models.CASCADE) author = models.ForeignKey(User, null=True, blank=True, on_delete= models.CASCADE) ratingRank = models.CharField(max_length= 100, blank=False, choices=RATING) waveIntensityRank = models.CharField(max_length= 100, blank=True, choices=RATING) crowdednessRank = models.CharField(max_length= 100, blank=True, choices=RATING) pollutionRank = models.CharField(max_length= 100, blank=True, choices=RATING) noiseLevelRank = models.CharField(max_length= 100, blank=True, choices=RATING) servicesRank = models.CharField(max_length= 100, blank=True, choices=RATING) comments = models.TextField(max_length=250, … -
How model field will be field automatically with the user ids
I am creating a payment/paid-subscription for my django project. I decided to create a separate payment app and connect it to my django project. In below, you see the model for payment which I expect to have user ids with their payment status(for now just want to start with default=False): from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Payment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) paid = models.BooleanField(default=False) class Meta: db_table = 'payment' I created this, but in the database table, I see the user_id and paid are empty, while I have already a lot of users signed up. How to bring those ids here, with a default false paid? And what should I do to say django that after each new sign up fill this model as well? -
Django: select option with default field in template
I want to try select my default field in select option forms. My main form here is form and form.status gets all user possibility status and user_form.initial.status gets user current status: <div class="col-lg-9 select mb-3"> <select name="status" ng-model='discussionsSelect' class="custom-select form-control"> {% for status in form.status %} <option value="{{user_form.initial.status}}" {% if status == user_form.initial.status %}selected="selected"{% endif %}> {{status}} </option> {% endfor %} </select> </div> But it is not selected as default. -
how to store the cart id cookie or session, also past login
I'am still learning Django/Python and currently try to build an ecommerce site. What I want to do is to save the cart id somewhere. I have read about sessions, but learned that it removes the session_id on login. What I understood is that if a users creates a cart and somewhere in the process decides to login, the cart is lost (that is, the connection between user and cart is lost). So I thought to use the cookie and use set_cookie("value", card_id). But that requires me to use code like: response = HttpResponse("Cookie Set") response.set_cookie('python-tutorial2', 'gktcs.com') return response but I have no use for the response since I want to call the cart afterwards. So, basically, what I am asking is: what is the best way to store the connection between the user and the cart in such a way that it the cart_id is also retrievable if a user logs in (best: even if he logs out)? Or did I miss understand something or is there something else I am missing? Maybe this is a duplicate in which case I probably did not understand what happened there. (I have read 'quit some' in the past days). Pointers for where … -
Max and min values for a Django model field, according to the values already introduced
I want to create a model in Django where I could introduce integer values for a given field, with limits depending on the values already introduced for that field. Specifically, I would like the value introduced to be in the range of (min = 1 | max = maximum value for that field +1) The code should be something like that in the models.py file: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class MyModel(models.Model): max_myfield = MyModel.objects.filter(myfield=self.myfield).aggregate(Max('myfield'))["myfield_max"] myfield = models.IntegerField(validators=[MinValueValidator=1, MaxValueValidator=max_myfield + 1]) The problem with this is that max_myfield is using the MyModel itself, raising a NameError as it is not defined yet. In addition, if there is no record in the table, the max value shall be also 1, like the minimum. -
Can o.e project have more than one template directory
I saw one tutorial when a template folxer is made to live in an application folder. Is it possible for a django project to have more than one template folder? -
Django InlineFormset with M2M Field
I found a way to do forms of Models that are connected as Foreignkeys to each other. I am looking for a formset which will create a dynamic form that has a M2M relationship with each other, so following model: class PrescriptionLine(models.Model): id = models.AutoField(primary_key=True) drug = models.ForeignKey(Drug, on_delete=models.CASCADE) morning = models.FloatField(choices=[(val, val) for val in TABLET_INTAKE_QTY], default=0, blank=True, null=True) class Prescription(models.Model): id = models.AutoField(primary_key=True) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) line_prescription = models.ManyToManyField(PrescriptionLine, on_delete=models.CASCADE) note = models.TextField(max_length=100, default='') Now I can do something like this: PrescriptionFormset = inlineformset_factory( Prescription, PrescriptionLine, form=PrescriptionForm, fields=['drug', 'morning'], extra=1, can_delete=True ) But I can't do that because it says that PrescriptionLine has no ForeignKey to Prescription. How can this be done? Please help I am struggling with this for many months now. The formset itself is kinda ready if need I can add it here? -
How does a django render function know where this file is located?
Right so I am following a long a python Django tutorial and I am confused on how this render function knows where index.html is. The file I am in is views.py. from django.shortcuts import render from appTwo.forms import NewUserForm def index(request): return render(request,'appTwo/index.html') The file structure looks like -
Is the Django JsonResponse API or not?
Can I use json response instead of Django-REST-framework? If I can't, how I can build a web API using Django JsonResponse? -
Django 'str' object is not callable and subuser register
Im try different method for user register. I want to enroll a company staff user: I want to register method "companyname.staffusername" but I cant do register. How can I do it? Im try different way but I have error. I seen this error: "'str' object is not callable" Forms: from django import forms from django.db.models import fields from .models import SubUser class SubUserForm(forms.ModelForm): class Meta: model = SubUser fields = ["Subusername","Subpassword","active","staff","Company"] Views: from article.views import index from user.views import loginUser from django.contrib import messages from django.contrib.auth import authenticate from django.shortcuts import redirect, render from . import forms from .models import SubUser # Create your views here. def RegisterSubUser(request): if request.method=="POST": form = forms.SubUserForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("Subusername") password = form.cleaned_data.get("Subpassword") newUser = SubUser(Subusername = username) newUser.Subpassword(password) newUser.save() loginUser(request,newUser) messages.success(request,"Kayıt Başarılı") messages.warning(request,"DANGER") return render(request,"index.html") context ={ "form":form } return render(request,"register.html",context) else: form = forms.SubUserForm() context ={ "form":form } return render(request,"register.html",context) Models: from django.db import models # Create your models here. class SubUser(models.Model): Subusername = models.CharField(max_length=15,verbose_name="kullanıcı adı") Subpassword = models.CharField(max_length=15,verbose_name="Parola") active = models.BooleanField(default=True) staff = models.BooleanField(default=True) Company = models.ForeignKey("auth.User", on_delete= models.CASCADE,verbose_name="Çalıştığı Firma") def __str__(self): return self.Subusername -
Best method to store alt tags in Django
I am currently building a blog with Django and I would like to add a alt tag to my images for improving my SEO. My model is like this at the moment. My images are inside the Post class in models.py: class Post(models.Model): title = models.CharField(max_length=60) description = models.CharField(max_length=160) thumbnail = models.ImageField() My first thought is to define a separate Image class with the tag as one of its properties: class Image(models.Model): thumbnail = models.ImageField() alt_tag = models.Charfield() class Post(models.Model): title = models.CharField(max_length=60) description = models.CharField(max_length=160) image = models.ForeignKey(Image) So is this a correct or the prefered way of handling alt tags? I am using Amazon S3 to store these images, so maybe I could store alt tag as metadata. Or use a third party package like django-alttext? -
Statics not working with any of my projects after attempting to deploy
I was following for this deployment and at the last step my html will pull up but not any of my CSS styling. The weird part of all this is now none of the projects on my desktop will show their CSS either. So it did not only effect my portfolio but seems "my computer". any ideas? this is the error I get when I inspect it Refused to apply style from 'http://127.0.0.1:5502/projects/templates/%7B%%20static%20'css/styles.css'%20%%7D' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Set Up Server You can use something like Linode or Digital Ocean to follow these instruction. Step 1: Create a linode Step 2: Use terminal or any ssh client to login with root and run: ssh root@IP apt update && apt upgrade -y Step 3: Set hostname for server. I used test-server. You can use whatever you want. hostnamectl set-hostname test-server Step 4: Connect host ip and hostname run nano /etc/hosts and add your server ip, click tab and then your hostname (from step 3) Step 5: Install some dependencies run sudo apt install python-pip virtualenv ufw Step 6: Create a limited user and give sudo privlidges run adduser … -
Best way to run django on subdomain and react on main domain
Whenever a user goes to the (main domain), they should be able to navigate to the subdomain.(main domain) which is running the Django app. The main domain will be running the React app. My question is: Should Django and React be running on the same server but on different port numbers? or Should Django and React be running on different servers mapped by A-records? Assuming both approaches work, which would provide the best performance? -
Calling Django custom management command using Celery and Redis outputs "Unknown command" error
I am trying to call a function asynchronously in Django using Celery and Redis as a message broker. I am calling a function that calls call_command() to execute a custom management command I made. @app.task def processVideo(url): management.call_command('analyzevideos', url) However, calling processVideo.delay(url) produces the following error: django.core.management.base.CommandError: Unknown command: 'analyzevideos' I'm not sure why this error is occurring since calling management.call_command('analyzevideos', url) in the Python shell works perfectly fine. This question is similar to this one that has no answers. -
filter select field in django using ajax
I have a form with two fields related to each other and I want the rooms filtered based on the class in the front form this is my code models.py class Class(models.Model): class_name = models.CharField(max_length=100) def __str__(self): return self.class_name class Room(models.Model): room_name = models.CharField(max_length=100) class = models.ForeignKey(Class,related_name='class',on_delete=models.SET_NULL, null=True) def __str__(self): return self.room_name views.py class CustomFormView(LoginMixin, TemplateView): template_name = 'form.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['class'] = Class.objects.values('pk','class_name') context['rooms'] = Room.objects.all() return self.render_to_response(context) def get_related_rooms(request): class_id = request.GET.get('class_id') rooms = Room.objects.filter(class_id=class_id) return render(request, 'form.html', {'rooms': rooms}) form.html <form id="custom_form" data-rooms-url="{% url 'app:get_related_rooms' %}"> Class Name: <select type="text" class="form-control"id="class_name" onchange="test()" name="class_name"> {% for c in class %} <option value="{{ c.pk }}">{{ c.class_name }}</option> {% endfor %} </select> Room Name: </label> <select type="text" class="form-control" id="room_name" name="room_name"> </select> </form> //here is the ajax call to get the rooms <script> function test() { var classId = document.getElementById("class_name").value; $.ajax({ url: "{% url 'calculator:get_related_rooms' %}" , method: 'GET', data: { 'class_id': classId }, success: function (result) { // console.log(result) $("#room_name").append($('<option></option>').attr("value", 'pk').text('room_name')); } }) }; </script> the option .text('room_name')); is inserted when I select from class drop down , but I want it to come from database -
DURING installation of Django i got problem
The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. -
Django get_queryset method executed before dispatch
I have a heir of generic DetailView where I override get_queryset method, say: def get_queryset(self): return User.objects.filter(role=UserRoles.employee, team_leader=self.request.user) and in the same time, I want view to be accessible only to specific users, for example entitled as a leader. So I override a dispatch method: def dispatch(self, request, *args, **kwargs): dispatch = super().dispatch(request, *args, **kwargs) if not request.user.role == UserRoles.leader: raise PermissionDenied return dispatch My problem is that get_queryset method is executed before dispatch. Thus instead of getting 403, users who don't have leader title and thus no employees will receive 404. How to overcome it? -
Django for loop in views.py only gets the last occurence
I am trying to display a different price for each item in a list, based on the logged-in user information. However, my current code seems to overwrite the "price" key with the last occurrence "custom_price" each time... I cannot seem to find a solution. class MenuListView(ListView): model = Menu template_name = 'home.html' def get_context_data(self, **kwargs): if self.request.user.is_authenticated: context = super(MenuListView, self).get_context_data(**kwargs) user=get_object_or_404(Profile, user = self.request.user) coef = user.bmr menus = Menu.objects.all() price = [] for menu in menus: menu_price = menu.price menu_kcal = menu.kcal custom_price = (menu_price/menu_kcal) * (coef*(35/100)) price.append(custom_price) context['menus'] = menus context['price'] = price return context Template: {% for item in menus %} <div class="col-sm-6 col-md-6 col-lg-6"> <div class="food-card food-card--vertical"> <div class="food-card_img"> {% for img in item.photo_set.all %} <img src="{{ img.image.url }}" alt=""> {% endfor %} </div> <div class="food-card_content"> <div class="food-card_title-section"> <span class="food-card_title">{{ item.title }}</span> <span class="food-card_author">{{ item.category }} - {{ item.focus }}</span> </div> <div class="food-card_bottom-section"> <div class="space-between"> <div> <span class="fa fa-fire"></span> {{ item.kcal }} Kcal </div> </div> <hr> <div class="space-between"> <div class="food-card_price"> <span>{{ price }} €</span> </div> </div> </div> </div> </div> </div> {% endfor %} Could someone help ? Many thanks in advance ! -
Django evaluate python code accessing django model instance attributes in model method
I am using Django 3.1 and I want to create a model that allows an admin user to specify custom logic (Python code) as a field on the model. /path/to/app/models.py class FooModel(SomeBaseModel): slug = models.SlugField(max_length=64, blank=False, null=False, db_index=True, unique=True) code = models.TextField(null=False,blank=False) # ... def checkitout(self, **state): user = state["user"] execute_code(user) Example code to be run # django aware code # For each known category for category in Category.objects.all(): value = user.get_profile(category).amount if value > 1: doSomething() else doSomethingElse() Pseudocode for implementation of method def execute_code(self, user): code_to_execute=self.code # how to execute the code and pass user object to it? My question is, how to implement the model method execute_code() which will allow custom django code to be executed by the model?