Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we automate migrations for multiple database in django?
I am working with mult-tenant setup in django.I have multiple databases for which I am looking for a way to run a migration across all the databases linked in my settings.py file in one go. Currently, I have to do "python manage.py makemigrations --database=db_name " for all the databases one by one. -
Is there a way to change the autogenerated shema name of a serializer in drf-spectacular
I got many serializers named 'InputSerializer' and 'OutputSerializer' which translates to 'Input' and 'Output' schema name in drf-spectacular. This ends up referring the api endpoints to the same schema. Is there a way to override the autogenerated schema names of these serializers without changing the name of the class? -
Connect webRTC javascript to Django
My question is: How can I send my webRTC audio and video data to Django server and then apply some ML operations. I can successfully create a P2P connection in webRTC using Django channels for communicating between two clients. Any suggestions or solutions are highly respected -
How to use multi-level {%url%} with Django in HTML template - Class Based Views
Im utilizing class based views: I have an app that has 2 sublevels urls files and 1 view file portfolio_menu.urls: app_name = 'portfolio' urlpatterns = [ path('test', include('store.urls', namespace='store')), path('', views.menu), ] store.urls: app_name = 'store urlpatterns = [ path('', include('product.urls', namespace='product')), ] product.urls: app_name = 'product' urlpatterns = [ path('', views.ProductListView.as_view(), name='list'), ] the funcion I want to get, but don't know the sintax: <a href="{%url portfolio:store:product:list%}"></a> #I wish something like that -
Edit and Add in django
How to allow all fields to be added to the database and only some to be edited in django class PageAdmin(admin.ModelAdmin): list_display = ('rooms', 'first_name', 'last_name', 'visit_date','leave_date','admin') list_filter = ('rooms',) readonly_fields = ('visit_date',) admin.site.site_header = 'Uzbegim' def get_form(self, request, *args, **kwargs): form = super(PageAdmin, self).get_form(request, *args, **kwargs) form.base_fields['admin'].initial = request.user return form (so that after creation it was impossible to edit a certain field) class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True,verbose_name='Релевантность') category = models.CharField(max_length=150,verbose_name='Категория') def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE,verbose_name='Номер',help_text='Номер в который хотите заселить гостя!') first_name = models.CharField(max_length=150,verbose_name='Имя') last_name = models.CharField(max_length=150,verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='Администратор') pasport_serial_num = models.CharField(max_length=100,verbose_name='Серия паспорта',help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа',help_text='Загружайте файл в формате .pdf') visit_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day, hour=datetime.datetime.now().hour, minute=datetime.datetime.now().minute, second=00,),verbose_name='Дата прибытия') leave_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day + 1, hour=12, minute=00, second=00),verbose_name='Дата отбытия') guest_count = models.IntegerField(default=1,verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False,verbose_name='Релевантность',help_text='При бронирование отключите галочку') -
Can I use any method to choose a specific foreign key like I used while using get in Django?
Can I use any method to choose a specific foreign key like I used while using get? session = StudentReporter.objects.get(pk=pk).session_report.session.pk session_report = StudentReporter.objects.get(pk=pk).session_report.pk studentsession = StudentSessions.objects.filter(session=session).select_related('student', 'session', 'session__teacher', 'session__name', 'session__day') # I tried this for loop but it returns a string not a model instance student = tuple([(student.student,student.student) for student in studentsession]) self.fields['student'] = forms.ChoiceField(choices= student) I want the code to be like that session = StudentReporter.objects.get(pk=pk).session_report.session.pk session_report = StudentReporter.objects.get(pk=pk).session_report.pk # watch the change in the following lines studentsession = StudentSessions.objects.filter(session=session).select_related('student', 'session', 'session__teacher', 'session__name', 'session__day').students self.fields['student'] = forms.ChoiceField(choices= studentsession) as I can use the students in models StudentSessions model in models.py class StudentSessions(models.Model): student = models.ForeignKey(Student, related_name='student_session', on_delete=models.CASCADE) session = models.ForeignKey(Session, related_name='student_session', on_delete=models.CASCADE) class Meta: unique_together = ['student', 'session'] def __str__(self): return f'{self.student.name}, {self.session.teacher}, {self.session.time}, {self.session.name} ' # type: ignore -
data base or text file and excel file in Django
if you have some fixed data in Django, for example, ten rows and 5 columns. Is it better to create a database for it and read it from the database, or is it not good and it is better to create a dictionary and read the data from the dictionary? In terms of speed and logic and ... If the database is not a good choice, should I write the data as a dictionary in View Django or inside a text file or inside an Excel file? Whichever method is better, please explain why. -
django.db.migrations.exceptions.NodeNotFoundError pytest
I have troubles with migrations when i run pytest. Tracebak django.db.migrations.exceptions.NodeNotFoundError: Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') Migration file: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ('contenttypes', '0002_remove_content_type_name'), ] I try to python manage.py flush and delete all migrations folders. But it doesn't work for my case. Can you give me some advices for this trouble ? -
Javascript remove class="d-none" function not defined HTMLSpanElement.onclick (Uncaught ReferenceError)
I'm trying to link a Javascript remove function (i.e. the ability to hide/unhide a dropdown menu) from a button on my website's navigation bar. When I run my server clicking the button doesn't do anything, and my console is giving me an Uncaught ReferenceError: Uncaught ReferenceError: showNotifications is not defined at HTMLSpanElement.onclick ((index):61:135) social.js: function showNotifications() { const container = document.getElementById('notification-container'); if (container.classList.contains('d-none')) { container.classList.remove('d-none'); } else { container.classList.add('d-none'); } } The HTML document the function is linked to: show_notifications.html: <div class="dropdown"> <span class="badge notification-badge" style="background-color: #d7a5eb;" onclick="showNotifications()">{{ notifications.count }}</span> <div class="dropdown-content d-none" id="notification-container"> {% for notification in notifications %} {% if notification.post %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked your post</a> <span class="dropdown-item-close">&times;</span> </div> {% elif notification.notification_type == 2 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} commented on your post</a> <span class="dropdown-item-close">&times;</span> </div> {% endif %} {% elif notification.comment %} {% if notification.notification_type == 1 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} liked on your comment</a> <span class="dropdown-item-close">&times;</span> </div> {% elif notification.notification_type == 2 %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} replied to your comment</a> <span class="dropdown-item-close">&times;</span> </div> {% endif %} {% else %} <div class="dropdown-item-parent"> <a href="#">@{{ notification.from_user }} has started … -
ProgrammingError at / relation "website_request" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "website_request"
this is my first deployment to heroku and i am getting the above error, i did everything right, I mean I think so at least and still getting the error. am deploying via heroku CLI -
Cannot locate local path of uploaded file to Heroku from django using ephemeral file system( Web based Application)
I have recently deployed my first django project to Heroku. My project is a Web Based Application that allows users to upload a file to the server and the server will export a product after processing it. The views.py processing the upload process is as follows if form.is_valid(): task= form.save(commit=False) task.task_created_by = request.user task.save() The model is as follows class db(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) excel = models.FileField(upload_to='task/excel/') userinput = models.FileField(upload_to='task/userinput/') output= models.FileField(blank=True,null=True) uploaded_at = models.DateTimeField(auto_now_add=True) settings.py #Media path setting MEDIA_URL = '/uploaded/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded') Therefore, a part of the server involves accessing the user uploaded file and thus processing it. I did not set up any external file storage service(e.g. aws s3) and is only using the default ephemeral file system. when I first run the application the server response this error No such file or directory: '/app/uploaded/task\\excel\\abc.xlsx' However, as I am using the django model file field, when I go to the django admin panel, it shows the file is uploaded and can be downloaded from the admin panel... Therefore, the question is where did Heroku saved the uploaded file locally... I have tried the heroku run bash method to search for … -
Django arguments '(1, '')' not found. 1 pattern(s) tried:
Error Reverse for 'comment_fix' with arguments '(1, '')' not found. 1 pattern(s) tried: ['comment_fix/(?P[0-9]+)/(?P<comment_id>[0-9]+)\Z'] My problem Why can't I find the information (?P<comment_id>[0-9]+)\Z'? Where can I edit to get information? MY html <div> <form method="POST" action="{% url 'create_comment' post.id %}"> {% csrf_token %} {{ comment_form }} <input type="submit"> {% for i in post.question_set.all %} <p>comment: {{ i.subject }}</p> <p>time: {{ i.created_at }}</p> <a href="{% url 'comment_fix' post.id question.id %}">comment fix</a> <hr> {% endfor %} </form> </div> MY urls urlpatterns = [ path('home/', views.home, name='home'), path('home/top', PostList.as_view(), name='top'), path('home/top/<int:pk>/', views.top_detail, name='top_detail'), path('search/', views.search, name='search'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='main/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('create_comment/<int:post_id>', views.create_comment, name='create_comment'), path('comment_fix/<int:pk>/<int:comment_id>', views.comment_fix, name="comment_fix") ] My models class Top(models.Model): product_name = models.CharField(blank=True, null=True, max_length=30) product_price = models.CharField(blank=True, null=True, max_length=30) product_image = models.ImageField(blank=True, null=True, upload_to="images") product_explain = models.TextField(blank=True, null=True, ) class Question(models.Model): post = models.ForeignKey(Top, null=True, on_delete=models.CASCADE) subject = models.CharField(null=True, max_length=150) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject My views def top_detail(request,pk): post = get_object_or_404(Top, pk=pk) post_list = Top.objects.get(pk=pk) comment_form = CommentForm() return render(request, 'main/top_detail.html', {'post':post, 'post_list':post_list,'comment_form':comment_form}) def create_comment(request, post_id): filled_form = CommentForm(request.POST) if filled_form.is_valid(): form = filled_form.save(commit=False) form.post = Top.objects.get(id=post_id) form.save() return redirect('top_detail',post_id) #comment fix @login_required def comment_fix(request, comment_id, pk): question = Question.objects.get(id=comment_id) comment_form = CommentForm(instance=question) … -
Django serializer updation only one column shld have same values and remaining columns shld get new value option to entry for a user
Here i do have some columns called task_name tht should every day update same perivous task_name but task_value shld not update it shld give option to user to enter new task_value and new threshold value my models class SubTask(models.Model): tasks = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='task_regular', null=True, blank=True) task_id = models.AutoField(primary_key=True) regular_task_id = models.PositiveIntegerField(blank=True, null=True) task_name = models.CharField(max_length=200, blank=True, null=True) task_value = models.CharField(max_length=200, blank=True, null=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(blank=True, null=True) threshold = models.FloatField(blank=True, null=True) views class SubTaskViewSet(viewsets.ModelViewSet): pagination_class = None queryset = SubTask.objects.all() serializer_class = SubTaskSerializer Serializer class SubTaskSerializer(serializers.ModelSerializer): class Meta: model = SubTask fields = '__all__' Let me know which method i need to follow -
passing json from js to views in django
I am trying to pass some data from JavaScript to python views here is my js code sourcejson=JSON.stringify(sourceGoal) jsonmap=JSON.stringify(mapgraph.showNodes()) json=JSON.stringify(straightLineToDestination) $.ajax({ type: "get", url: "", dataType: 'json', data: jsonmap, success: function(response){ graphview.appendChild('<p>'+response.result+'</p>') } }); $.ajax({ type: "get", url: "", dataType: 'json', data: sourceGoal, }); $.ajax({ type: "get", url: "", dataType: 'json', data: straightLineToDestination, }); here is my views.py import imp import json from telnetlib import STATUS from urllib import request from django.shortcuts import render from django.http import HttpResponse import os from django.views.generic import View from queue import PriorityQueue from django.http import JsonResponse class ajaxhandlerview(View): def get(self,request): return render(request,'index.html') def post(self,request): global GRAPH global straight_line global SourceandGoal GRAPH=json.loads(request.Get.get('jsonmap')) straight_line=json.loads(request.Get.get('straightLineToDestination')) SourceandGoal=json.loads(request.Get.get('sourceGoal')) print(GRAPH) print(straight_line) print(SourceandGoal) if request.is_ajax(): heuristic, cost, optimal_path = a_star(SourceandGoal.start, SourceandGoal.end) result=' -> '.join(city for city in optimal_path) return JsonResponse({"heuristic":heuristic,"cost":cost,"optimal_path":optimal_path,"result":result},STATUS=200) return render(request,'index.html') def a_star(source, destination): """Optimal path from source to destination using straight line distance heuristic :param source: Source city name :param destination: Destination city name :returns: Heuristic value, cost and path for optimal traversal """ priority_queue, visited = PriorityQueue(), {} priority_queue.put((straight_line[source], 0, source, [source])) visited[source] = straight_line[source] while not priority_queue.empty(): (heuristic, cost, vertex, path) = priority_queue.get() if vertex == destination: return heuristic, cost, path for next_node in GRAPH[vertex].keys(): current_cost = … -
__init__() got an unexpected keyword argument 'content_type'
I have @action in DRF ModelViewSet which should export data into csv @action (detail = False, methods = ['get']) def export(self,request): csv_response = HttpResponse(content_type='text/csv') csv_response =['Content-Disposition']='attachement; filename="data.csv"' writer = csv.writer(csv_response) row = ','.join(['a','b','c']) writer.writerow(row) return csv_response but this method returns next error : __init__() got an unexpected keyword argument 'content_type' What is the reason and how can I fix it? Thanks in advance -
form.save() not working in django using FileField() in models. Uploaded File is not getting saved in the directory
I am pretty new to Django and am trying to save the uploaded image by the user to a folder. After researching a bit, I learned that form.save() saves the form and the image to my folder. But it isn't working. You might see GridFS codes, it's because I'm also trying to save the uploaded file to the MongoDB database via GridFS. I've mentioned the codes and errors below. I have these lines of code in my views.py file def upload_file(request): if request.method == 'POST': form = UploadFile(request.POST, request.FILES) file = request.FILES['file'] extension = str(file).split('.')[1] img_extension = ['jpeg', 'jpg', 'png', 'tiff', 'raw', 'gif'] video_extension = ['mp4', 'mov', 'wmv', 'avi', 'mkv', 'webm'] if extension in img_extension: if form.is_valid(): form.save() return HttpResponse('Success') return HttpResponse('It is a Image Extension - ' + str(extension)) elif extension in video_extension: if form.is_valid(): form.save() return HttpResponse('Success') return HttpResponse('It is a Video Extension - ' + str(extension)) else: return HttpResponse('Please Upload a proper Image or a Video format') else: form = UploadFile() context = { 'form': form, } return render(request, 'upload.html', context) I have a simple FileField() in the models.py file from django.db import models from django.conf import settings from djongo.storage import GridFSStorage from django.core.files.storage import FileSystemStorage from … -
Mess with models primary key. Django
There are two models: class Parent(models.Model): name = models.CharField(max_length=25) date = models.DateField(default=now) class Child(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) In my app I have a set (or list) of parents within a set of child elements inside. When I try to delete child element - request redirects me to the wrong parent. Here below my view: def deleteChild(request, pk): child= get_object_or_404(Child, pk=pk) parent= get_object_or_404(Parent, pk=child.parent.pk) if request.method == 'POST': child.delete() return redirect('detail', pk=parent.pk) context = {'parent': parent.pk} return render(request, 'parent-detail.html', context) my url: path('child-delete/<int:pk>', views.deleteChild, name='child-delete'), I assume one of the reasons are - incorrect ID pass... Point me please what is wrong with this and much appreciate to You All if You give me an advice how to correctly prescribe Models for such case (maybe best practice if any). Because I expect same issue when I start doing updateChild view X))). Thanks a lot and have a nice day! -
ReactJS with Django Elements Displayed As Text
I try to get elements inside my div but they are displayed as text and not Elements. I use Django as the back-end and ReactJS as a link import in my HTML template on the front-end. my template is like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin</script> </head> <body> <div id ="form-container"> </div> <!-- Bootstrap JS CDN --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> <script src="{% static '/js/login.js' %}"></script> </html> and my react JS file is like this: const hello = ('<h1>test</h1>'); const root = ReactDOM.createRoot(document.getElementById("form-container")); root.render(hello); Have tried removing the ' ' or the parenthesis but can't get it to work it either it shows invalid syntax. -
Austi updating Django postgres database when changes in legacy database are made in a docker container
I'm working on a Django project with docker which use different legacy Microsoft SQL Server database. Since I didn't want to alter those legacy databases I use inspectdb and Django router to create models and then use the data there to read and write a default Postgres database with all the Django specific tables. Everything was working fine, each instance of my model objects have the initial data from the SQL server db populating into the Postgres db. However whenever anything is updated in the SQL server db the data in the is not updating in Postgres db unless the docker container is stop and restarted. I'm wondering is there a way to autoupdate my postgres db when changes are made in the connected SQL Server db's with stopping the container? Would I need to use something like celery or a cron job to schedule updates? I've used cron jobs before but only to pull from an api. Is it possibly to run celery or a cron job just on a database and not an api? Or is there a solution that's simplier? I'm also running with nginx and gunicorn on an Ubuntu server. Using volumes to persist db. -
How to display background image in email letter (gmail smtp)
I use WagtailCMS and I installed wagtail-birdsong plagin (its for sending topics for subscribers) It uses django-mjml for email template. When admin create a letter, he choses an image as a background for email letter, but this image doesnt appear at all. I have such HTML- file: {% extends "mail/base.html" %} {% load wagtailimages_tags %} {% block email_body %} {% image self.header_background original as bg_img %} <mj-hero mode="fluid-height" background-width="600px" background-height="400px" background-url="{{ site.root_url }}{{ bg_img.url }}" padding="100px 0px"> <mj-text align="center" font-size="32px" color="orange">{{ self.headline }}</mj-text> </mj-hero> <mj-section css-class="richtext"> <mj-column> <mj-text font-size="18px">Hello {{ contact.email }}!</mj-text> {% for b in self.body %} {{ b }} {% endfor %} </mj-column> </mj-section> {% endblock email_body %} {% block email_head %} <mj-style> .richtext h3 { font-size: 26px; } .richtext p { font-size: 16px; line-height: 1.5; } </mj-style> {% endblock email_head %} base file: {% load mjml %} {% mjml %} <mjml> <mj-head> {% block email_head %} {% endblock email_head %} </mj-head> <mj-body> {% block email_body %} {% endblock email_body %} </mj-body> </mjml> {% endmjml %} so when I get this email and going to dev-tools I can see the root to the image and I can see the image via this root, but I also got a … -
Django 404 Error, views not found. Why? View is not show up or is not found
I programmed in Ruby beforehand and am now moving to Django. I am trying to follow the article here. https://docs.djangoproject.com/en/4.0/intro/tutorial01/ #polls/url.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] # mysite /urls.py """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] Here is my tree: polls/ --> init.py -> admin.py -> apps.py -> migrations/ --> init.py -> models.py -> tests.py -> urls.py -> views.py -> Of course, I ran django-admin startproject mysite before all of tihs and the output for the version is: └──╼ $python -m django --version 4.0.4 I tried starting the server: ─╼ $python manage.py runserver Watching for file changes with StatReloader Performing system checks... System … -
Why does my Django form keeps saying "this field is required"
I'm a beginner at Django. My registration page is making my form invalid and it keeps printing the same error even though both the password fields are filled and they are the same. I have only attached any codes that are relevant to the password fields Error: <ul class="errorlist"><li>password1<ul class="errorlist"><li>This field is required.</li></ul></li><li>password2<ul class="errorlist"><li>This field is required.</li></ul></li><li>__all__<ul class="errorlist nonfield"><li>Passwords do not match.</li></ul></li></ul> forms.py: class RegisterForm(UserCreationForm): password1 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password1', 'id': 'floatingPassword', 'placeholder':'Password', }), ) password2 = forms.CharField( required=True, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'name': 'password2', 'id': 'floatingConfirmPassword', 'placeholder':'Confirm password', }), ) class Meta: model = User fields = [ 'password1', 'password2', ] # Compare password def clean(self): self.cleaned_data = super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password != password2: raise forms.ValidationError("Passwords do not match.") return self.cleaned_data views.py (In prototype) def register(request): # Create a new form if request.method == 'GET': form = RegisterForm() return render(request, 'users/register.html', {'form': form}) # When the user submits the form elif request.method == 'POST': form = RegisterForm(request.POST) # Check if the form is valid if form.is_valid(): print('FORM is valid!') print(form.cleaned_data) form.save() #user = form.cleaned_data.get('username') #messages.success(request, f"Account has been created for {user}") # UPDATE THE URL LINK IN THE FUTURE return redirect('/login') … -
Can I user `django-filebrowser` with Django version 2.2.6
Hi I am working on django app version 2.2.6 and I want to use tinymce.models HTMLFIELd in my model and one of the requirement is the user want when click on the image tab to pop up with insert image url or brows from local file, the defult of HTMLFIEL is to render only image url option and for me to add the second options it seems I need to install ``django-filebrowser` but when I looked at the docs its say requirement django higher that the django version I am using and I don't want to upgraed django, is there any way to make it work -
Django Files doesn't save
I want to do a django project where you upload an image and this image is displayed on another page. I can edit it only with admin panel. Here is the code: Views.py def home(request): all1 = New.objects.filter(username='mynameis12').all() if not request.user.is_authenticated: return redirect('/login/') return render(request, 'home.html',{'alls':all1}) Models.py class New(models.Model): username = models.CharField(max_length=200) image = models.ImageField(upload_to='media') Forms.py class New1(ModelForm): username = forms.CharField(max_length=200) image = forms.ImageField(required=False) class Meta: model = New fields = ['username','image'] The image is showed but it doesn't be saved. What should I do? Thanks. -
Non FK models tied together by ID (unmanaged model) - how to filter in Django?
I have two models that are related - but they are not a FK relationship in Django because one is a non-managed model with the data coming from a pre-populated DB table. class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="locationID") grade = models.CharField(db_column="grade", max_length=10) class Meta(object): managed = False db_table = "mytable_Enrollments" class Location(models.Model): name = models.CharField(max_length=50) alternate_name = models.IntegerField() I'm trying to filter Enrollment models using a list of Location models - but they are not tied together in a FK relationship. I am trying to get enrollments for a particular location like this: # This does not work properly - but does not hit the db which is what I want location_ids = Location.objects.filter(id=1).values_list("id", flat=True) enrollments = Enrollment.objects.filter(location_id__in=location_ids) However, this returns an empty queryset. If I cast location_ids to a list (like this: list(location_ids)) and then filter on that, it works. # This works properly - but hits the db which is NOT what I want location_ids = Location.objects.filter(id=1).values_list("id", flat=True) enrollments = Enrollment.objects.filter(location_id__in=list(location_ids)) Is there a way to use the Django ORM to get what I want in this case without causing it to evaluate the queryset?