Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- how to create submenu
I am envisioning to create menu with links to various pages. I want to create submenu which should be visible when particular main menu option is clicked. Please suggest what I am writing wrong. <nav id="primary-menu"> <ul class="main-menu text-center"> <li><a href="{% url 'index' %}">{% if '/' == request.path %} <mark>Home</mark> {% else %} Home {% endif %}</a> </li> <li><a href="{% url 'listings_residential_rent' %}">{% if 'listings_residential_rent' in request.path %} <mark>Residential Rent</mark> {% else %} Residential Rent {% endif %}</a> </li> <ul class="sub-menu"> <li><a href="#">Submenu1</a></li> <li><a href="#">Submenu1</a></li> </ul> <li><a href="{% url 'admin:index' %}">{% if user.is_authenticated %} Welcome {{ user.username }} {% else %} Realtor Login {% endif %}</a> </li> </ul> </nav> -
django - saving more than one information from foreign key
I have three model User, Topic and Major class User(AbstractUser): email = models.EmailField(_("Email Address"), max_length=254, unique=True) first_name = models.CharField(_("First Name"), max_length=254) last_name = models.CharField(_("Last Name"), max_length=254) major = models.ForeignKey(Major, verbose_name=_("Student Major"), on_delete=models.SET_NULL, null=True) class Major(models.Model): code = models.CharField(_("Major Code"), max_length=10,unique=True,) name = models.CharField(_("Major Name"), max_length=250) class Topic(models.Model): name = models.CharField(_("Name"), max_length=400) description = models.TextField(_("Description")) created_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name="created_by") I'm using this repository to save created_by column Now, I want to save the Major code of created_by user on the Topic, i don't know how to pick and save the Major code or created_by user. My end goal is at the end Topic will only displayed to user who has the same major with the person on created_by -
How to deploy a django + django channels docker container in heroku?
I have a dockerized django api backend hosted on heroku. I've used the heroku documentation to deploy the docker container https://devcenter.heroku.com/articles/container-registry-and-runtime. Now I integrated django channels, it works fine locally after i followed the basic installation tutorial https://channels.readthedocs.io/en/stable/installation.html, but it doesn't work on heroku enviroment. What is the best way to deploy a dockerized django channels to heroku? -
Migrating Fixtures to Django Test Database
I need to use a custom database for my tests. I can ensure this by a custom setting file for tests. How can I export fixtures to this test database? (e.g. superuser for tests or other test related database exports) I'm ready to apply other solutions instead of fixtures if fixtures are not applicable to second custom database. Here's my custom setting file for testing: (settings/test.py) from defaults import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_test_db', } } Here's how I run the tests: python manage.py test --settings=settings.test -
Setting up an academic year in Django
I am fairly new to Django, and find it best to learn by doing but I am truly scratching my head on this one. I am building a pricing tool to practise but I would like to be able to set a rolling academic year regardless of the current year. The fiscal academic year ends at the 31st of March every year so this would be ideal. It would also allow me to pro-rata prices generated by the quoting based on the current month until the next occurrence of March. To summarise: Fiscal year ends at the end of March every year Will be a rolling fiscal year Need to account for pro-rata data, £100 per month so if it is mid-January then it will cost them £200 for contract to start in February. I have searched high and low but it is time to admit defeat and ask those much wiser than me. Your help is appreciated, let me know if you need any more information. -
django admin - displaying multiple column of data in one column from foreign key using list_display
So, I have 2 tables user and major, major as foreign key on the user model. Right now the 'major' on list_display only displaying the name column from major model I need to display column name and rank from major model on the list_display is there a way to do this from django.contrib.auth.admin import UserAdmin as OrigUserAdmin class ProfileAdmin(OrigUserAdmin): list_display = ('username', "email", 'major', 'student_id',) -
Django ldap3 : how to retrieve users belonwing to a CN group
I am trying to implement a login screen on a Windows 2012 server with Django, which brings the Windows AD users belonging to a certain group. For that, I am using ldap3. I put the following code in settings.py: LDAP_AUTH_URL = "ldap://server:389" LDAP_AUTH_USE_TLS = False LDAP_AUTH_SEARCH_BASE = "CN=DevGroup,OU=Groups,OU=America,DC=domain,DC=company,DC=com" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "domain" LDAP_AUTH_CONNECTION_USERNAME = "user" LDAP_AUTH_CONNECTION_PASSWORD = "pass" It is not giving any error (it appears the lookup OK message). However, it isn't retrieving any users to the auth_users table. Doing some research, I saw that the problem is that the users are within the group CN=DevGroup, so I put LDAP_AUTH_OBJECT_CLASS = "group" in stead of "user". That "works" and bring the groups to auth_user table, but I want to bring the users belonging to CN=DevGroup. Can you help me, please? I've been reading a lot of comments and doing a lot of tests, but I can't get it to work. Thank you so much. -
Bootstrap Glyphicons not showing in Django
I am trying to import the bootstrap cdn and display some social icons. For some reason, it is not showing what am I doing wrong? {% load static %} <!DOCTYPE html> <head> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'main/css/styles.css' %}" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <div class ="right"> <span class="glyphicon glyphicon-envelope"></span> </div> </body> -
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?