Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In query set can we use distinct with exclude and orderby in django
I am working in a django project. The query set is longestPendingTask = WorkAssignment.objects.filter(isActive=True,client_id = request.session["clientId"],expectedDate__lte=today).exclude(status="Completed").order_by("expectedDate") It is having exclude and order_by. I want to use distinct to show only unique records, but it does not work. Also the field in distinct is foreign key from another table. Please guide me how to show distinct records. -
Django rest framework's StringRelatedField is throwing KeyError
I have the following model classes. class Categories(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='category_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) class Meta: unique_together = ('business', 'name') class Menu(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True) business = models.ForeignKey(Business, related_name='menu_business', on_delete=models.CASCADE) name = models.CharField(max_length=128) description = models.CharField(max_length=128) category = models.ForeignKey(Categories, related_name='menus', on_delete=models.CASCADE) price = models.IntegerField() class Meta: unique_together = ('business', 'name', 'category') def __str__(self): return '%s %s %s' % (self.name, self.price, self.description) and I have imported these classes as following as they are located in a separate package Categories = apps.get_model('business', 'Categories') Menu = apps.get_model('business', 'Menu') and this is my serializer class class GetCategoriesSerializer(serializers.ModelSerializer): menus = serializers.StringRelatedField(many=True) class Meta: model = Categories fields = ('name', 'menus') and views is class GetCategories(generics.ListAPIView): """ Returns a list of businesses to the user. It'd read only and no authentication is needed """ permission_classes = [ReadOnly] queryset = Categories.objects.values() serializer_class = GetCategoriesSerializer and url has the following path('customer/<str:pk>/categories', GetCategories.as_view()), I am getting the following error KeyError: 'menus' I looked into the DRF example and this seems to be a simple thing to achieve. https://www.django-rest-framework.org/api-guide/relations/#api-reference But I am kind of stuck at this point. Am I doing anything wrong? Thanks in advance for any help. -
I need a good way to divide a list in Django list view
Hi i'm quite new in django I'm making a student man\ agement program. Currently, the paging and search function have been coded as query and It works in combination , but since we receive new students every year, school_year is important. I want to see the student list by school_year that I want by pressing the year on the top right. I've been thinking about implementing it as a query, but it seems too complicated(I think it's too complicated to combine with the queries that have already been created.), and it's too unnecessary to make a listview for each grade. pls give me some good idea or solution thanks ! listveiw template IMG my views.py here ''' class StudentList(ListView): model = Student template_name = 'student/orders.html' context_object_name = 'students' paginate_by = 12 def get_queryset(self): keyword = self.request.GET.get('keyword') if keyword: object_list = self.model.objects.filter( Q(name__icontains=keyword) | Q(email__icontains=keyword) | Q(student_mobile__icontains=keyword) ) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): context = super(StudentList, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 # Display only 5 page numbers max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if … -
Images from Media directory doesn't show up
My diretory looks something like this: project |_app |_ media |_ profile_pics |_ 1x1.jpg |_ templates |_ urls.py ... I already specified the MEDIA settings on the settings.py: # This part is right below the BASE_DIR MEDIA_DIR = os.path.join(BASE_DIR, 'media') # This part is right at the end of the file # Media MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' On my urls.py: from django.conf.urls.static import static from pro_five import settings from . import views app_name = 'my_app' urlpatterns = [ url('^$', views.index, name='index'), url(r'^registration/', views.register, name='register'), url(r'^login/', views.user_login, name='user_login'), url(r'^logout/', views.user_logout, name='logout'), url(r'^profile/', views.profile, name='profile') ] urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) And finally on my template: <img src="media/profile_pics/1x1.jpg" alt="asdasdasd"><br> I don't know why but it just doesn't show up. I followed a lot of solutions only but seems nothing to work for me. I'm relatively new to Django so please forgive my naiveness. Any advices? Thanks a ton! -
Cannot send null to state in order to make ImageField change to null in React and Django
What I want to do Set null in ImageField. And I want to make the value of ImageField that a models has null. Problem When I send Patch request, I got an error like below. The submitted data was not a file. Check the encoding type on the form. Actually, I send image data as file which comes from input type="file". When I send this request to set an image in a model, it works well. But when I send this request again to delete the image that the models has, it doesn't work. How could I set null to ImageField? Or, how could I delete an image that a model already has? I am a beginner to React and Django so I would like you to help me out. I post my code related to my question below. Thank you very much. models.py class User(AbstractUser): # AbstractUserでpasswordは定義済みのため、ここではpasswordを再定義しない(DBにはちゃんと保存される。) username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) profile = models.TextField(max_length=800, blank=True, null=True) icon = models.ImageField(upload_to="images/", blank=True, null=True) background = models.ImageField(upload_to="images/", blank=True, null=True) # AbstractUserはfirst_name,last_nameを保持しているため無効化 first_name = None last_name = None is_staff = models.BooleanField( ('staff status'), default=True, help_text=( '管理サイトへのアクセス権を持っているかどうか'), ) is_active = models.BooleanField( ('active'), default=True, help_text=( 'ユーザーがアクティブかどうか' ), ) is_superuser = models.BooleanField( … -
Show only loaded images in a Carousel/Modal - Bootstrap
below is the layout of a modal in my website: The problem is: in the database there are only 2 images to be displayed in this modal but as I'm using a preconfig Boostratp it is showing always 4 images, regardeless the amount it'd be necessary. My goal is to display, in this case, only 2 images, something like this: In the backend I'm working with Django. Below, my template: <!-- modal area start--> {% for product in products %} <div class="modal fade" id="modal_box-{{ product.id }}" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <div class="modal_body"> <div class="container"> <div class="row"> <div class="col-lg-5 col-md-5 col-sm-12"> <div class="modal_tab"> <div class="tab-content product-details-large"> <div class="tab-pane fade show active" id="tab1" role="tabpanel" > <div class="modal_tab_img"> <a href="#"><img src="{{ product.image.url }}" alt=""></a> </div> </div> <div class="tab-pane fade" id="tab2" role="tabpanel"> <div class="modal_tab_img"> {% if product.image2 %}<a href="#"><img src="{{ product.image2.url }}" alt=""></a>{% endif %} </div> </div> </div> <div class="modal_tab_button"> <ul class="nav product_navactive owl-carousel" role="tablist"> <li > <a class="nav-link active" data-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="false"><img src="{{ product.image.url }}" alt=""></a> </li> {% if product.image2 %} <li> <a class="nav-link" data-toggle="tab" href="#tab2" role="tab" aria-controls="tab2" aria-selected="false"><img src="{{ product.image2.url }}" alt=""></a> </li> {% endif %} </ul> … -
How to call specific data respective to a particular choice in django?
So I am new to django. Suppose I want to choose a particular option from a dropdown box and show the data regarding that particular option in the website in the same webpage considering the fact that i am trying to make a single page app. Also I am trying to pull the data from an API. -
ctrl+click feature is broken in Django project in Pycharm
Hi I have a Django project that I could nicely navigate from view, to template file by ctrl+click on the html file. I made some changes to project and split my setting.py into base, local,production and put them in a settings folder. I made some changes in settings.py on BASE_DIR to reflect the changes accordingly. Now the project is working, however ctrl+click feature is broken and not working. any Idea, why this is lost? -
How do I pass a variable in the URL to a Django list view?
First things first, I want to state I have seen the post created here. The problem is that I am still very new to the Django framework and every attempt I had at implementing this strategy into my code , failed. Anyways, I was curious about how I could pass a string value from the URL into my listview. In my case, the variable named item so I can do a filtered query. This was extremely easy to do on function based views, but I am struggling to do the same on these class based views. Thanks! Class Based View: class PostListView(ListView): model = Post.objects.get(subject_name=item) template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 Routing: path('<str:item>/', PostListView.as_view(), name='post-view') -
Why Django send email function is sending email twice?
I have Used Django EmailMessage function . Here is views.py file. def send_bill_mail(request): context_dict={ "name": "SANKET" } html_message = render_to_string('home/email_templates/bill_generation.html', context_dict) try: email = EmailMessage( ' Welcome to store', html_message, to=['abc@gmail.com'] ) email.content_subtype = "html" email.send() except Exception as e: messages.error(request,"Something Went Wrong !") return redirect('home:dashboard') Here Is settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = 'xyz' EMAIL_PORT = 587 Following Exception is Occured During processing of views. Exception happened during processing of request from ('127.0.0.1', 50522) Traceback (most recent call last): File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\sanke\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
How to customize user profilesingup when using django-allauth
I am trying to create a form class that asks users for additional data for my custom user model only on signup. Currently in my aap/forms.py I have: class SetUniversityForm(forms.ModelForm): program = forms.CharField( required=False, widget=forms.TextInput( attrs={ "placeholder":"What are you studying?", "class": "form-control", } ) ) university = forms.ChoiceField( label='', required=True, choices = UNIVERSITY_CHOICES, widget=MySelect( attrs={ "class":"form-control", } ), ) class Meta: model = Profile fields = ('university','program') def signup(self, request, user): user.university = self.cleaned_data['university'] user.program = self.cleaned_data['program'] user.save() And be default user model is: class Profile(AbstractUser): bio = models.TextField() university = models.CharField(max_length=50) program = models.CharField(blank=True,max_length=100) In my settings.py I have: ACCOUNT_SIGNUP_FORM_CLASS = 'app.forms.SetUniversityForm' However, upon user signup for the first time using Google it still redirects to my LOGIN_REDIRECT_URL. How can I implement this? I have looked at: How to customize user profile when using django-allauth But I couldn't fix it. I have also tried using adapters. But I only require this information on signup. -
Display each element of a queryset separated with an <br> inside of a <td> in django template
Model class Tesis(models.Model): descripcion = models.CharField(max_length=50, blank=False, null=True) año = models.PositiveSmallIntegerField(blank=False, null=True) carrera = models.ForeignKey( Carrera, related_name="tesis_carrera", on_delete=models.SET_NULL, null=True) tutor = models.ForeignKey( Tutor, on_delete=models.SET_NULL, null=True, related_name="tutor_tesis") alumno = models.ManyToManyField(Alumno, related_name="alumno_tesis") class Meta: verbose_name_plural = "Tesis" verbose_name = "Tesis" def __str__(self): return self.descripcion VIEW class Listar_TesisListView(LoginRequiredMixin,ListView): queryset = Tesis.objects.all() template_name = "listar_tesis_cargadas.html" model = Tesis TEMPLATE <div class="table-container"> <table class="table"> <thead> <tr> <th class="has-text-centered" colspan="6"> LISTADO DE TESIS </th> </tr> <th>DESCRIPCIÓN</th> <th>AÑO</th> <th>CARRERA</th> <th>TUTOR</th> <th>ALUMNO</th> </thead> <tbody> {% for item in object_list %} <tr> <td>{{ item.descripcion }}</td> <td>{{ item.año}}</td> <td>{{ item.carrera }}</td> <td>{{ item.tutor}}</td> <td><{{item.alumno.all}}</td> {% for al in item.alumno.all %} <td> {{al}} <br> </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> WHAT I GET WHAT I WANT In the same <td> when the alumno queryset has 2 elements print the first and then make a breaking line and print the next one. Like this: Alumno Depru1 Alu2 depru2 I also tried this: {% if item.alumno.count > 1 %} {% for al in item.alumno.all %} <td> {{al}} <br>{{al}} </td> {% endfor %} {% else %} {% for al in item.alumno.all %} <td> {{al}} </td> {% endfor %} {% endif %} and I get: Also tried: % for al … -
Trouble with Fetch from JS to Django view
I could use assistance understanding and fixing my error for the following: Javascript calls the following function during some event on the page: function load_homePage() { // Pull all posts fetch('/homepage') .then(response => response.json()) .then(posts => { // Print all posts posts.forEach( function(post) { console.log(post) }) }) } Eventually, I will have JS create dynamic Div's to display all the data that comes in from the call. Fetch is calling to the following view: @csrf_exempt @login_required def view_homePage(request): posts = Post.objects.all() # Return entire set of posts to webpage return JsonResponse([post.serialize() for post in posts], safe=False) Here all I want is for Django to query the database, pull all the data from the Post model, and send it back to the page. The model is as follows: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): posterID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post") content = models.TextField(blank=False) timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "posterID": self.posterID, "content": self.content, "timestamp": self.timestamp } The Url.py file is also complete: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("post", views.new_post, name="posts"), path("homepage", views.view_homePage, name="homepage") ] When I try to get the event to … -
My web Page displays nothing when i use load static
Been Practicing Django for a month now.I have learnt the basics,i downloaded a frontend template and i am trying to build a website but when i load my server ,it just keeps on loading without displaying anything.No images or text just keeps loading on and on.I have watched tutorials and done exactly what is done there,then i found out that it does that when i use {%load static}.I already have my static directory and templates in my project. Please I need answers ASAP,Been at it for 4 straight days. enter code here ``URLS.PY from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('', views.estate,name='Estate'), ] -
How to display Ajax response data in Popup?
I have some data in response but I want to display that data in the popup, please let me know how I can display Ajax data in the popup. here is my views.py file... def myview(request): datas=TestForm.objects.all template_name='test.html' context={'datas':datas} return render(request, template_name, context) def myview(request, id): display=TestForm.objects.get(pk=id) template_name='test.html' context={'display':display} return render(request, template_name, context) here is my html file... {% for a in datas %} <a href="javascript:void()" class="btn btn-primary" onclick"exampleModal({{a.id)}})" data-url="{% url 'myap:list_single' a.id %}"> {{a.product_id}} </button> {% endfor %} here is my popup code...where I want to dispslay AJAX data... <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <tr> <td>{{datas.name}}</td> <td>{{datas.price}}</td> <td>{{datas.category}}</td> </tr> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> here is my AJAX code... function exampleModal(id){ $.ajax({ url: $(this).attr("data-url") type: 'get', dataType: "HTML" success: function(res) { $('.exampleModal').html(res); $("#exampleModal").modal("show"); } }); } -
Django queryset filter with if condition
How to apply a filter in django queryset only if a condition is met. I have a filter object that contains forms list. if forms contains "all" then i want to fetch all objects of the AnswerDetails model else i want to fetch only the u_id in the forms list Code: fil = self.d.get('filter', None) f_uid = fil.get('forms',["all"]) if "all" in f_uid: f_uid = [] a = AnswerDetails.objects.filter(proj=_p, form__u_id__in=f_uid).order_by('-saved_on') -
Django Can't open Admin page (Url Change and get message)
I am getting a message while trying to page Admin. This is default url page I change url to this When I click enter , url was change and get message How to fix this? -
Any suggestions on the methodology, languages and frameworks I should use to build a library managing robot?
I have a project to build an automated library robot.It will receive order of book from users by a website on library server and bring it.The robot and the webserver need to be connected to exchange data.Upon getting the necessary data from the webserver, the robot will search for the book using computer vision and bring the book to the user's table. -
Django FileField should only accept video files
here is my django model; class HomeVideo(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE, related_name="home_videos") home_video = models.FileField( blank=True, null=True, upload_to="home_videos", ) def __str__(self): return str(self.home) According to this stackoverflow link: Only accept a certain file type in FileField, server-side(which is the closest I was able to find to what I want), I have to specify the file type that I want my application to support. But my problem is, I want my application to accept all video file format, without having to specify all the long list of video file formats; which of course won't scale, because new video file format would emerge from time to time. So is they any way I could solve this problem? -
Django or Flask. Aspiring software developer
I hope you are well. I am novice software developer and the next step on my learning journey is to learn how to use Django or Flask. Which framework would you recommend for someone who is just starting in this field? I look forward to hearing your thoughts. Thanks a lot in advance, Matías -
How to integrate screens with django, screen integration, screens designed to be joined with frontend?
How to integrate screens with django, screen integration, screens designed to be joined with frontend using visual studio -
DRF: A theoretical approach on the proper use of Serializers and ViewSets
I love Python and Django, and I've been learning Django REST Framework for the past weeks, because there is no escape to REST today in 2020. In my hobbie project (which is a Python forum, ridicously called Pyrty because it is a Python Party), I decided to make a CRUD for the comments app. I did it (except by update), but I don't get what is the difference between putting the code in the Serializer and/or in the ViewSet. My create and list are in the Serializer, while delete is in the ViewSet. All of them are working as expected, but I don't want to code dirty and I wish to understand the important points and differences of putting something in one part or the other. comments.models.py: class Comment(PyrtyModel): # the inheritance class just adds creation and modification dates, and sorting stuff user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) positive_votes = models.ManyToManyField('users.User', related_name='c_positive_vote_set') negative_votes = models.ManyToManyField('users.User', related_name='c_negative_vote_set') score = 0 def __init__(self, *args, **kwargs): # init with the score (positive votes - negative votes) if the comment is persisted super(Comment, self).__init__(*args, **kwargs) if self.id is not None: self.score = ( self.positive_votes.all().count() - … -
Django "temporary" User Accounts
I have a django application that handles online orders. I want to make it such that end users can use the app without making an account. My solution to this, to avoid changing the code as much as posisble, is that users who don't have an account will give their email which will be used to make a "temporary" account or whatever the proper term is. Said account ideally would be later "activated" and the user could choose their password or whatever. The package django-lazysignup seems to be a good solution to this but I was wondering if there were any other recommendations or ideas? What would the best or usual practice with something like this be? -
How do we use Bootstrap 4 login forms with default login auth? Can we just grab the value from context?
I have the following in my project setting urls: path('accounts/', include('django.contrib.auth.urls')), Which gives me out of the box support for login, logout, registration and more. Without using crispy forms, etc, is there a way I can grab the values from bootstrap template below: <form method="post"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="username" class="form-control" id="username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password"> <small id="passwordHelp" class="form-text text-muted">Password must be at least 6 characters.</small> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> Or would I have to create my own log in function and do something like: username = request.POST.get("username") Classes are pretty complicating, and I am not sure how to go about this. Guidance would be appreciated. The tutorials I've seen all create their own forms in forms.py, but is there an easier way? -
ImportError: cannot import name 'Scheme'
when i type pip i get error File "/home/ubuntu/myproject/myprojectenv/bin/pip", line 6, in from pip._internal.cli.main import main File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/cmdoptions.py", line 24, in from pip._internal.cli.progress_bars import BAR_TYPES File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/cli/progress_bars.py", line 12, in from pip._internal.utils.logging import get_indentation File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/utils/logging.py", line 18, in from pip._internal.utils.misc import ensure_dir File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 31, in from pip._internal.locations import ( File "/home/ubuntu/myproject/myprojectenv/lib/python3.6/site-packages/pip/_internal/locations.py", line 18, in from pip._internal.models.scheme import Scheme ImportError: cannot import name 'Scheme'