Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-modeltranslation: Why to I have 3 columns for two translations in database
Here is the relevant section of my settings.py LANGUAGE_CODE = "de" gettext = lambda s: s LANGUAGES = [ ("de", gettext("German")), ("en", gettext("English")), ] TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True And I have this translation.py file in my awards app: from modeltranslation.translator import TranslationOptions, translator from .models import Award class AwardTranslationOptions(TranslationOptions): fields = ("title", "text") But in the database I get 3 columns for title: title title_en title_de And when I assign 1,2,3 to these three fields in the same order and save in admin I get the values: title: 2 title_en: 2 title_de: 3 It seems like title is always equal to title_en. Also, in the admin, the title field is required and the title_en and title_de are not required. What I had expected was to get only two fields, title_en and title_de of which title_de should be required since it is the default language. Can someone explain to me what is going on here? -
How to store selected values of the template in Django
I have searched a lot about how to store choices and dropdown list, but I could not find a solution for my situation. Here I have three classes with rating choices. models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) class Question(models.Model): text = models.CharField(max_length=100) def __str__(self): return self.text class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.IntegerField(choices=RATING_CHOICES, default=1) views.py Here I want to know how to write my function to store data. from django.shortcuts import render from .models import Question, RATING_CHOICES, Teacher def index(request): context = {'questions': Question.objects.all(), 'rating_choices': RATING_CHOICES, 'teacher': Teacher.objects.all()} return render(request, 'index.html', context) index.html <form action=""> <select name="teacher" id=""> {% for teacher in teacher %} <option value="{{teacher}}">{{teacher}}</option> {% endfor %} </select> {% for question in questions %} <ol>{{ question.text }}</ol> {% for choice in rating_choices %} <input type="radio" name="question_{{question.id}}" value="{{choice.0}}">{{choice.1}} {% endfor %} {% endfor %} <br> <input type="submit" value="Vote"> </form> I want to store selected values similar to the admin when you simply select your options and save the results. -
Updating a Boolean field with detail View
I want to believe you all are doing fine. i've a little issue I've been thinking my head out about. I've a class detail view that displays my model class object, which works perfectly fine. i want to create a functionality for one of the objects in my models paper = models.BooleanField(default=True, blank=True). in my template, i created a link so were a user clicks on the link, the link will update the Boolean field to be true. now my question is, in my def paper_frame(request,pk) (the code is below) how can i add it to the class BusinessDetailView(DetailView), so it stands as just one functionality. class BusinessDetailView(DetailView): model = Item template_name = 'business/detail_view.html' context_object_name='items' def paper_frame(request,pk): paper = Item.objects.get(pk=pk) paper.paper = True paper.save() return redirect("???")``` -
I cannot have “skip to” functionality inspite of adding controls to my django .html file video tag. How do I resolve that?
<video class="video" controls src="{{post.clip.url}}" type="video/mp4"></video> To get "skip to particular time", what do I need to do? -
i want to edit my restaurant data but i got this"The view company.views.edit_res didn't return an HttpResponse object. It returned None instead."
ValueError at /company/edit_res/1/ i got this error on " F:\restaurant\venv\lib\site-packages\django\core\handlers\base.py, line 307, in check_response" this location please guide me for successful edit this is my first learig project views.py def edit_res(request, id): if request.method == 'POST': pi = ResRegister.objects.get(pk=id) fm = CompRegisterForm(request.POST, instance=pi) if fm.is_valid(): fm.save() else: pi = User.objects.get(pk=id) fm = CompRegisterForm(instance=pi) return render(request, 'comp/edit.html', {'form': fm}) urls.py from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings app_name = 'company' urlpatterns = [ path('res_list/', views.res_list, name='res_list'), path('food_list/', views.food_list, name='food_list'), path('remove_res/<int:id>/', views.remove_res, name='remove_res'), path('remove_food/<int:id>/', views.remove_food, name='remove_food'), path('edit_res/<int:id>/', views.edit_res, name='edit_res'), path('edit_food/<int:pd>/', views.edit_food, name='edit_food'), path('add_food/', views.add_food, name='add_food'), path('cart_page/', views.cart_page, name='cart_page'), path('generate_invoice/', views.generate_invoice, name='generate_invoice'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) edit.html <!doctype html> {% extends 'Comp_base.html' %} {% block body %} {% load static %} <br><br> <div class="container"> <h1>Update Information</h1><br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="register" class="btn btn-primary btn-lg btn-block">Update</button><br> </form> </div> {% endblock %} -
Creating Text Editior in Django
I want to create a notes app in django and want a text editor which helps user to add bullets and bold text and more functionalities. How can i do this in the template in django? I am a newbie in django so please suggest me some ways to do that. -
python convert string to content of the string
What I get: names = """[{"lname": "HORJLAND", "fname": "Birger"}, {"lname": "LAMERS", "fname": "Edmund"}]""" What I want: names_list = [{"lname": "HORJLAND", "fname": "Birger"}, {"lname": "LAMERS", "fname": "Edmund"} How can I get names_list from names? I get the names variable from a django template and I want to parse it in a template tags by looping over it and get name['fname'] and name['lname'] like: for name in names: print(name['fname']) TypeError: string indices must be integers But since I get names and not names_list my loop is looping over each character of names! for name in names: print(name) [ { " l n a ... Quite stupid but I can't figure out how to do it... -
How Can I increase Django search performance?
I have 100 million contents in boards and show with paigination. But when a user search, query counts the number of contents having a keyword and make pagination. It's big query so I want to increase the performance. -
django rest framework social oauth2 with google
I am total noob to django and programming as whole, so excuse me, if the question seems silly to you, but the last couple of days I've been struggling with the task of implementing social authentication with django rest framework social oauth2 library. I followed this https://chrisbartos.com/articles/how-to-implement-oauth2-using-django-rest-framework/ tutorial for the local authentication and so far it is working. The unclear process for me is the social authentication itself. My questions are as follows: When I am building the application from the admin panel what should be the value of Authorization grant type? How should look like the Postman request, so I can receive the Authorization code for the particular user? Even though I've watched couple of videos about Oauth2 so I understand the idea behind the process, I can't figure it out for how to make it work for me. Any suggestion and guidance would be appreciated. Thank you. -
Django: how to annotate a comparison as an expression?
I have a model including these two fields in my models.py: class Dummy(models.Model): timestamp1 = models.DateTimeField() timestamp2 = models.DateTimeField() Now I want to list all values including the fact, if timestamp1 is greater than timestamp2. Instead of figuring that out in the template, I thought the right way would be to annotate this in the views.py. Unfortunately this does not work: from .models import Dummy dummy = Dummy.objects.annotate(is_newer=timestamp1 > timestamp2) I get the error: QuerySet.annotate() received non-expression(s): False. OK, annotate needs an expression, so I tried using When: from .models import Dummy from django.db.models import When dummy = Dummy.objects.annotate(is_newer=When(timestamp1__gt=timestamp2, then=True) This leads to the following error message: name 'timestamp2' is not defined Now I am out of ideas. What should I do? -
Convert the name of image file automatically when i use Python for loop in HTML(Django)
I'm Trying to make my own blog for practice Django. In index page, There are several images. and those image's name is 'image1.jpg. / 'image2.jpg' / 'image3.jpg' ....... I want to use for loop in html to show those images. This is my code and It does not working. (I use forloop.counter) Do you have some Ideas? Thanks (Sorry for my English...) {% for post in lastest_post %} {% if forloop.first %} <div class="col-md-12"> <div class="single-post-big"> <div class="big-image"> <img src="{% static 'img/post-image{{ forloop.counter }}.jpg' %}" alt=""> </div> <div class="big-text"> <h3><a href="{{ post.get_absoulte_url }}">{{ post.title }}</a></h3> <p> {% if post.is_content_more320 %} {{ post.get_content_320 }} {% else %} {{ post.content }} {% endif %} </p> <h4><span class="date">25 February 2017</span><span class="author">Category <span class="author-name"> {% for c in post.category.all %} {{ c }} {% if not forloop.last %} , {% endif %} {% endfor %} </span> </span> </h4> </div> </div> </div> {% else %} -
How to hide dropdown when another dropdown is clicked
I have two dropdown lists in same class: HTML <li class="menu"><a href="#" onclick="studentDrop()">Studenci</a></li> <div class="dropdown-content" id="subDrop"> test </div> <li class="menu"><a href="#" onclick="subjectDrop()">Przedmioty</a></li> <div class="dropdown-content" id="subjectcont"> {% for subject in subjects %} {{ subject.subject_name }} {% endfor %} </div> CSS .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; } .show { display: block; } Javascript function subjectDrop() { document.getElementById("subjectcont").classList.toggle("show"); window.onclick() } function studentDrop() { document.getElementById("subDrop").classList.toggle("show"); window.onclick() } window.onclick = function(event) { if (!event.target.matches('.column-left a')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } window.onclick hides all dropdowns when clicked outside. However, I can't figure out how to hide one dropdown when another is clicked. When I click one after another, two dropdowns are shown at once. -
The view company.views.edit_res didn't return an HttpResponse object. It returned None instead
ValueError at /company/edit_res/1/ see my code and help to resolve it views.py def edit_res(request, id): if request.method == 'POST': pi = ResRegister.objects.get(pk=id) fm = CompRegisterForm(request.POST, instance=pi) if fm.is_valid(): fm.save() else: pi = User.objects.get(pk=id) fm = CompRegisterForm(instance=pi) return render(request, 'comp/edit.html', {'form': fm}) <!doctype html> {% extends 'Comp_base.html' %} {% block body %} {% load static %} <div class="container"> <h1>Update Information</h1><br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="register" class="btn btn-primary btn-lg btn-block">Update</button> </form> </div> {% endblock %} what would i do now any suggestios? -
How do we add and save additional parameters to a serializer object in django rest framework?
These are the field in my PostSerializer fields = ('id','user_id','title','desc','comments') The user_id and comments are code generated and title,desc were obtained from api calls. I want to pass this as additional values to my request.data. This is my APIView object class PostView(APIView): permission_classes = (IsAuthenticated,) def post(self,request): request.data['user_id'] = request.user.id request.data['comments'] = "machine generated" post_serializer = PostSerializer(data=request.data) if post_serializer.is_valid(): post_serializer.save() print(request.data) return Response(post_serializer.data) While my print(request.data) shows user_id,comments fields and their corresponding values. In the saved database though the values for user_id and comments are null. How do we add and save additional parameters to a serializer object in django rest framework? -
while deploying my project using django i got this error
Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001DA81D1C620> Traceback (most recent call last): File "C:\Users\Anil\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__self.loader = MigrationLoader(self.connection) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__self.build_graph() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\migrations\loader.py", line 207, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations if self.has_table(): File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor return self._cursor() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 232, in _cursor self.ensure_connection() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 162, in get_new_connection conn = Database.connect(**conn_params) TypeError: argument 1 must be str, not WindowsPath forrtl: error (200): program aborting due to control-C event Image PC Routine Line Source libifcoremd.dll 00007FFBB0D094C4 Unknown Unknown Unknown KERNELBASE.dll 00007FFBF10E62A3 Unknown Unknown Unknown KERNEL32.DLL 00007FFBF3177C24 Unknown Unknown Unknown ntdll.dll 00007FFBF32CD4D1 Unknown Unknown Unknown Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Anil\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Anil\Anaconda3\lib\site-packages\django\core\management\__init__.py", … -
Django: Cannot render images in template
I am new to coding. I am not able to render the book-covers (uploaded in Django admin and stored in media/images) on my book_detail.html-page. Tried to add the below but then get this typeerror: MEDIA_ROOT = BASE_DIR('media') TypeError: 'PosixPath' object is not callable I think I have to add more to urls.py? Definitely, the img src-tag in {{ }} is wrong. Tried to comprehend and root cause but there are too many things wrong, I guess. :) I hope, someone can help. urls.py path('', BookListView.as_view(), name='book_list'), path('<int:pk>/', BookDetailView.as_view(), name='book_detail'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #added settings.py MEDIA_ROOT = BASE_DIR('media') MEDIA_URL = '/media/' STATIC_ROOT = BASE_DIR('staticfiles') STATIC_URL = '/static/' models.py class Book(models.Model): cover = models.ImageField(upload_to='images/', null=True) title = models.CharField(max_length=200, help_text='Capitalize first letters. No subheadlines.') author = models.ForeignKey(to=Author, on_delete=models.SET_NULL, null=True, related_name='books') book_detail.html {% block content %} <p> <img src="{{ photo.photo.url }}" alt="Image" width="300px"> <!-- <img src="{{ cover_image.url }}" alt="Image" width="250" height="250"> --> </p> <h1>{{ object.title }} {{ block.super }}</h1> <p class="lead"><em>by {{ object.author }}</em></p> # more code here {% endblock %} -
I cannot have "skip to" functionality inspite of adding controls to my django .html file video tag. How do I resolve that?
I get all other functionality except "skip to specific time" functionality -
'details referenced before assignment error'
I have two forms where one is used to enter the details of someone into the database and the other uses a unique value i.e the NationalId to get all the details that match the entered NationalId from the database if it exists. Below is my models file from django.db import models class EntryForm(models.Model): FirstName = models.CharField(max_length=120, blank=True, null= True) LastName = models.CharField(max_length=120, blank=True, null= True) NationalId = models.IntegerField() PlotName = models.CharField(max_length=120, blank=True, null= True) def __str__(self): return (f'{self.FirstName} - {self.NationalId}') This is my views file from django.shortcuts import render, redirect from .forms import ContactForm, RetrieveForm from .models import EntryForm # Create your views here. def Home(request): return render(request, 'store/home.html') def Contact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('contact') return render(request, 'store/contact.html', {'form':form}) def Details(request): form = RetrieveForm() if request.method == 'POST': form = RetrieveForm(request.POST) if form.is_valid(): Nid = form.cleaned_data['nationalId'] details = EntryForm.objects.get(NationalId=Nid) return redirect('home') context = {'form':form, 'details':details} return render(request, 'store/details.html', context) below is my form.py from django import forms from .models import EntryForm class ContactForm(forms.ModelForm): class Meta: model = EntryForm fields = '__all__' class RetrieveForm(forms.Form): nationalId = forms.IntegerField() it brings an error that 'details is referenced before assignment' what would … -
Media player creation in Open CV and integration with Django
Can we create a media player in an OpenCV with play, pause, or basic features of any media player and integrate with the web application, also I can select an object from a video. eg upload video to the web app, play pause video, and select objects from video. I have tried with Tkinter and Qt5 but it works only for desktop applications and I need to play frames in HTML video-tag -
Celery cannot get object from database
I use admin.ModelAdmin and i need to do some actions while saving an object. i need to use apply_async. I decided to override save_model. def save_model(self, request, obj, form, change): obj.save() result = some_actions.apply_async((obj.id,)) tasks.py @app.task def some_actions(obj_id): my_object = MyModel.objects.get(pk=obj_id) # some actions with my_object return some_obj_data It works correctly, but I need wait for the task to complete and get result. I have tried to use method get in save_model. some_obj_data = result.get() But then the error appears. my_app.models.MyModel.DoesNotExist: MyModel matching query does not exist. I looked in the database and there really is no new object. Why when I call .get() object is not saved? What i should do to get result apply_async? P.S. it is not necessary to overload save model. I can do the steps later if possible. The main thing is that 1) there is a ready-made object in the database, 2) actions were performed while the admin saves a new instance, 3) I can get result from apply_async. -
How to make ManyToMany field's value to show up in Django generic DeleteView
I have been trying to send model objects (as it is done for Django ListViews) in conjunction with Django generic DeleteView. Frankly I am not sure if I can do what I am trying to do. Given below is what I am using and to some extent it is working: Models class ApsProcesses(models.Model): aps_process = models.CharField(primary_key=True, max_length=1, ..) aps_process_text = models.CharField(max_length=35, verbose_name='Process Desc') class ProcessStatuses(models.Model): proc_status = models.CharField(primary_key=True, max_length=1, ...) proc_status_text = models.CharField(max_length=55, verbose_name='Short Desc') applicable_process_compo = models.ManyToManyField(ApsProcesses, related_name='proc_choices', ..) proc_status_weightage = models.PositiveSmallIntegerField(null=True, ..) Views class ProcStatusesDeleteView(DeleteView): template_name = .. model = ProcessStatuses context_object_name = 'proc_statuses' In my listview page I have the named url on the objects and on click it takes to the user to the delete page where I have the underlying data displayed (for the model instance selected by the user) and then two options are provided to the user - Confirm delete or Cancel and go back to the calling page. Here is what I am doing in the template: Template ... some codes truncated here <table> <tr> <th>Status Cd</th> <th>Status </th> <th>Process </th> <th>Weightage </th> </tr> <tr> <td style='color:red'> <strong>{{ proc_statuses }}</strong></td> <td>{{ proc_statuses.proc_status_text }}</td> <td>{{ proc_statuses.applicable_process_compo__aps_process }}</td> {# .aps_process_text #} {# << Tried … -
Getting 504 gateway timeout after configured for a timeout after 20 minutes
I have a django app which times out after 10 minutes. In the /etc/nginx/nginx.conf file, I added the following commands in the http object: proxy_connect_timeout 1200; proxy_send_timeout 1200; proxy_read_timeout 1200; which means it will time out after 20 minutes right? But still I am getting 504 Gateway Timeout after 10 minutes. Seems like this setup is not functioning. Is there anything else I need to do? Or am I not doing the right thing? -
Difference between reverse and reverse_lazy in django
I learned about this reverse_lazy function in django fairly recently, but I can't seem to understand the difference between the reverse and reverse_lazy function. For example, I have a CBV for deleting blog posts: class BlogDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home.html') What difference would it make if I just wrote reverse instead of reverse_lazy? I mean, both functions redirect us to a url. Then why do I need to use reverse_lazy in some places? -
Django not show image on the view
Here my view look : when i inspect element, it given image source are : 127.0.0.1:8000/store/arm-list/apple.jpg and : so here my code : urls.py : urlpatterns = [ path('arm-list/', VechileListView.as_view(), name='arm-list'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py : class VechileListView(ListView): model = Vechile template_name = 'store/arm_list.html' context_object_name = 'arm' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['vendor'] = Vendor.objects.all() return context settings.py STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'store/images') MEDIA_URL = '/media/' arm_list.html enter code here {% if arm %} {% for arm in arm %} <tr> <td class="serial">{{ forloop.counter }}</td> <td><img src="{{ arm.photo.url }}"></td> <td>{{ arm.alias }}</td> ..... ... {% endfor %} -
pass title of page into url
Using Django I am trying to pass the title of the current page into a dynamic URL but I keep getting errors, the title of the page is also produced dynamically from other views.py functions. urls.py path("wiki/edit/<str:title>", views.edit_page, name="edit") HTML file {% block title %} {{ title }} {% endblock %} {% block body %} <a class="page-link" href="{% url 'wiki:edit' page=title %}">edit page</a> {% endblock %} views.py def edit_page(request, page): page_request = page if request.method == "GET": return render(request, "encyclopedia/edit_page.html", { "form": form, "page": page_request })