Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSignature Field Not Appearing in Django
First time posting on the site, apologies before hand as I am a newbie. Building a Django project in Visual Studio for a class and need a signature form to appear on one of the pages. Currently been following this guide: https://pypi.org/project/django-jsignature/ but have hit a roadblock as all I can get to show on the page is a save button. Below I've listed what I've got. forms.py from django import forms ... from jsignature.forms import JSignatureField from jsignature.widgets import JSignatureWidget ... class SignatureForm(forms.Form): signature = JSignatureField() template.html {% extends "app/layout.html" %} {% block content %} <meta charset="utf-8" /> <title></title> {{form.media }} <form action="." method="POST"> {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} <input type="submit" value="Save"/> {% csrf_token %} </form> {% endblock %} views.py from jsignature.utils import draw_signature from app.forms import SignatureForm ... def signature(request): assert isinstance(request, HttpRequest) return render( request, 'app/template.html', { 'title':'About', 'message':'Your application description page.', 'year':datetime.now().year, } ) def my_view(request): form = SignatureForm(request.POST or None) if form.is_valid(): signature = form.cleaned_data.get('signature') if signature: #as an image signature_picture = draw_signature(signature) #or as a file signature_file_path = draw_signature(signature, as_file=True) Again, when taken to my template page all that populates is a lone save β¦ -
Is it possible in django that two different models of a single app belong to tw different database or is multiple database is achievable at app level?
I am trying to achieve that two different models in a single app in django belong to two different database. I used database routers to achieve the same. But the tables are being created at both the databases instead of one in each. myproject/myapp1/models.py: class mymodel1(models.Model): name = models.CharField(max_length=30) class Meta: app_label = 'myapp1' class mymodel2(models.Model): first_name = models.CharField(max_length=20) class Meta: app_label = 'myapp1' A very simple DB Router: myproject/store/db_router.py: class ModelRouter(object): """ A DB router that controls all database operations """ def db_for_read(self, model, **hints): return self.db_for_write(model, **hints) def db_for_write(self, model, **hints): #any condition based on model name say mymodel2 to store in DB2 if model._meta.name == 'mymodel2' return mymodeldb2 return None def allow_relation(self, obj1, obj2, **hints): """ Here allow relation if objects are both in same database. """ return self.db_for_write(obj1) == self.db_for_write(obj2) def allow_migrate(self, db, app_label, model_name=None, **hints): """ Ensure that the models get created in the right databases """ if db == 'mymodeldb2': if app_label in ['myapp1'] and model_name == 'mymodel2': return True else: return False elif app_label in ['myapp1'] and model_name == 'mymodel2': return False return None myproject/project_name/settings.py: DATABASE_ROUTERS = ['store.db_router.ModelRouter'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres_db', 'USER': 'XYX', 'PASSWORD': 'YXY', 'HOST': 'localhost', β¦ -
What is the deployment procedure of a Django Web application?
I am trying to build an Online Judge using Django Framework where users can submit their code against some problems and they will be accepted if the output of their code matches the correct ones. In that case, I have to access the command line programmatically to run the submitted codes. I need to know if I can do that and also if I can, what is the deployment procedure? -
How to create a model with multiply choices with custom text?
I'm building a simple quiz app. I want to add an ability to add multiple choices (with custom user text) for each question in the admin panel. So the user can create a question and on the same page add as many answers as he needs. What is the best way to realize it? I know that I can add another model for answers and make a relationship with questions model. But it's not exactly what I want to achieve. Thanks for any help. -
Nginx not serving static files for Django in Amazon EC2 - 404 Error
I'm pretty new to Django development and Nginx Configuration. Once the application is deployed in amazon EC2 using gunicorn and Nginx, the page loads without the static files (css, js etc). I suspect that Nginx is unable to load the static files. I spent a couple of hours trying to tweak the Nginx Config, and reading other answers, but still no luck. Any tips in the right direction are appreciated. /etc/nginx/sites-available/sbs server{ listen 80; server_name my_server_host; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; root /home/ubuntu/secure-banking-system/sbs/static/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/secure-banking-system/sbs/sbs.sock; } } settings.py STATIC_ROOT = '/home/ubuntu/secure-banking-system/sbs/static' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'sbs/static') ] I have already verified that the static files are available in /home/ubuntu/secure-banking-system/sbs/static/ File Structure secure-banking-system | |ββsbs | |βββββ β βββ sbs β | β βββ static β βββ css β βββ images β βββ js | βββ static βββ css βββ images βββ js -
How to create a like functionality in django for a blog
I have to build a blog for my chess club and I would like to make a like functionality for the posts. When the user likes the post the like count increases and the post its shown in the user profile. Here is what I made so far: This is my post model: class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() is_aproved = models.BooleanField(default=False) # comment_count = models.IntegerField(default = 0) # view_count = models.IntegerField(default = 0) slug = models.SlugField(unique=True, blank=True) likes = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='post_likes') author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) likes = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='post_likes') featured = models.BooleanField() previous_post = models.ForeignKey( 'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey( 'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) def get_update_url(self): return reverse('post-update', kwargs={ 'id': self.id }) def get_delete_url(self): return reverse('post-delete', kwargs={ 'id': self.id }) @property def get_comments(self): return self.comments.all().order_by('-timestamp') @property def comment_count(self): return Comment.objects.filter(post=self).count() @property def view_count(self): return PostView.objects.filter(post=self).count() And this is my view: def post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) if request.user.is_authenticated: PostView.objects.get_or_create(user=request.user, post=post) form = CommentForm(request.POST or None) if request.method == β¦ -
How name of a user who filled a form can be saved in the model
I am new in Django and I have a CustomUser model which has OneToMany relation to Car model. I want logged in user fill the form and automatically the data save in Car model with name of users. Car model has person as person = models.ForeignKey('CustomUser', on_delete=models.CASCADE) In my form I used this field and when a user will fill the form he can see all the users. How can I solve this problem? Thank you, in advance -
Auto fill ForeignKey(User) with current signed in user
I have this model called business I want the foreinkey field owner to get the logged in user name automatically without bringing the dropdown button of all users, I have tried some methods, but it doesn't work. How can I autofill the owner field with the logged in user models.py class User(AbstractUser): phone_number = models.CharField(('phone number'), max_length=15,default='+234', help_text=('Field to save the phone number of the user.'),unique=True) fullname=models.CharField(max_length=50) class Business(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE,default=1) Phone_Number=models.IntegerField(default='086878432',unique=True) Figi_ID=models.IntegerField(blank=True) views.py def details_business(request): if request.user.is_authenticated: business_form=Business() if request.method=='POST': business_form=Business_owner_form(request.POST,request.FILES) if business_form.is_valid(): bform=business_form bform.owner=request.user bform.save() -
Foreign key widget finds more than 1 value, how should i approach this
I am using django-import-export library and I am trying to implement ForeignKey widget which is available to lookup related objects using Author.name instead of Author.pk. Now, the here is the tricky part for the given calendar year I only have one author with the same name, however, next year the author name will be similar. When i try to import, of course, it brings the issue saying that more than Author.name was found. Is there a suggestion to solve the issue? -
My django default imagefield not displaying
am working on a project, i want to display the default picture in the profile table, but the image is not displaying, but there is another picture in the table that is not the default picture, it will display here is my code profile.html <img class="card-img-top mt-2 PoNeImg img-responsive" style="width: 90%;" src="{{user.profile.image.url}}" alt=""> models.py 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' def save(self, force_insert=False, force_update=False, using=None): super().save() pls how can i make the default picture display -
ALLOWED_HOSTS not working in my Django App deployed to Elastic Beanstalk
I deployed a Django App to AWS Elastic Beanstalk and I'm getting "Invalid HTTP_HOST header" error even when I've added it to my allowed hosts settings. I'm getting this error: Invalid HTTP_HOST header: 'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com'. You may need to add 'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com' to ALLOWED_HOSTS. This is what I have in my settings.py settings.py: ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', '.amazonaws.com', '.elasticbeanstalk.com', 'recordings-env.kf4qfzaijd.us-west-2.elasticbeanstalk.com', ] after modifying it I run eb deploy without errors. -
How to check username & password for custom login
models.py class student(models.Model): u_email = models.CharField(max_length=50) u_username = models.CharField(max_length=50) u_password = models.CharField(max_length=20) view.py def login_check(request, *args,**kwargs ): if request.method == 'POST': c_username= request.POST['username'] c_password = request.POST['password'] print(username,password) how can i perform following query for authenticate student in django "SELECT id FROM student WHERE u_username = c_username and password = c_password" -
how to combine Filtering and Pagination with Django?
I am new programming with python, I want to combine paginations with filter but the solutions that I find do not work for me, i hope someone can help me this is my view @login_required def publication_list(request): f = PublicationFilter(request.GET, queryset=Publication.objects.all()) return render(request, 'info/filter.html', {'filter':f}) -
Is there any django query grammar specification?
I'm just wondering if all ways allowed to query a database (with django orm) are available in a grammar format? I only find documentation about all kinds of queries but nothing about the big picture to all allowed combinations. I mean something like that python3 grammar specs but for the Django queries. How do the they check that a query is valid or not in the other case? -
Why my django project url direct old one when I use pycharm
first of all, i use pycharm to create a django project pj2, obviously, I already have one pj1 before this. pj1 was created in virtualenv called venv. when I run new project cd pj2 python manage.py runserver it will enter the url 127.0.0.1:8000/catalog, whether or not i create pj2 in virtual environment. catalog is pj1's app. why did that happen? its ok in cmd. so i think the problem is pycharm. -
Just want a way to save all objects in once
I have created a model with three objects to be saved in database but the saving in different different columns. Just see my screenshots Sir Thanks in Advance views.py def buyerrequest(request, pk, id): if request.method === 'POST': frm = rst(request.POST) if frm.is_valid(request.POST): sid = models.request(seller_id=pk) bid = models.request(buyer_id=id) sid.save()// I need a method to save it at once that's all bid.save() frm.save() return HttpResponseRedirect('index') else: frm = rst() return render(request, 'port_folio/request.html', {'frm': frm}) enter image description here -
how to handle my skills as aclass model in Django?
I am creating my portfolio which I handled its template from bootstrap templates into a django project, I need to make skills section in template comes from a model called "skills" to be able to add more skills later.but they mentioned as list items and fontawesome icons in the template so which model field could handle that? note that not all of them are fontawsome icons . here is code in template: Skills <div class="subheading mb-3">Programming Languages &amp; Tools</div> <ul class="list-inline dev-icons"> <li class="list-inline-item"> <i class="fab fa-html5"></i> </li> <li class="list-inline-item"> <i class="fab fa-css3-alt"></i> </li> <li class="list-inline-item"> <i class="fab fa-js-square"></i> </li> <li class="list-inline-item"> <i class="fab fa-sass"></i> </li> <li class="list-inline-item"> <i class="fab fa-python"></i> </li> <li class="list-inline-item"> <img class="img-fluid img-profile mx-auto mb-2" src="{% static 'img/sql.png' %}"> </li> <li class="list-inline-item"> <img id="logo" src="{% static 'img/logo.png' %}"> </li> </ul> <div class="subheading mb-3">Duties & Responsibilities</div> <ul class="fa-ul mb-0"> <li> <i class="fa-li fa fa-check"></i> Write reusable, testable, and efficient code.</li> <li> <i class="fa-li fa fa-check"></i> Design and implement of low-latency, high-availability, and performant applications.</li> <li> <i class="fa-li fa fa-check"></i> Integration of user-facing elements developed by front-end developers with server side logic.</li> <li> <i class="fa-li fa fa-check"></i> Implementation of security and data protection</li> <li> <i class="fa-li fa fa-check"></i> β¦ -
How to access cached properties in a queryset
One of my models contains a @cached_property. When I query this model and filter the results, the cached property is not available. However, if I isolate a single instance in the queryset, I can access the cached property. How can I filter the entire queryset based on the value of the cached property? django.core.exceptions.FieldError: Cannot resolve keyword 'my_cached_property' into field. -
bootstrap css not loading in django template
when loading base_html all bootstrap css is loading: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Custom styles for this template --> <link rel="stylesheet" href="{% static "artdb/css/custom.css" %}"> but when I want to load my signin page no css is loaded: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Custom styles for this template --> <link hrel="stylesheet" href="{% static "artdb/css/signin.css" %}"> my urls.py: path('',TemplateView.as_view(template_name='artdb/base.html')), path('signin/',TemplateView.as_view(template_name='artdb/signin.html')), any ideas? I have {% load staticfiles %} in both files. Any ideas? -
Verified user in Django
I want to allow only verified users by site admin should be able to post blog on site so how can i check the is_verifieduser field defined in model while rendering template class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT) phone_number = models.CharField(max_length=12,default="") is_verifieduser = models.BooleanField(default=False) def __str__(self): return self.user.username -
Django Paginator gives error __init__() missing 2 required positional arguments: 'number' and 'paginator'
I have used the following code from Django Documentation and for some reason the code doesn't work {% for contact in contacts %} {# Each "contact" is a Contact model object. #} {{ contact.full_name|upper }}<br> ... {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> <a href="?page={{ contacts.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> When I go to the page I get the error : init() missing 2 required positional arguments: 'number' and 'paginator' Strange! I have also tried passing on the url with page argument but it still doesn't work! -
Django rest framework: how to post parent and children objects correctly
I'm creating a rest API using Django-rest-framework. What I want to do is to post dynamic number of children objects with parent object at the same endpoint. There are some problems I'm facing. Here is serializers.py class ChildSerializer(serializer.ModelSeralizer): class Meta: model = Child fields = ('name',) class ParentSerializer(serializer.ModelSerializer): children = ChildSerializer(many=True) class Meta: model = Parent fields = ('name', 'children') def create(self, validated_data): children = validated_data.pop('children') parent = Parent.objects.create(**validated_data) for child in children: try: Child.objects.create(parent=parent, *child) except: break return parent First I tried to post children like ... children: [ "name": "NameA", "name": "NameB" ] But it doesn't work. The error says "detail": "JSON parse error - Expecting ',' delimiter What is the correct format when posting nested object in rawdata? Also, I want to associate child with parent when creating them but is my way correct? If not I want to know how to do it correctly. -
NameError: name 'index' is not defined
I have started my first django project and having an issue with adding a view to my urlpatters. project/first_app/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('test') project/project/urls.py from django.contrib import admin from django.urls import path from first_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name=index), ] This is throwing the below error in my server terminal File "/xxx/xxx/xxx/xxx/xxx/project/project/urls.py", line 22, in <module> path('first_app', views.index, name=index), NameError: name 'index' is not defined I've played around with the path: path('first_app' quite a lot and can't seem to get it working. -
Static file image in not found
I am very new to Django and trying to do some static file exercise. Under the project Twenty3rdMarch I have created a folder static and under that one folder called images. In the images folder, I have placed a few images. Here is my setting.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR=os.path.join(BASE_DIR,'templates') print(TEMPLATES_DIR) STATIC_DIR=os.path.join(BASE_DIR,'static') SECRET_KEY = 'mz^^exko@!2czk35u$w-qr&v8u(46(fp7#u41ctabvwf=mz9m&' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Twenty3rdMrach.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Twenty3rdMrach.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'udemy', 'USER':'root', 'PASSWORD':'Ravi@go123', 'HOST':'localhost', 'PORT':'3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIR=(STATIC_DIR,) Here is my view: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def index(request): template=loader.get_template('first_app/index.html') my_dict={'insert_me':"Hello I have created my first dynamic Template"} return HttpResponse(template.render(my_dict,request)) def help(request): template=loader.get_template('first_app/help.html') context1={'help':'Helping Hand!!'} β¦ -
What does is not None stands for in django/python?
I want to display a not valid message when my html form field is empty. But the code below goes to if block when the field is empty. And else block when the field is not empty. Shouldn't it be the other way around? I wrote it this way because this seems to do the job. But I'm confused. Shouldn't it be the other way around? if(request.POST['amount'] is not None): os.remove(os.path.join(settings.MEDIA_ROOT,str(uploaded_file.name) )) messages.success(request,('Invalid Field....')) return redirect('assignFine') else: form = Fine(amount=request.POST['amount'],numberPlate=num,policeUsername=request.user) form.save()