Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using __in operator in if condition
I have view with if condition: if request_status.id__in [3,5]: car.booked = False car.save() I want to use __in operator in it similar to this example Entry.objects.filter(id__in=[1, 3, 4]) Any help is appreciated. -
How to automatically add logged in user as creator of product
I have a form that can create a product. My problem is how do I add the logged-in user automatically? While logged-in, when I create a product and look at admin http://127.0.0.1:8000/admin the 'creator' object is blank --- or I have to choose the user manually. I want to relate a product with a user. models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) prodname = models.CharField(max_length=255, null=True) description = models.CharField(max_length=255, null=True) price = models.FloatField(null=True) image = models.ImageField(null=True, upload_to='images') views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from .forms import ProductForm, RegisterUserForm from .models import * def home_view(request): return render(request, 'home.html') def product_create_view(request): form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'product/product_create.html', context ) def register_view(request): form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() return redirect('product/login.html') context = { 'form': form } return render(request,'product/register.html', context) def login_user(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home-view') else: messages.info(request,'Username or password is incorrect') return render(request,'product/login.html') def logout_user(request): logout(request) … -
Do I define new models if they already exist in db? [duplicate]
I am new to Django. I am trying to write a code, which takes data from a database and shows it in a website. My question is, if the data already exist in the database and I only want to get them, do I need to define new models in the models.py? -
How to store model field data type based on choices?
Here in my model I want to set option value based on choice value. How can I do this or any other solutions ? class MyModel(models.Model): title = models.ForeignKey(Title, on_delete=models.CASCADE) option_name = models.CharField(max_length=200) option_value_choices = [ (1, "models.BooleanField"), (2, "models.DateField"), (3, "models.IntegerField"), (4, "models.CharFIeld") ] option_value_type = models.CharField(max_length=10, choices=opt_choices) option_value = .. ? -
how to make a field have choices from another model in django
I am creating a gradeviewing app for my School Project and I am confused on how do I need to build relationships of each models. I want a subject field on my StudentGrade model to have a list of choices coming from Student model but I only want to display/get the enrolled_subjects of the student instance model.py: class Subjects(models.Model): subject_name = models.CharField(...) subject_code = ... ... class Student(models.Model): student = models.ForeignKey(setttings.AUTH_USER_MODEL,...) enrolled_subjects = models.ManyToManyField(Subjects) ... class StudentGrade(models.Model): PERIOD_CHOICES = [ ... ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, limit_choices_to=Q(is_student=True)) period = models.CharField(choices=PERIOD_CHOICES, max_length=25) subject = // i want this to be list of subjects that the student has enrolled grade = models.DecimalField(max_digits=4, decimal_places=2) on the StudentGrade model, I want the subject field to be based on the enrolled_subjects of student instance how can I do that? -
How to update model except null values using PUT method in django?
I have a Post model which has many fields. I want to update a field only if it's not null which means it should have the value from the request. post = PostModel.objects.get(id = id).update() -
How do you create a dynamic form field in Django?
I want to create a dynamic form field that always filters a model and shows the filtered elements in a list in the form. Here is the code I have so far: class OrganisorClassStatusUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs) self.fields['off_day_student'] = forms.ModelChoiceField( queryset=Class.objects.filter(teacher=self.object.teacher).filter(is_new_set=True).filter(time=self.object.time).order_by('-date')[:10] ) The problem I have with this code is that the self.object refers to the form itself, not the model I am trying to update. This is important since I need to filter the queryset using some of the information in the model I am trying to update. Please ask me any question if you need anything. Thanks a lot. -
Validating a Regex pattern entered into form via user interface
I'm struggling to find how to validate a user entered Regex pattern. The use case here is that the user interfaces allows the user to create rules that merge any incoming Merchants that meet the regex pattern specified in a rule. So the user themselves enter the regex pattern. I hope that makes sense. merchants = Merchant.objects.filter(name__iregex=merge_rule.pattern) I get system errors when a bad regex is entered into the rule, so I'd like to validate against these. -
How do I connect to an mssql db that is on a windows computer from a linux VM inside these computers' intranet?
I have a client that has a desktop application for its employees. I've been tasked with porting this over to a web application that runs within their intranet. This web application obviously needs to connect to the db they currently have. But I am lost as to how to do this. It's an mssql db. I've never worked with mssql before. Nor have I made a web application that runs only within an intranet. Can anyone help? I'm writing this web app in django, for what it's worth -
How to POST multiple objects in one JSON request?
I am using django-rest-framework and recently I encountered a problem. I need to post such request and get 2 objects created: { "lease": 28, "date": [ { "from_date": "2021-06-01", "until_date": "2021-07-01" }, { "from_date": "2022-03-22", "until_date": "2022-04-23" } ] } Model looks like this: class DateUnavailable(models.Model): lease = models.ForeignKey(Lease, on_delete=models.CASCADE, blank=False, null=False) from_date = models.DateField(blank=True, null=True) until_date = models.DateField(blank=True, null=True) Currently my views.py looks like this: class DateUnavailableCreateView(generics.CreateAPIView): #POST permission_classes = [IsAuthenticated, ] def get(self, request): all_dates = DateUnavailable.objects.all() serializer = DateUnavailableSerializer(all_dates, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, *args, **kwargs): lease = request.data['lease'] dates = dict(request.data.items())['date'] flag = 1 arr = [] for date in dates: modified_data = modify_input_for_multiple_dates(lease, date) date_serializer = DateUnavailableSerializer(data=modified_data, many=True) if date_serializer.is_valid(): if date_serializer.validated_data["lease"].user != self.request.user: return (Response('You are not allowed to make changes to this schedule', status=status.HTTP_405_METHOD_NOT_ALLOWED)) date_serializer.save() arr.append(date_serializer.data) else: flag = 0 return (Response(arr, status=status.HTTP_201_CREATED) if flag == 1 else Response(arr, status=status.HTTP_400_BAD_REQUEST)) This view is the slight modification of the one that I used successfully for creating multiple file objects related to one object through ForeignKey. -
Django Accessing Child Data in Templates from Parent object
I am new to Django and am trying to do something that should be very straightforward (in my mind) but I've spent a few hours on this and haven't solved it yet. Goal: Within a template I would like to get a value from a field from a child object using the parent. In this case I am trying to get the lab_request object by knowing the parent sample. So far I have tried using both a ForeignKey in the Lab_Request model as well as a OneToOneField Specific area in the code where I believe I am going wrong is {{ sample.lab_request.placeholder_to_be_replaced }}. Sample is a parent and 'Lab_Requests' is a child. In thus case I have set it to OneToOneField but really I have this issue in another area where it will be a Parent to multiple Children. Code: #models.py class Sample(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) status = models.CharField(max_length=2, choices=SAMPLE_STATUS_OPTIONS, default="01") sample_number = models.CharField(max_length=19, unique=True, editable=False, default=get_sample_number) class Inspection_Request(models.Model): #Add stuff here placeholder_to_be_replaced = models.CharField(max_length=1) sample = models.OneToOneField(Sample, on_delete=models.CASCADE) inspector = models.OneToOneField(Inspector, on_delete=models.CASCADE, null=True, blank=True) #views.py class SampleHomeView(ListView): model = Sample samples = Sample.objects.all context_object_name = 'samples' template_name = '<app name>/sample.html' ordering = ['-sample_date'] paginate_by = 10 #sample.html {% … -
Hosting django channels on apache and daphne
I am trying to deploy django chat application on apache the same way. Can someone please help me with setting up the daphne server? I am totally new to deploying django channels. I have a linux virtual machine (ubuntu). The site is running but the websocket connection is not established. the error I see in the console is: (index):16 WebSocket connection to 'ws://chat.bagdigital.in/ws/chat/lobby/' failed: (anonymous) @ (index):16 (index):30 Chat socket closed unexpectedly chatSocket.onclose @ (index):30 here is my apache conf file. <VirtualHost *:80> ServerName chat.bagdigital.in #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error_chat_bagwebsite.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/pksingh/chat-app/chat-api/static Alias /media /home/pksingh/chat-app/chat-api/media <Directory /home/pksingh/chat-app/chat-api/static> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/media> Require all granted </Directory> <Directory /home/pksingh/chat-app/chat-api/chatapi> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/pksingh/chat-app/chat-api/chatapi/wsgi.py WSGIDaemonProcess bag_chat_app python-path=/home/pksingh/chat-app/chat-api python-home=/home/pksingh/chat-app/chat-api/venv WSGIProcessGroup bag_chat_app I have installed the redis server. And the socket connection is running fine if I run the django server at port 8000 normally without using apache. python3 manage.py runserver 0.0.0.0:8000 & Can someone help me with setting up daphne server here?? -
Django: How to manually render each field of a form on a bootstrap template?
I've found this nice bootstrap template online and I want to use it as my template for updating a user profile, I have tried several methods I've found in here and also in youtube, but I still couldn't get it to work. Not only does the form isn't rendering, the updated profile is not being saved also when I click update. Could someone help me out what is the problem? and I do apologize in advance if I'm not making sense as english is my second langauge. here is my view for profile update, I did not create a form for it as I've read online that I do not need to create a form for it to work, just need the model. class TutorProfileUpdateView(UpdateView): model = User fields = ['first_name', 'last_name', 'email', 'phone number', 'current_address', 'image', 'bio'] template_name = 'account/tutor_dashboard.html' success_url = reverse_lazy('tutor-dashboard') def form_valid(self, form): fm = form.save(commit=False) fm.user = self.request.user fm.save() messages.success(self.request, f'Profile Updated!') return HttpResponseRedirect(self.get_success_url()) and here is some part of the template, I will not paste it all here as it is too long. <form method="POST"> {% csrf_token%} <div class="card h-100"> <div class="card-body"> <div class="row gutters"> <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12"> <h6 class="mb-2 text-primary">Personal … -
Django - Best practice for running (switching) dev/debug/product mode?
In my source (using Docker), there is a database and my django code. docker-compose.yml services: app: db: When I debug locally, I usually delete the database in Docker-compose to prevent it creating a new database locally. Then I change the settings in django source to connect to the database of the server settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 123.231.***, 'NAME': db***, 'USER': ****, 'PASSWORD': **** } } or When I develop a new feature, I would prefer to create a database locally to test things our rather than connect directly to the server database. Well, my question is that how to set things up so we can easily switch between dev/ prod/ debug mode. In my thought, it should be easy like commanding: python manage.py run dev-mode -
Serving media files in Django , gunicorn and nginx
I have deployed my Full Stack application using Django and React using nginx on AWS . All the files including static files are being served as expected but I am unable to serve media files present in the /home/user/backend/media/images/ directory . My directory structure looks as follows /home/user/backend/media/images/image1.jpg, /home/user/backend/media/images/image2.jpg etc. In development (manage.py runserver) mode I am able to access my files using http://localhost:8000/media/images/image1.jpg . here is my Nginx configuration file : server { listen 80; server_name xxxxxxxxx; root /home/user/frontend/build; index index.html; location / { root /home/user/frontend/build; try_files $uri /index.html; } location = /favicon.ico { access_log off; log_not_found off; } location /django_static/ { root /home/user/backend; } location /media/images/ { include /etc/nginx/mime.types; root /home/user/backend; } location /api/{ proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/user/backend/backend.sock; } } Here is my media settings in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/',include('api.urls'))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also when i try to access the files using http://server/media/images/image1.jpg the browser just times out and i get no response , so I nothing is logged in /var/log/nginx/error.log . This is my first deployment so any help is … -
DRF: how to mix model fields directly inside a serializer
Suppose I have class Model1(models.Model) first_name = models.CharField(_('first name'), max_length=150, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) class Model2(models.Model): location = models.TextField() phone = models.CharField(max_length=15) I want to create a serializer using these fields. This has nothing to do with the models or the POST transaction. Just i want to use the definition of the models class CombinedSerializer(serializer.ModelSerializer): class Meta: model = Model1 fields = ['first_name'] model = Model2 fields = ['location'] So that i dont have to define them again. -
Dango rest framework: mixing some fields of one model with another and make a serializer
I have the User model and UserProfile model. User model contains the following: email password first_name last_name and UserProfile model contains class UserProfile(models.Model): user = models.OneToOneField(on_delete=models.CASCADE, primary_key=True) photo = models.ImageField() location = models.TextField() phone = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to create an api endpoint where User can edit the following fields and save after login --> from User first_name last_name --> from Userprofile photo location phone In normal Django forms. I can use multiple forms and validate them and save. User will see them as one form. In serializers how can I do this -
Fixing a type error for xhtm2pdf in a Django Project
I am trying to generate a PDF for my Django Project. I have used pip install xhtml2pdf The PDF was generate with plain text but when I added style in the pdf.html I got this Exception Type: TypeError: '<' not supported between instances of 'int' and 'NoneType' Here is the views.py: def admin_order_pdf(request,info_id): info = get_object_or_404(Info, id=info_id) template_path = 'businessplan/pdf.html' context = {'info': info} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # response['Content-Disposition'] = 'attachment; filename="report.pdf"' response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Info.id) # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response Here is the pdf.html {% load static %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'css/report.css' %}" /> <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">--> <title>{{ info.businessName }}</title> <style> @charset "UTF-8"; @font-face { font-family: Fira Sans; font-weight: 400; src: url('/static/img/FiraSans-Regular.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: 400; src: url('/static/img/FiraSans-Italic.otf'); } @font-face { font-family: Fira Sans; font-weight: 300; src: url('/static/img/FiraSans-Light.otf'); } @font-face { font-family: Fira Sans; font-style: italic; font-weight: … -
Django static files not showing
I hav gone through my settings.py file to look at my static file setting STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') but all my static files are nt showing when the page loads. Please what could be going on -
Django Not Found: /calendar/{'% static 'cal/css/styles.css' %}
I'm trying to make event calendar using django. 404 Not Found error messages appears I tried to switch the file directory and check spelling error but It doesn't work at all To figure it out I've been searching for several hours still stuck in the problem can anybody help me ? Here is base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css"> <link rel="stylesheet" type="text/css" href="{'% static 'cal/css/styles.css' %}"> <title>Django Calendar App</title> </head> <body> {'% block content %} {'% endblock %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {'% block script %} {'% endblock %} </body> </html> display appears when I run server error message I found from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6l5=#1_ur(n*=ctu)*yh3_m62oq%jkpt(+i66s#u@el)xb57*#' # SECURITY WARNING: don't run with debug turned on … -
Customize Django Default Login Form
I'm creating a login page using Django auth and struggling to understand how to customize the form fields generated by the form.as_p method. login.html <form method="post"> {% csrf_token %} {{ form.as_p }} <div class="text-center mt-3"> <button class="btn btn-lg btn-primary" type="submit">Log In</button> </div> </form> I'm looking for the rendered HTML to be: <div class="mb-3"> <label>Email</label> <input class="form-control form-control-lg" type="email" name="email" placeholder="Enter your email"/> </div> <div class="mb-3"> <label>Password</label> <input class="form-control form-control-lg" type="password" name="password" placeholder="Enter your password"/> <small> <a href="/forgot-password">Forgot password?</a> </small> </div> -
What is the best and future proof language to write a web app today?
Is Django better than Flask and Php nowadays? If not, what front and back end combo should I use? The goal is to make a forum site like reddit -
Multiple lines for TabularInline fields
I'd like to see the child model in the admin page in tabularinline format. The problem is that I have 10 entries in the child model and it goes out of the page if I just use class ChildClassInline(admin.TabularInline): model = MyChildClass I don't want to use the StackedInline because the display format is not as clean as TabularInline. Could you please help me out with this? -
Django copy value from one field to another
Please tell me how can I copy value from one field to another. Please look on this example: class MyImage(models.Model): name = models.CharField(max_length=128, blank=False) width = models.PositiveIntegerField(blank=False) ---> height = models.PositiveIntegerField(blank=False) ---> new_image = ProcessedImageField(processors=[ResizeToFill(500, 500)], <--- format='JPEG', options={'quality': 60}) I have to to swap first 500 into value from variable width and and second 500 into variable height. Thanks in advance! :) -
Django: make list_display different from the actual variable
So I have a django model called clown: And I make the list of attributes show up in Django admin like this: How do I make it so that the list in the Django Admin UI is different from the actual variable? Like let's say the variable is identification and I want it to show up as id in the administration.