Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run django tests in a pre-commit hook
I'm stuck on how to simply run my django tests in a pre-commit hook. I will eventually put them in the push stage, but I'm just trying to get them to run first. It's trying to loop over my tests, but the tests object is a NoneType object. Works fine outside of this hook. I'm sure this is obvious to someone. Thanks. This is my test hook. repo: local hooks: - id: tests name: run tests always_run: true entry: python manage.py test language: system types: [python] -
User Authentication With Django Restframework and google
so i'm new to django and django rest api and i'm struggling with drf authentication. I'm trying to build an api with DRF that enables my users sign up with google. I've spent the last few days doing research but i've found more information on how to implement this in django as an app(which i have successfully done) but i need helping with implementing it in DRF. So far i have tried to use django oauth tool kit and socialoauth but i keep failing because most of the tutorials are not beginner friendly and make a lot of assumptions. I then spend hours trying to find out what they meant. This api will be used by an ios app and a webapp I would really appreciate any help. -
How to map the two heroku connect columns _hc_err and _hc_lastop in django ORM?
I've been trying to map the two columns which automatically gets created by heroku connect i.e. "_hc_err" and "_hc_lastop". These contain the value of the status of syncing to salesforce. Now, when I try to map them in django ORM, considering it to be a text field, it throws an error- (models.E008) Field '{variable_in_model_class}' has column name '_hc_err' that is used by another field. HINT: Specify a 'db_column' for the field. If it means that it is a foreign key rather than a text field, then which table should I relate it to? And what should I specify for Lookup i.e. "sf_field_name", "to" and "to_field" which we use for hc_models? I want these fields to check if the record has been successfully synced to salesforce or not. I know that we can use TriggerLogs but they are there for 30 days max in the archive. I want to check the status later as well. -
Access django rest framework CreateApiView response object with jQuery
I want to create an instance of User with ajax call. My view is a heir of CreateApiView and looks like this: class ManagerSignUp(CreateAPIView): serializer_class = ManagerSignUpSerializer permission_classes = [permissions.AllowAny] def perform_create(self, serializer): property_id = check_identifier(uuid.uuid4()) Hotel.objects.create( name=serializer.validated_data.get('works_for'), property_id=property_id ) serializer.save( title=TitleChoice.manager, property_id=property_id ) The jQuery function looks like following: $('#submitform').click(function () { var form = $(this) $.ajax({ url: form.attr('action'), data: form.serialize(), type: 'post', dataType: 'json', success: function (data) { console.log(data) } }) }) It creates User but as you could've guessed it doesn't log anything to the console, but renders standard DRF page. How can I access the data from serializer and prevent rendering the common DRF HTML? -
Image file not getting stored and Fetched in Django via Template Update View
views.py: from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from .models import Project, Task from .forms import ProjectForm, TaskForm from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView) # Create your views here. def index(request): projects = Project.objects.all() print("projects: ", projects) form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) return redirect('/') context = {'projects': projects, 'form': form} return render(request, 'projects/list_project.html', context) class ProjectDetailView(DetailView): model = Project def updateProject(request, pk): project_inst = Project.objects.get(id=pk) form = ProjectForm(instance=project_inst) if request.method == 'POST': form = ProjectForm(request.POST, instance=project_inst) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'projects/update_project.html', context) models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings # Create your models here. def upload_project_image(instance, filename): return "todoapp/files/{filename}".format(filename=filename) class Project(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=upload_project_image, null=True, blank=True) duration = models.DurationField(null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("project_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Task(models.Model): STATUS= ( ('New', 'New'), ('Assigned', 'Assigned'), ('Selected For Development', 'Selected For Development'), ('In Progress', 'In Progress'), ('Blocked', 'Blocked'), ('Completed', 'Completed'), ) title = models.CharField(max_length=200) description = models.TextField() project = models.ForeignKey(Project, related_name='tasks', on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) current_status = models.CharField(max_length=50, choices=STATUS, default='New') def … -
Is there any Multithreading issue with Kubernetes
I have severe Django API in my application one of the API implement multithreading and return response but when I deploy it using kubernetes That particular API gives performance issue almost all the time it stuck in pending mode for long and does not return a response . without kubernetes it is working fine . Is this issue with the thread ? -
Cant login using hashed password in django
I am trying to implement a custom user model. Whenever I try to log in for a user (created using the registration form), it returns no user. but if I create a user using the admin panel then the login function works perfectly. I think the problem is with password hashing. Tried some solve from here and there but seems like I can't find what I am looking for. The problem I am having : email: yeamin21@outlook.com pass: 1234 works (created using admin panel) but, email: yeamin21@outlook.com pass: hashed(1234) does not (created using the registration form) models.py from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractBaseUser): username = models.CharField(max_length=30,unique=True) email = models.EmailField(verbose_name='Email',unique=True) name = models.CharField(max_length=100) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' def __str__(self): return self.name class Restaurant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) location = models.CharField(max_length=200) def __str__(self): return self.user.email forms.py from django.contrib.auth.forms import UserCreationForm from django.db import transaction from Customer.models import User, Restaurant class RestaurantSignUpForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ['email','name','username'] @transaction.atomic def save(self, commit=True): user = super().save(commit=False) user.is_restaurant=True user.is_active=True user.save() restaurant = Restaurant.objects.create(user=user) restaurant.save() return user backend.py from django.contrib.auth.backends import BaseBackend, ModelBackend from Customer.models import User … -
How to Build a Studying App for mobile phones and PC
I would like to develop an App for studying that will work on mobile phones and on Windows. The idea is that the app should allow me to create different courses and upload study materials for each course where I can access them and read anytime I want to. And I should be able to track my progress for each course. I need some suggestions on how I can implement it, or is there any app that I can use which does what I have mentioned? -
how to create subdomain automatically for each user in django & heroku
I want to create subdomains automatically for each user, like: user1.example.com, user2.example.com, user3.example.com .... or I want to show example.com/user1 to user1.example.com in url using django and heroku. how can I do it? Please try to explain in brief as I am beginner. I am using django with heroku and my domain is on godaady. -
I am trying to add signup page data to django admin table that I created but code is not working
Here is my signup page code:- <body> <form action="/signup" method="POST"> {% csrf_token %} <div id="wrapper"> <div class="main-content"> <div class="header"> <img src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png" alt="noimage"/> <h4>Sign up to see photos and videos from your friends.</h4> </div> <div class="l-part"> <input type="email" placeholder="Email/Mobile Number" class="input-1" name="email" /> <div class="overlap-text"> <input type="text" placeholder="Name" class="input-2" name="name"/> </div> <div class="l-part"> <input type="text" placeholder="Username" class="input-1" name="username"/> <div class="overlap-text"> <input type="password" placeholder="Password" class="input-2" name="password"/> </div> <a href="" ><input type="button" value="SignUp" class="btn" /></a> </div> </div> </div> </div> </form> </body> This is how I rooted url to views from django.urls import path from . import views urlpatterns = [ path('',views.index,name="index"), path('main', views.main, name="main"), path('signup', views.signup, name="signup"), path('signup_page', views.signup_page, name="signup_page"), ] and here is my views section: from django.shortcuts import render from .models import sign def index(request): return render(request, "polls/index.html") def main(request): return render(request, "polls/main.html") def signup_page(request): return render(request,"polls/signup.html") def signup(request): if request.method=="POST": email=request.POST["email"] name= request.POST["name"] username = request.POST["username"] password = request.POST["password"] sign_up=sign(email=email,name=name,username=username,password=password) sign_up.save() return render(request, "polls/signup.html") else: return render(request, "polls/signup.html") Here is my models section from django.db import models class sign(models.Model): email=models.EmailField(max_length=200) name=models.CharField(max_length=100) username=models.CharField(max_length=100) password=models.CharField(max_length=10) def __str__(self): return self.name I tried to do it with this code Please tell me where I am doing wrong as there is no error But the … -
How to create a user in django with custom attributes using create_user?
I'm trying to run a test of the middleware of a django app. Looks like this: class TestAuthenticationMiddleware(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('test_user', 'test@example.com', 'test_password') def setUp(self): self.middleware = AuthenticationMiddleware(lambda req: HttpResponse()) self.client.force_login(self.user) self.request = HttpRequest() self.request.session = self.client.session But I'm getting this attribute error: queryset = user.get_subscriptions_all() AttributeError: 'User' object has no attribute 'get_subscriptions_all' because the User class is defined like this: User(AbstractBaseUser, LimitHelpers): [...] def get_subscriptions_all(self): return self.subscriptions.all().union(self.account.subscriptions.all()) Any idea about how to use the create_user to include the get_subscriptions_all attr? -
Defining enviromental variables Django + Heroku
Can you define env variables in settings.py this way?: DEBUG = 'DEVELOPMENT' in os.environ Have a variable set in Heroku : DEVELOPMENT = False Yet it still works in debug mode. -
ModelMultipleChoiceField initial values
I'm struggling to include the right initial values for a ModelMultipleChoiceField (as checkbox widget). I generate the required initial selection in the view and pass it to the form as 'data' via **kwargs. Using print(...) I have verified that this information makes it to the forms.py but it then doesn't make it to the form itself. The two selected strengths (in the list [2,3]) are always shown... class StrengthsForInstanceForm(forms.ModelForm): strength = forms.ModelMultipleChoiceField(queryset=Strength.objects.all()) class Meta: model = Instance exclude = ['name','subject','observer'] def __init__(self, *args, **kwargs): selected_strengths = [2,3] if kwargs.get('data'): selected_strengths = kwargs.pop('data') super(StrengthsForInstanceForm, self).__init__(*args, **kwargs) self.fields["strength"].widget = CheckboxSelectMultiple() self.fields["strength"].queryset = Strength.objects.all() self.fields["strength"].initial = selected_strengths Any ideas on how to solve this? -
Can't save serialized object with django apiview
i'm creating a API which is a get,put,delete in django i've already created one api that works but when i'm trying to use the APIView it does not work for reasons i dont know! and actually makes no sense for me. what i want is to transform the api def todo_get_change_delete(request,pk): into the new APIview api TodoUpdate(APIView): from rest_framework.decorators import api_view from app.models import Todo from app.serializers import TodoSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.exceptions import NotFound from rest_framework.views import APIView class TodoListAndCreate(APIView): def get(self, request): todos =Todo.objects.all() serializer = TodoSerializer(todos,many=True) return Response(serializer.data) def post(self, request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status= status.HTTP_201_CREATED) return Response(serializer.errors,status = status.HTTP_400_BAD_REQUEST) @api_view(['GET','DELETE','PUT']) def todo_get_change_delete(request,pk): try: todo = Todo.objects.get(pk=pk) except Todo.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TodoSerializer(todo) return Response(serializer.data) elif request.method == 'PUT': serializer = TodoSerializer(todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) elif request.method == 'DELETE': todo.delete() return Response(serializer.data,status = status.HTTP_204_NO_CONTENT) class TodoUpdate(APIView): def get_object(self, pk): try: todo = Todo.objects.get(pk=pk) return TodoSerializer(todo).data except Todo.DoesNotExist: raise NotFound def get(self, request,pk): todo = self.get_object(pk) return Response(TodoSerializer(todo).data) def put(self, request,pk): todo = self.get_object(pk) serializer = TodoSerializer(todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status= status.HTTP_400_BAD_REQUESTs) with thes … -
Problem in sending Dictionary object(converted JSON file) to template using render in DJANGO
I am fetching an external json file . Whenever I send the data in dictionary form to html page and reload it, The page doesn't opens instead that html file is downloaded. My views function: def index(req): data = urllib.request.urlopen("https://api.covid19india.org/states_daily.json").read() output = json.loads(data) print(output) return render(req,'india.html',{'countries':countries},{'states':output}) -
How to work with forloop and template model?
Here I am using simple a card snippet for all the post shown in post_list template. And I have added a template model so when i click on particular post it show me that model with the content of the post on which i clicked. With the following code, Almost everything is working okay but when i click on any post it show me the content of first post. I want to see content of the post in a model on which i clicked. {% for post in post_list%} <div class="cardbox"> <div class="cardbox-heading"> <div class="media m-0"> <div class="d-flex mr-3"> <a href="#"><img class="img-responsive img-circle" src="{{post.username.avatar.url}}" alt="User"></a> </div> <div class="media-body"> <p class="m-0">{{post.username}}</p> <small><span>{{post.create_date|timesince}}</span></small> </div> </div><!--/ media --> </div><!--/ cardbox-heading --> <div class="cardbox-item"> <a href="#myModal" data-toggle="modal"> <img class="img-responsive" src="{{post.image_data.url}}" alt="MaterialImg"> </a> </div><!--/ cardbox-item --> </div><!--/ cardbox --> Modal Section =============================================== --> <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div class="row"> <div class="col-md-8 modal-image"> <img class="img-responsive" src="{{post.image_data.url}}" alt="Image"/> </div><!--/ col-md-8 --> <div class="col-md-4 modal-meta"> <div class="modal-meta-top"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> <span aria-hidden="true">×</span><span class="sr-only">Close</span> </button><!--/ button --> <div class="img-poster clearfix"> <a href="#"><img class="img-responsive img-circle" src="{% static 'assets/img/users/18.jpg'%}" alt="Image"/></a> <strong><a href="#">Benjamin</a></strong> <span>12 minutes ago</span><br/> <a href="#" class="kafe kafe-btn-mint-small"><i class="fa fa-check-square"></i> Following</a> </div><!--/ … -
python django validate user input by decorator or extra function? Whats more pythonic?
Im working on a web application. The user can set some parameters to run some algorithms. So when I extract the parameters in the backend, I want to validate them before starting an algorithm, that could crash after a long execution time. Should I use a decorator around the algorithm function or should I pass the parameters to a function like def validate_parameters(), which raises an error if the parameter are incorrect? -
Python3.9 Django Docker Postgres
I'm trying to update my docker image switching from python:3.8.2-alpine3.10 to python:3.9.0-alpine3.12, but I'm getting an issue when running django commands SSL_check_private_key: symbol not found. I get the following error when running checks: bash -c "touch /var/donor_reporting_portal/.touch && django-admin check --deploy " /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /usr/local/lib/python3.9/site-packages/donor_reporting_portal/config/.env doesn't exist - if you're not configuring your environment separately, create one. Traceback (most recent call last): File "/usr/local/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/usr/local/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line File "/usr/local/lib/python3.9/site-packages/django/core/management/init.py", line 377, in execute File "/usr/local/lib/python3.9/site-packages/django/init.py", line 24, in setup File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 116, in create File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/django/contrib/postgres/apps.py", line 1, in File "/usr/local/lib/python3.9/site-packages/psycopg2/init.py", line 51, in ImportError: Error relocating /usr/local/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-x86_64-linux-gnu.so: SSL_check_private_key: symbol not found make[2]: *** [.run] Error 1 make[1]: *** [test] Error 2 make: *** [build] Error 2 I don't get any issue when running this on my machine. -
Need Contrains for Foreign Key
I am creating a College Management App in Django. Here is my model. file: accounts/model.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): ROLE = {('student', 'student'), ('staff', 'staff'), ('account_manager', 'account_manager'), ('Admin', 'Admin')} role = models.CharField(choices=ROLE, default='student', max_length=20, blank=True, null=True) I am using the inbuilt user class for all the users (staff, student, HOD and principal). We can identify the user by the role. No, I want to create a course database, where the staff_id will be the foreign key of CustomeUser table. Is there any way to select the user with the role of the foreign key? class Course(models.Model): course = models.CharField(max_length=150) start_date = models.DateField() end_date = models.DateField() instructor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='instructor_name') examinar = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='examinar_name') def __str__(self): return f'{self.course.name} Batch No: {self.batch_no}' Here both referring to the same CustomUser foreign key. That's why I have added the related name. (is this a right approach?) But in the admin page, if I want to add a new course, I am getting all the users. like this, [![enter image description here][1]][1] I want to display the users only if the role is staff. Is it possible? [1]: https://i.stack.imgur.com/pxn6S.png -
How can I connect a model instance to a user in django?
Im looking to make it so the logged in user that creates a profile is linked to their guestprofile model when they create their profile. When I create the guest profile while logged in, it successfully creates the guest profile, but in the guest profile admin screen there is no user connected to the guest profile model created. Instead there is a dropdown menu listing all users, which makes the connection process manual. Thanks. views.py class AddProfileView(CreateView): model = GuestProfile form_class = AddProfileForm template_name = 'profilemanip/addprofile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user Forms.py class AddProfileForm(forms.ModelForm): name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) summary = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) profile_pic = forms.ImageField() class Meta: model = GuestProfile fields = ('name', 'location', 'summary', 'profile_pic') Models.py class GuestProfile(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) location = models.CharField(max_length=100) summary = models.TextField(max_length=350) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return str(self.user) -
i want to create a search in django which have order by istartswith first than icontains
def autocomplete(request): template_name='searchresults.html' if 'term' in request.GET: qs=Post.objects.filter(Q(title__istartswith=request.GET.get('term'))|Q(content__icontains=request.GET.get('term'))) titles=list() for post in qs: titles.append(post.title) return JsonResponse(titles, safe=False) return render(request, template_name) How can I can order them ins such a way that if it begins with term order it as first and the one that contains it but does not begin with it as second -
Search form only works on home page
I have a search form that works correctly on the home page but not on any other page. The search form is embedded in the nav bar which has its own html file. Also, the ul for the search results in nested right below the search form. I want it to work regardless of what page the user navigates to. Here is the main.html: <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2", type="text", name="search" placeholder="Search"> </form> <ul id="search-results"> </ul> Here is the views.py: def home(request): post = Pilot.objects.all().order_by('id') #Search Filter search = request.GET.get('search') if search != '' and search is not None: post = post.filter(Q(title__icontains=search) | Q(writer__icontains=search)).distinct() ... return render(request, 'home.html', context) Here is the urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('about/', views.about, name="about"), path('comment/', views.comment, name="comment"), path('comment_submit/', views.comment_submit, name="comment_submit"), -
404 in Django isn't working, I get a 500 error [closed]
My custom 404 page says "500 server error", instead of showing the custom 404 page. I also turned off debug in the settings. -
How to automatically mark a specific field either False or true after certain time has been elapsed?
I'm creating a Hotel table reservation web app in Django 3.x.x I have a Table Model with isBooked field that is set to either False or True depending on a table status. Code for this model: class Table(models.Model): title = models.CharField(max_length=50, null=True) t_id = models.IntegerField("Table ID", null=True, unique=True) isBooked = models.BooleanField('Is Booked', default=False) chairs_booked = models.IntegerField("Chairs Booked", default=0) max_chairs = models.IntegerField("Total Chairs", default=0) max_book = models.IntegerField("Least Bookable", default=0) chairs_left = models.IntegerField("empty chairs", default=0) Now, I have another Model called Reservation that stores data for booked Tables. Here is its code: class Reservation(models.Model): t_username = models.CharField("Booked By", max_length=100, null=True) t_email = models.EmailField("Email Address", null=True) t_phone = models.IntegerField("Phone Number", default=0, null=True) t_id = models.IntegerField("Table Id", null=True) booked_date = models.CharField("Check In Date", null=True, max_length=50) # '2020-10-27' booked_time = models.CharField("Check in Time", null=True, max_length=50) # '7:00' def _get_checkout_date(self): t = self.booked_date return t checkout_date = property(_get_checkout_date) def _get_checkout_time(self): the_time = dt.datetime.strptime(self.booked_time, '%H:%M') new_time = the_time + dt.timedelta(hours=3) return new_time.strftime('%H:%M') checkout_time = property(_get_checkout_time) at this point, I have a table with following information stored in variables: booked_time this holds a string for time showing when table was booked e.g. 7:00 checkout_time this holds a string for time showing when table should be vacated/checked-out e.g 10:00 … -
How can I link an input to an object's attribute and update that attribute as you click on it?
Given these model, view, and template files: models.py class Item(models.Model): class Included(models.IntegerChoices): YES = 1 NO = 0 included = models.IntegerField(choices=Included.choices, default=Included.YES) name = models.CharField() views.py def index(request): items = Item.objects.all() context = { 'items':item } return render(request, template.html, context( template.html {% for item in items %} {{ item.name }} <input type="checkbox"> {% endfor %} How can I do it such that the checkbox reflects if the Item it's with is included or not? How can I change if it's included or not by just ticking the checkbox? In general, how can I link an input to an object's attribute and update that attribute as you click on it? I don't think it would be feasible to use forms here, as it only changes a field. Plus if it's possible, do it realtime. Forms won't update a page unless you refresh it afaik, any ideas?