Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you add a favicon to HTML page?
I know this is a duplicate question, but I was trying to add a favicon.ico file to my site on localhost:8000 made with Django. The favicon exists on templates\articles (in an app called articles), and I've tried everything on stackoverflow, youtube, and used , but nothing works. Do I have to define the Django URL/view for the ICO file, as localhost:8000/favicon.ico brings up error? Here's my (simplified) code by the way: <title>Newsreed | Articles</title> <link rel="shortcut icon" type = 'image/x-icon' href="favicon.ico"> What should I do, because I've been struggling with it for several days now and tere has been no solution on anything. -
Using Django to pull from bitbucket and push to bitbucket
cannot provide lots of code yet, but I am learning how to push/pull data from bitbucket using Django to create a web application allowing a user to do so. I have been looking for guides online to use bitbucket instead of lets say sqlite3. as my end result is to have an application that allows a user to edit fields, and having the web application push to a bitbucket server, but obviously firstly pulling the information before pulling. What is the best guide for this? I can see in mysite/settings.py I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } How can I connect this to an outter source such as github/bitbucket/git instead of using a local database? if anyone can point me to a tutorial, that could help would be greatly appreciated. Once again this is my first real Django web application, so I am trying to provision this the best I can. -
Fetching data from template to send email
please this is the html file i am trying to fetch the data <form action="{% url 'send'%}" method="post" role="form" class="contactForm"> {% csrf_token %} <div class="form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div class="validation"></div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div class="validation"></div> </div> <div class="form-group"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" /> <div class="validation"></div> </div> <div class="form-group"> <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea> <div class="validation"></div> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> and this is my views.py which i collected the data from the html file def sendEmail(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send_mail( "Contact Form", message, email, settings.EMAIL_HOST_USER, fail_silently=False ) return render(request, 'app/index.html') and my settings for the email which i am using gmail EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '*****@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 EMAIL_USE_TLS = True and my urls.py is which i sent it to my url to the views urlpatterns = [ path('',views.index,name='index'), path('sendmail/', views.sendEmail, name='send'), ] -
Importing model classes from other apps without causing circular reference in Django
I have 3 apps products, sales, purchases. each app has a correspondingly named Model class, Product, Sale, and Purchase. products/models.py class Product(models.Model): Name = models.CharField(max_length=32) sales/models.py class Sale(models.Model): Product = models.ForeignKey('products.Product', on_delete=models.CASCADE) purchases/models.py class Purchase(models.Model): Product = models.ForeignKey('products.Product', on_delete=models.CASCADE) And I decided to make custom managers for the Model classes so that I can keep all the logic in the model files (by overriding objects attr for each class) when I'm writing the methods in the custom manager I imported Sale model In products.models and Product model in sales.models which creates a circular reference, I was able to get away with it by performing the imports in the methods themselves but I remember reading online that circular imports are sign of bad code writing. So my question is how can I avoid circular imports in this case and have access to the Product Model in sales.models and Sale in products.models. -
How to show data already on the database in a update form in Django?
I currently have a form that successfully updates both the model Userand Client. The only thing I want it also to do is, when accessing the update page, that the form already have the current information (like we can do with placeholders, but actually editable data) so that the client can edit what he needs. I also wonder if there is a way of updating only the changed fields or if it must update everything, even if it is the same. This is my form: class UpdateClient(ModelForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control'})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) def clean_nif(self): nif = self.cleaned_data['nif']; if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.") return nif def __init__(self, *args, **kwargs): super(UpdateClient, self).__init__(*args, **kwargs) self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['last_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['email'].widget = EmailInput(attrs={'class': 'form-control'}) class Meta: model = User fields = ('email','first_name','last_name', 'address', 'nif', 'mobile') And this is my views.py: def client_det(request, nif): ls= Clients.objects.get(nif=nif) if request.method == 'POST': form = UpdateClient(request.POST, instance=ls.user) if form.is_valid(): user = form.save() user.refresh_from_db() user.clients.address = form.cleaned_data.get('address') user.clients.nif = form.cleaned_data.get('nif') user.clients.mobile = form.cleaned_data.get('mobile') user.clients.save() return redirect('clients') else: form = UpdateClient() return render(request, 'backend/client_detail.html', {'form': form, 'ls': ls}) And my client_detail.html … -
Model design django
The model looks as follows. Where apps is a field which can have only app1 and app2 as choices which can be incremented in the future. Also, each app choice (app1, app2) should be a model with fields representing features. How to implement this in Django models. apps: app1: feature1: "Data" feature2: "Data" app2: feature1: "Data" feature2: "Data" -
Need help , associate user to a post
hi everyone i'm trying to make a blog and i want to associate a user to post .. and to comment , it's a multi-user blog and i don't know how to do it , any help guys ? ! here is the model file : from django.db import models from django.utils import timezone from django.conf import settings from django.utils.text import slugify # Create your models here. #this is for categories class Category(models.Model): title=models.CharField(max_length=100,default='') def __str__(self): return self.title #this is where a user can create his own gigs class Gigposter(models.Model): title=models.CharField(default='',max_length=100,blank=False) user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=False) categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',null=False) published_at=models.DateTimeField(auto_now_add=True) description=models.TextField(default='',max_length=None,blank=False) mainphoto=models.ImageField(default='') photo=models.ImageField() def __str__(self): return self.title #this is where a user can comment and say what he thinks about others work class Comment_area(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False) comment=models.TextField(max_length=None,default='') commented_at=models.DateTimeField(auto_now_add=True) and the views file is empty as you can see : from django.shortcuts import render # Create your views here. -
Django: ManyToManyField appears as empty on my template
I'm having an issue displaying a ManyToManyField in a character profile template using Django. The template has to show an avatar, alongside some information about the character, including a list of guilds this character had joined. But, when I try to display that list, it appears as if it is empty. I had a look into my site administration page, and that information is there, so I have confirmation that the data can be displayed in my template. I just don't know how. How could I handle that? These are my models: """ Modelos de la aplicación de personajes """ from django.db import models class Guild(models.Model): """ Modelo del clan """ guild_name = models.CharField(max_length=25) rank = models.PositiveSmallIntegerField() def __str__(self): return self.guild_name class Character(models.Model): """ Modelo del personaje """ character_name = models.CharField(max_length=25) level = models.PositiveSmallIntegerField() race = models.CharField(max_length=25) gender = models.CharField(max_length=25) job = models.CharField(max_length=25) avatar = models.ImageField(upload_to='', blank=True) character_guilds = models.ManyToManyField(Guild, blank=True) def __str__(self): return self.character_name+': '+self.race+' '+self.job+' level '+str(self.level)+'. ' My view.py file: def characterprofile(request, pk): """ Método para mostrar el perfil de un personaje """ template = '../templates/character/characterProfile.html' profile = Character.objects.get(pk=pk) guilds = profile.character_guilds.all() context = { 'profile': profile, 'guilds': guilds } return render (request, template, context) And my … -
ValueError Django CSV
All I'm trying to do is through Django display my CSV table on the page. And everything seems to work, but for some reason I get an error and I can’t find a solution to it ValueError: The view csv_app.views.csv_simple_read didn't return an HttpResponse object. It returned None instead. [19/Feb/2020 21:40:07] "GET / HTTP/1.1" 500 57986 I'm new to django. I would be very grateful for any help. Views.py import csv import os def csv_simple_read(request): path = os.path.dirname(__file__) file = os.path.join(path, 'csv_simple_read.csv') with open(file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') line_count = 0 for row in csv_reader: print('\n\nColumn names are {}, {}, {}, {}'.format(row[0], row[1], row[2], row[3])) line_count += 1 csv_simple_read.csv test3;2020-02-16;05:22:49;OK test2;2020-02-16;05:22:25;OK test1;2020-02-16;05:22:10;OK test3;2020-02-16;05:22:49;OK test2;2020-02-16;05:22:25;OK test1;2020-02-16;05:22:10;OK csv_home.html <body> <h3>CSV Example - Read Write Examples</h3> <ul> <br> <li>Read Operation <ul> <li> <a href="{% url 'csv_simple_read' %}">Simple CSV Read Operation</a> </li> </ul> </li> </ul> {{csv_data}} {% if csv_data %} sad {{csv_data}} {% endif %} </body> -
is it possible customizing django admin dashboard with bootstrap template?
I want customize my django admin dashboard. Like php based framework code-igniter there are many admin template that we can used in admin panel/dashboard. Basically i want change my admin panel looking. -
ProgrammingError at /register relation "small_small_hr_staffprofile" does not exist
I'm running into this error while trying to post a form for creating a user or logging in. I noticed for some reason some tables were not created in my db when i ran python manage.py makemigrations/ migrate. My db settings look ok. Any ideas why this is happening? ProgrammingError at /register relation "small_small_hr_staffprofile" does not exist LINE 1: INSERT INTO "small_small_hr_staffprofile" ("created", "modif... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Swift_hr', 'USER': 'postgres', 'PASSWORD': '*********', 'HOST': '127.0.0.1', 'PORT': '5432' } } -
Django - how to create field as dropdown list from database table values and then post back to database
This is being posted by a newbie who has been working on these 2 problems for over a week straight, with no results, and now am seeking help from the professionals on how to accomplish the following. I have 2 pages. The first page provides a search for an ASSIGNMENTS.ID. Then the value is passed to a second page where the data for the ASSIGNMENTS is displayed. Below that all of the PRODUCTS linked to the ASSIGNMENTS.ID, as fk, are displayed in a table. This works great. (PROBLEM #1 requesting help with:) I would like to make the PRODUCTS.STATUS_CODE field on page 2 as a dropdown list of values from the data in the table. This would allow the user to change the value of the PRODUCT.STATUS_CODE, by selecting another value from the dropdown list. (PROBLEM #2 requesting help with:) After the PRODUCT.STATUS_CODE value change, how do I code to submit the page with changed STATUS_CODE value to be saved in the database. NOTE: The page 1 relates to the 'cancel_form_view' and the 'cancel_form.html' The page 2 relates to the 'cancel_result_view' and the 'cancel_results.html' Here are the code in Django files. MODELS.PY from django.db import models class Assignments(models.Model): id = … -
Testing removal of django whitenoise
In my django microservice, I have copied some of the whitenoise related code along with other code which I don't need because it should get handled at the CDN level. I have removed "whitenoise.middleware.WhiteNoiseMiddleware" from the settings.py but I'm not sure how to check if I need to remove anything else. In simple words, how do I check if my microservice is using whitenoise or not? -
Django deleted DDBB table and cannot migrate anymore: no such table error
I've deleted a table from the sqlite DDBB because I wanted to make some changes and wasn't able to do those with a simple update of the models in Django. Since then, I am not able to perform migrations again and get a new table for my models, getting the error "django.db.utils.OperationalError: no such table: shop_productitem". I've tried to follow many hints in other similar threads with no luck. I've tried this and this for example and I cannot solve the issue. My understanding is that if I run makemigrations and then migrate the models the ddbb should update itself with the new specifications, but I'm probably mistaken in this specific case. Can someone address me where the problem would sit? I fear I have not the necessary knowledge to figure this out of my own, I've been looking for ages. Please find below the whole error message I'm getting: Applying shop.0002_auto_20200218_1958...Traceback (most recent call last): File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: shop_productitem The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, … -
How To Reload Html Page Conent in Django using api
Hi Everyone I Create a Django BTC app that can get a bitcoin price via api but i want to know how to update price in template if btc price change i want to update in template but i don't know how to do it My Problem is how to refresh page content without reloading page Here is my views.py from django.shortcuts import render from django.http import HttpResponse import requests # Create your views here. def index(request): url = 'https://min-api.cryptocompare.com/.....' price_json = requests.get(url).json() price = price_json['USD'] print(price) return render(request,'p.html',{'price':price}) Here is my p.html: <h1>Price is {{ price }}</h1> The Result is Static BTC PRICE I Want Something Like This If Api Get New BTC Price Change the price in html without user to reload! -
how to use django framework as backend and reactjs as frontend?
I using django and I want to switch to reactjs as frontend framework and I am wondering if I use reactjs how its works with django forms and how I am supposed to do data validation in the backend side ?? thanks -
Trouble using django File.chunks() generator
I want to process a file uploaded with a form in Django. This file is a TemporaryUploadedFile so I need to save it first somewhere on disk. I followed the django doc related to file uploads, hence using chunks generator. My function looks like this : def handle_uploaded_file(myfile): temp_filepath = myfile.temporary_file_path() with open(temp_filepath, 'wb+') as destination: for chunk in myfile.chunks(): destination.write(chunk) ds = DataSource(temp_filepath) Problem is the for loop does nothing, though my file is correct because I can populate a list then iterating over that list and it works (see below)… I'm confused by this behaviour, can someone explain where I'm wrong ? This works : def handle_uploaded_file(myfile): chunks = [] for chunk in myfile.chunks(): chunks.append(chunk) temp_filepath = myfile.temporary_file_path() with open(temp_filepath, 'wb+') as destination: for chunk in chunks: destination.write(chunk) ds = DataSource(temp_filepath) I can't explain to myself why the generator is not generating in the first example… -
Fatal Python error: Cannot recover from stack overflow django postsave
# Create your models here. class SavedTest(models.Model): banner = models.URLField(null=True, editable=False) date_uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title @receiver(post_save, sender=SavedTest, dispatch_uid="update_imdb_banner") def saved_test_save(sender, instance, **kwargs): instance.banner = "https://www.test.com" instance.save() My goal was to change the banner field of the instance to what I choose but I get fatal python error. -
Django referencing foreignkeys on updates
I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit. I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value. Which I did: for entry in params: item = {} if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']: item[entry] = params[entry] if entry == 'code': item[entry] = Demo_user_sessions.objects.get(session=session_key) obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item) This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey. Here my model for the entry that I am trying to make. class Demo_user_sessions(models.Model): session = models.CharField(primary_key=True, max_length=8) timestamp = models.DateTimeField(auto_now_add=True) code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True) # ... some other class Meta: ordering = ['timestamp'] def __str__(self): return self Here my current error message when doing: Traceback (most recent call last): File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) … -
Multiple User types and Roles for Django
How can I make multiple user types with different roles and access for Django with different access roles and functions for each user type? I'm relatively new with Django and I just need some guidance on where should I go next. Right now I followed some tip I found online and I went with thisusing abstract user and I plan to replace the User template but I'm not completely sure if I'm going to go all in or if I need to modify this for later. I'm also not sure If I have to create another seperate app for each of the access type or do I have to stick with this app that I created. Right now my goal is to create a database that should contain the intended roles: class User(AbstractBaseUser): USER_TYPE_CHOICES= ( (1, 'pqa'), (2, 'tester'), (3, 'test_lead'), (4, 'test_manager'), (5, 'admin'), ) email=models.EmailField(max_length=255, unique=True) full_name=models.CharField(max_length=255,blank=True,null=True) active= models.BooleanField(default=True) birth_date=models.DateField(null=True,blank=True) hire_date=models.DateField(null=True,blank=True) user_type=models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) def __str__(self): return self.full_name I'm not sure what to do next to be honest, I just need some help or a hint on what to do next. TIA! -
How do you send a value from a template in one app to a template in another app in Django
I am trying to build a booking website and I have two seperate apps for now. One app is hotel one is booking. I have a list of hotels, you can click on a hotel and it takes you to a page with the details of that hotel and a book button. In the bookings app i have a form that creates a booking where the users types in his information and the info of the hotel. I am trying to have that when the user click on the book button in the Hotel View it takes them to the create booking in the bookings app and fills in the hotel information automatically. In my root directory I have a folder named hotels where all the views urls and templates for hotels are and another one for bookings. I am trying to do this using django -
How do I prevent my script from being run every time a Docker container is brought up?
I would to run a script (populate my MySql Docker container) only when my docker containers are built. I'm running the following docker-compose.yml file, which contains a Django container. version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 depends_on: - mysql apache: restart: always build: ./apache/ ports: - "80:80" #volumes: # - web-static:/www/static links: - web:web volumes: my-db: I have this web/Dockerfile FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY entrypoint.sh /app/ COPY . /app/ RUN ["chmod", "+x", "/app/entrypoint.sh"] ENTRYPOINT ["/app/entrypoint.sh"] and these are the contents of … -
How to log exceptions from django management commands to file without hacking manage,py?
Consider the following manage.py command: class Command(BaseCommand): def handle(self, *args, **options): raise Exception('Test exception') Is there a way to make django log that exception to a specific file automatically without wrapping handle() function in a big try-catch or without hacking the manage.py itself, which basically mean I do the logging myself. I mean something like configuring admin mail handler for views, but log to file instead of an email and management command instead of a view. Then raise exceptions from any place inside a management command and be sure they will be logged. -
Django REST Framework: Using the Accept-Language header to set an instance's "locale"
So, I have a model with the following attribute: locale = models.CharField(max_length=10, choices=get_locale_choices(), default='en-gb') The associated serializer for this model is currently: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' I then call a create endpoint: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) I was wondering, how best to modify the above to allow the locale attribute of MyModel to be updated by the Accept-Language header en-GB,en;q=0.5. I get my locale choices from django.conf.locale.LANG_INFO: from django.conf.locale import LANG_INFO def get_locale_choices(): return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v] I guess I need to pass in the request.headers as some sort of extra context...? But I'm thinking, what if the Accept-Language is not set, etc? -
LoginRequiredMiddleware not working for Unauthenticated User
I am trying to automate the links access for authenticated and unauthenticated users using LoginRequiredMiddleware. The code is not working as unauthenticated users can still open other urls which they are not supposed to. Please see my code below and advise. Thanks. urls.py from django.urls import path from . import views from django.contrib.auth.views import ( LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView ) urlpatterns = [ path('', views.home, name = 'home'), path('column/', views.column), path('login/', LoginView.as_view(template_name='accounts/login.html'), name = 'login'), path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name = 'logout'), path('register/', views.register, name = 'register'), path('profile/', views.view_profile, name = 'view_profile'), path('profile/edit/', views.edit_profile, name = 'edit_profile'), path('change_password/', views.change_password, name = 'change_password'), path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name = 'password_reset'), path('reset-password/done', PasswordResetDoneView.as_view(), name = 'password_reset_done'), path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path('reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] settings.py STATIC_URL = '/static/' LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' LOGIN_EXEMPT_URLS = ( 'logout', 'register', ) LoginRequiredMiddleware.py import re from django.conf import settings from django.urls import reverse from django.shortcuts import redirect from django.contrib.auth import logout EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') if request.user.is_authenticated is False: if view_func.__name__ …