Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Define FileField upload_to directory in Django model
I have a model Audiopart with field filename = models.FileField(upload_to=get_upload_path, blank=True) and function for generating upload path def get_upload_path(instance, filename): return os.path.join( 'audio', instance.book_id.folder, filename ) So file uploads to directory (for ex. "audio\mybook\a1.mp3"), that's good. And in database in field "filename" stores path "audio\mybook\a1.mp3". Is any way to save in DB just filename "a1.mp3", without "audio\mybook\"? -
how to use django-redis hset operation in redis cache
I am using django 3.0.4 and python 3.6.9. I have to use hset operation to set some values in redis cache. My try: from django.core.cache import caches cache.set(), cache.get() // these operation are working But I am not able to use hset and hget operation using this library. There is no proper documentation about this in Django official docs. Note: I have referred this (Not A copy) -
django: Use different configuration for test database?
Can I specific a different configuration for the test database? Or alternatives simply use a different user in production?(how to manage that as settings file needs to be updated as well?) The testing requirements for postgresql require in my opinion too many privs like create DB and in my case I also need to create an extension upon db creation which means superuser privileges. -
matching query does not exist django heroku
i have deployed my app to heroku.. But when i try to go to the page, i get this error from log: apps.adminview.models.Templates.DoesNotExist: Templates matching query does not exist. This is from my adminview models, as you can see it is created correctly: ... class Templates(models.Model): description = models.TextField(null=True, blank=True) template_name = models.TextField(null=True, blank=True) isSelected = models.BooleanField(default=False) temp_selected = models.BooleanField(default=False) width_field = models.IntegerField(default=0, null=True) height_field = models.IntegerField(default=0, null=True) image_path = models.ImageField( width_field="width_field", height_field="height_field" ) def __str__(self): return "("+str(self.id)+") " + self.template_name Anyone could help me with this? Thank you!. -
Why can't I display more fields in django?
I'm Trying to develop a social website, and I want to display the bio and blood group of the user on their profile page along with their name and email. While the name and email are being Displayed in the profile page, their bio and blood group are not being displayed although I wrote the same code for them as their name and email. Can anyone please help me out? My models.py : from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' my forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() CHOICES = ( ('type', 'AB+'), ('type', 'AB-'), ('type', 'A+'), ('type', 'A-'), ('type', 'B+'), ('type', 'B-'), ('type', 'O+'), ('type', 'O-'), ) bloodgroup = forms.CharField(widget=forms.Select(choices=CHOICES)) bio = forms.CharField() class Meta: model = User fields = ['username', 'email', 'bio', 'bloodgroup', 'password1', 'password2'] my profile.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> <p class="text-primary">{{ user.bio }}</p> <p2 class="text-info">Blood Group - {{ … -
Django raw sql insert query in triple quotation: Django interprets null values from ajax request data as None column
I am working on a Django/React project. Using DRF, I am throwing an API route for performing SQL queries in my PostgreSQL database. But I am having issues with my current code setup. I have setup my INSERT query in the API as raw queries (using cursor) enclosed in a triple quote multi-line string """INSERT...""", then format my values using string formatting %s. In my API, I capture each request body into a variable. Everything works fine if all request data are filled. But, if it is null, Django obviously assigns None to the variable. Now back to my sql query, Django will treat the null %s as None and as a table column instead of a correct null value, thus throwing a ProgrammingError column "none" does not exist. Here are sample codes: React Frontend const [lastName, setLastName] = useState('') const [firstName, setFirstName] = useState('') const [middleName, setMiddleName] = useState('') const [nameExtn, setNameExtn] = useState('') const [sex, setSex] = useState('') const [civilStatus, setCivilStatus] = useState('') const [bloodType, setBloodType] = useState('') const [height, setHeight] = useState('') const [weight, setWeight] = useState('') const newPersonalInfo = (token, data) => { let endpoint = "/jobnet/api/profile/pds/basic/personal/" let lookupOptions = { method: "POST", headers: { 'Content-Type': … -
How do I add my custom field in django filter?
I am creating an API to return posts on a user profile. The posts can be public, friends only or with custom privacy. Here is my filter: posts = Post.objects.filter( Q(created_by=user, privacy='PUBLIC') | Q(created_by=user, privacy='FRIENDS')| Q(created_by=instance, privacy='CUSTOM', custom_list=requested_by.pk)) Here I want to get the 'friends_only' posts if the requested user is friend of the user whose profile I am showing. Problem is I don't have any relation between Post and Friend. I am using a Friend model as shown below: class Friend(models.Model): sender = models.ForeignKey(UserProfile, related_name="sender", on_delete=models.CASCADE) receiver = models.ForeignKey(UserProfile, related_name="receiver", on_delete=models.CASCADE) accepted = models.NullBooleanField(default=None) and Post model as: class Post(BaseModel, models.Model): PRIVACY_CHOICES = [ ('PUBLIC', 'Public'), ('PRIVATE', 'Private'), ('FRIENDS', 'Friends only'), ('CUSTOM', 'Custom') ] text = models.TextField() image = models.ImageField(upload_to="assets/posts/", null=True, blank=True) created_by = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE) privacy = models.CharField(max_length=10, choices=PRIVACY_CHOICES) custom_list = models.ManyToManyField(UserProfile, related_name="post_by_friends", blank=True) liked_by = models.ManyToManyField(UserProfile, related_name="likes", blank=True) My question is how can I filter the Post model by providing my condition in filter is_friend = True -
Unable to import Django model into Python shell
I am recently trying to lean APIs using DJango Rest. I have a model to work with: class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question I want work with the model in the python shell, but whenever I do: from polls.models import Poll in python shell, it shows: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. could anyone help? I am also working on a virtual env -
is Django 'app' equal to 'component' in Angular?
Just started learning Django, as an Angular developer can we say that apps in Django are similar to Angular components ? -
How to override default formats in the data and time fields using Django rest framework?
I tried to override the default formats in time and date fields using the Django rest framework but it's not working. So I added to format and input_format parameter in fields. still, I facing that issue. I refer to the many documentation and many StackOverflow answers. Still, it's not working. anyone can help me. How to solve this error Models.py class Showss(models.Model): show_Time = models.TimeField() Serializer.py class ShowSerializer(serializers.ModelSerializer): show_Time = serializers.TimeField(format='%H:%M:%S', input_formats='%H:%M:%S') class Meta: model = Showss fields = '__all__' settings.py REST_FRAMEWORK = { "TIME_INPUT_FORMATS": [("%H:%M:%S"),] } -
How do I auto login after registration in Django?
So, I'm trying to let the user be automatically logged in as soon as he/she registers. Here's my register function. def register(response): if response.method == 'POST': form = RegisterForm(response.POST) if form.is_valid: form.save() return redirect('/main/inputuserinfo') else: form = RegisterForm() return render(response, 'register/register.html', {'form' : form}) As I mentioned, I'd like to log the user in right after he/she registers, then redirect him/her to '/main/inputuserinfo'. But I have no idea on how I can create it. I very much appreciate your help. :) -
unable to save model form data in database. gives patientmedinfo.errors = none and patientmedinfo.is_valid() = false
'I am new to django , trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where i am going wrong. models.py from django.db import models # Create your models here. class PatientInfo(models.Model): sex = ( ('M', 'Male'), ('F', 'Female') ) first_name = models.CharField(max_length=35) middle_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length= 30) sex = models.CharField(max_length=1,choices=sex) date_of_birth = models.DateField() height = models.FloatField() weight = models.FloatField() phone_no =models.CharField(max_length=15) class PatientHist(PatientInfo): Yes_No = ( (True, 'Yes'), (False, 'No'), ) Veg_nonveg =( (True,'Veg'), (False,'Non-Veg'), ) diabetes = models.BooleanField(default=False,choices=Yes_No) diabetes_long = models.CharField(max_length=20) hypertension = models.BooleanField(default=False,choices=Yes_No) hypertension_long = models.CharField(max_length=20) obesity = models.BooleanField(default=False,choices=Yes_No) obesity_long = models.CharField(max_length=20) pcod = models.BooleanField(default=False,choices=Yes_No) pcod_long= models.CharField(max_length=20) thyroid = models.BooleanField(default=False,choices=Yes_No) thyroid_long = models.CharField(max_length=20) heartdiease = models.BooleanField(default=False,choices=Yes_No) heartdiease_long = models.CharField(max_length=20) liverdisease = models.BooleanField(default=False,choices=Yes_No) liverdisease_long = models.CharField(max_length=20) kidney = models.BooleanField(default=False,choices=Yes_No) kidney_long = models.CharField(max_length=20) familyhistory = models.BooleanField(default=False,choices=Yes_No) currentmed = models.CharField(max_length=20) foodhabit= models.BooleanField(default=False,choices= Veg_nonveg) hba1c = models.FloatField(max_length=20) fasting = models.FloatField(max_length=20) pp = models.FloatField(max_length=20) forms.py from django import forms from .models import * class Patient_form(forms.ModelForm): class Meta: model = PatientInfo fields = "__all__" class PatientHistory_form(forms.ModelForm): class Meta: model = PatientHist widgets = { 'diabetes': forms.RadioSelect, 'hypertension': forms.RadioSelect, 'obesity': forms.RadioSelect, 'pcod': forms.RadioSelect, 'thyroid': … -
mypy gives an error while importing submodule : Module has no attribute
When I am checking my modules through mypy it gives me this error: Module 'django.contrib.gis' has no attribute 'forms' and I am importing forms like this " from django.contrib.gis import forms ". I know it is correct but mypy shows this error message. I could import like this: from django.contrib import gis and use forms as gis.forms but I do not want to. Can anyone help me to fix this? Thanks. -
What is difference between django-bootstrap4 and bootstrap4?
I am beginner in Django web development & currently I am using using bootstrap4 by loading bootstrap.min.css & bootstrap.min.js as below in html files. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> Recently I have found that there been module in Django named django-bootstrap4 & I am reading its documentation also. https://django-bootstrap4.readthedocs.io/ I have tried to find difference between those but not found any. Which will be suitable to use in web development? Tried to find answer on google but not found any so please can someone explain me difference between these two? -
How to append values in a tabular format from JSON in Django Template?
I am making a small web application that allow user to perform OCR on the selected image and provides the JSON output in a tabular Format like this. What I'm facing now is when I'm selected new image to add values in the table, it overrides the values instead of appending. And what I want is to append new value in the table by choosing another image, the previous row show me stay as it is and new will get append. So that finally I can submit all the values to the database all together by clicking on the submit button. Here is my template code : <form method="post">{% csrf_token %} <div class="table-responsive"> <table id="datatable2" class="table order-column hover"> <thead> <tr> <th>Investigation Name</th> <th>Result</th> <th>UOM</th> <th>Low Range</th> <th>High Range</th> </tr> </thead> <tbody> {% for key, value in data.items %} {% for key2,value2 in value.items %} <tr class="gradeX"> <td>{{ value2.test_name }}</td> <td>{{ value2.results }}</td> <td>{{ value2.units }}</td> <td>{{ value2.low_range }}</td> <td>{{ value2.high_range }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> </div> <!--end .table-responsive --> <button type="submit" class="btn btn-primary" name="data">Submit</button> </form> How can we use list in DTL to store the previous values and stay as it is and the new … -
Does django caches queryset results if those querysets are used (or deleted) later?
a = SampleModel.objects.filter(Id=2) b = SampleModel.objects.filter(Id=3) If a and b: print(true) a.delete() b.delete() Now in above code...how many time is database hit? It will be hit when calling a and b in if statement. But will database also be hit on .delete() operations. Or django has some cache mechanism which caches the queryset results? -
Getting ImportError on Django3.0.4 while running runserver [duplicate]
I have been trying to run the latest versionof django3.0.4, but I'm getting error while trying to run the local server. I tried installing the package six eventhough it was already installed. pip install six current version being used is six-1.14.0 pip install --upgrade django-cors-headers current versio being used is django-cors-headers-3.2.1 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/rest_framework/templatetags/rest_framework.py", line 9, in <module> from django.utils import six ImportError: cannot import name 'six' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/utils/autoreload.py", … -
how to change input durationfield format using forms like 3w 3h 3m. I tried several ways.Please help .I am fresher
Forms.py class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } class DurationInput(TextInput): def _format_value(self, value): duration = parse_duration(value) seconds = duration.seconds minutes = seconds // 60 seconds = seconds % 60 minutes = minutes % 60 return '{02w}{02d}{02h}{02m}'.format(minutes, seconds) models.py ESTIMATION_TIME = models.DurationField(null=True, blank=True) -
Email to Register Confirmation Django
The confirmation email is arriving normal at test@hotmail.com. But whenever I click the message appears:'Activation link is invalid!' ever. Can someone help me? Views.py def register(request): if not request.user.is_authenticated: if request.method == 'POST': register_status = register_user(request) if register_status != 1: messages.error(request, register_status) return redirect('register') #Register Success else: user = get_user_model() subject = 'Confirm your account' current_site = get_current_site(request) message = render_to_string('users/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) from_email = 'myacount@gmail.com' to_list = [from_email , 'test@hotmail.com'] send_mail( subject, message, from_email, to_list, fail_silently=False, ) messages.success(request, 'Please confirm your email') return redirect('login') else: return render(request, 'users/register.html') else: messages.error(request, 'You are already logged in') return redirect('index') def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = get_user_model() user = User.objects.get(pk=uid) print(user) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() url.py from django.urls import path from . import views urlpatterns … -
Why django PermissionRequiredMixin is not working as it intended to be
Here i have got a Django view that should normally redirect me to the Settings.LOGIN_URL if user has not the required permission but the issue is it's always displaying the 403 FORBIDDEN page. the url defined in Settings.LOGIN_URL is 'accounts/login/'. class LibrairianListView(PermissionRequiredMixin, View): model = BookInstance template_name = 'catalog/librairian_list_borrowed.html' permission_required = 'catalog.can_mark_returned' def get_queryset(self): return BookInstance.objects.filter(status__exact='o').order_by('due_back') def get_context_data(self, **kwargs): print(self.raise_exception) context = {} context['bookinstance_list'] = self.get_queryset() return context def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context_data()) And i change this to a function based view and everything is working fine, but i wanted to use class base view since this should do the same work -
Django: Where to go from "pinax.notifications?"
With regards to a deployed web-site I am rudely confronted with unexpected upgrade problems. "pinax.notifications" in particular is throwing problems such as a dependency on a package named "six" and inability to understand the decorator @python_2_unicode_compatible. The Django version that this app has been running was 2.1.11 and now the latest is 3.0.4 and this seems to have caused me a boatload of problems all of the sudden. Any advice appreciated ... -
How to add User model to Profile model in Django right way?
I am new to Django and trying to create a Profile(Patient) model. Here are my models. class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveSmallIntegerField() gender = models.CharField(max_length=1) def __str__(self): return str(self.user.username) class Doctor(models.Model): name = models.CharField(max_length=50) max_slots = models.PositiveIntegerField(default=10) available = models.PositiveIntegerField(default=0) def __str__(self): return str(self.name) class Assistant(models.Model): name = models.CharField(max_length=50) docid = models.OneToOneField('Doctor', on_delete=models.CASCADE) def __str__(self): return str(self.name) class Appointment(models.Model): confirmed = models.BooleanField(default=False) patid = models.OneToOneField('Patient', on_delete=models.CASCADE) docid = models.ForeignKey('Doctor', on_delete=models.CASCADE) assid = models.ForeignKey('Assistant', on_delete=models.CASCADE) def __str__(self): return str(self.patid) Last migration file class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('doctor', '0014_auto_20200318_0219'), ] operations = [ migrations.AlterField( model_name='patient', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] and error I am getting when I run migrations Operations to perform: Apply all migrations: admin, auth, contenttypes, doctor, sessions Running migrations: Applying doctor.0011_auto_20200318_0211...Traceback (most recent call last): File "C:\Users\syd's\.virtualenvs\django-hospital-0gp1XnhJ\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "doctor_patient" does not exist I tried dropping all my tables and running migrations again but no use. P.S. The name of my Django app is "doctor" and I am using PostgreSQL. -
Python 3.8 + Apache 2.4 + mod_wsgi to run django site
so I am running out of things I can possibly check for, I've made sure my python as well as apache are both 64 bit, python is a system wide install, I've uninstalled the 32 bit version before and reinstalled mod_wsgi to get the 64 bit module file, just in case I had the wrong build tools I even tried a pre-compiled mod_wsgi-4.7.1+ap24vc15-cp38-cp38-win_amd64.whl, but I did have the right build tools, I keep getting an error that says 'c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd into server: The specified module could not be found. .' The file is there, these are my parameters for the config that mod_wsgi-express module-config produces: LoadModule wsgi_module "c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "c:/users/eryk/pycharmprojects/django blog/venv" And here is my httpd.conf, in case anyone's wondering i disabled ssl cause I was getting an error saying 443 is taken, will troubleshoot that once I can actually get the apache service to start as this is getting silly, anyone got an idea what the issue might be? Would be greatly appreciated. CTRL + F "python" will find the python edits in the apache config ''' # Apache Hause .conf file for TLS/1.3 supported versions # # This is the main Apache HTTP server configuration file. It … -
ValueError: Cannot assign foreign key, value must be instance
Models.py class SalesOrder(BaseOrder): customer = models.ForeignKey(.... In serializers.py sales_order, sales_order_created = models.SalesOrder.objects.get_or_create( status_there = True, is_internal=False, ).first() billing_address = models.Address.objects.filter(sap_id__icontains='123').first() and sales_order.billing_address=billing_address sales_order.save() ValueError: Cannot assign "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" must be a "Customer" instance. I'm having the same error everywhere. this wherein files serializer, I am updating the sales order model. even with booleans ** When I print the billing address its just Customer-Cyberdyne Systems-a5233, But when I'm assigning to the sales order it is looking like this "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" ** Please let me know where I'm missing something, and is it okay to update a model from another serializer -
How to get python python-decouple to work on a live server?
I can't seem to get python-decouple to work on a live server. I have a Django project in which python-decouple is used to separate my important variables such as secret key, debug, database vars, and so on in a .env file. When the project is run locally, python-decouple works well and I have no problems. After confirming that it works well locally, I then added the .env file to my .gitignore file, pushed the code to my GitHub repository, then pulled the code to the AWS live server. However, when trying to make migrations while configuring the project on an AWS EC2 Ubuntu server, I get the error below. It seems as though the variables in the .env file are not being applied on the AWS Ubuntu server which would make sense because of the .gitignore file. But I thought the whole point of python-decouple was to not have the important variables on the live server. Does anyone know why this error is occurring? and how I can fix it? or do not fully understand the use cases of python-decouple? $ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, …