Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 }) -
How to personalize serializer?
I have models movie and comment , how can I get the number of comments as a response to a get request class Movie(models.Model): Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank=True) class Comment(models.Model): comment_text = models.CharField(max_length=200) movie_id = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='Comments') How to personalize serializer to get answer as { 'movie_id':'1', comments:'4', }, { 'movie_id':'3', 'comments':'2', } how to write logic for serializators and put Information you want ?? -
Django, Python: cannot unpack non-iterable int object
I have tried to figure this out by looking at the same questions asked by others but I could not figure it out by looking at their questions. Is it something wrong with the vote views of is it something else. The problem is everytime I hit the vote/submit button I get this error can someonne explain the reason for this. views.py class QuizView(DetailView): model = Question template_name = 'Quizzes/quiz.html' class ResultsView(generic.DetailView): model = Question template_name = 'JSUMA/results.html' def vote(request, question_id): question = get_object_or_404(Question, question_id) try: selected_answer = question.answer_set.get(pk=request.POST['answer']) except (KeyError,Answer.DoesNotExist): return render(request, 'Quizzes/quiz.html', {'question':question, 'error_message' : "You didn't select an answer.",}) else: selected_answer.ans += 1 selected_answer.save() return HttpResponseRedirect(reverse('JSUMA:', args=(question.id))) models.py class User(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) #password = models.CharField(max_length=25) email = models.EmailField(max_length=100) class Quiz(models.Model): name = models.CharField(max_length=200,primary_key=True) NOQ = models.IntegerField(default=1) class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" def __str__(self): return self.name #number Of Questions class Major(models.Model): major = models.CharField(max_length=200) ans = models.IntegerField(default=0) answer = models.ManyToManyField('Answer') def __str__(self): return self.major class Question(models.Model): question_text = models.CharField(max_length=400) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE, null=True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text quiz.html <h1><h1>{{ question.question_text }}</h1></h1> {% if error_message %}<p><strong>{{ error_message … -
Django form is sent but doesent save to database
I´m doing a simple user-business application, where a user has one or many business. The problem is that my create business forms is not saving its data to the database. The user has all the permissions and is active, and I can save data from the create user form with no problem. What is wrong? View.js: class crear_negocio(LoginRequiredMixin, FormView): template_name = "tienda/crear_negocio.html" form_class= Negocio_Form success_url = reverse_lazy('tienda_app:crear_negocio') login_url = reverse_lazy('register_app:logIn') form.js: class Negocio_Form(forms.ModelForm): class Meta: model = Negocio_Model fields = ("Nombre_Negocio","Administrador","Descipcion_Negocio",'Correo_Negocio','Telefono_Negocio','Direccion_Negocio') Model.js: class Negocio_Model(models.Model): Nombre_Negocio = models.CharField(max_length=25) Administrador = models.ForeignKey(Usuario_Model, on_delete=models.CASCADE) Descipcion_Negocio = models.TextField(null=True, blank=True) Correo_Negocio = models.EmailField() Telefono_Negocio = models.CharField(max_length=13) Direccion_Negocio = models.CharField(max_length=25) def __str__(self): return self.Nombre_Negocio+' '+self.Correo_Negocio+' '+self.Telefono_Negocio+' '+self.Direccion_Negocio Database config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bdtg1', 'USER':'juan', 'PASSWORD':'juanjo123', 'HOST':'127.0.0.1', 'PORT':'3306' } } -
Django post primary key as slug? How do I reference the primary key in models.py?
When creating the slug for my post model, I want to use the object's primary key as the slug. However when I create a new post, instance.id is NoneType and not an integer like I'd imagine. Here is my model: class Post(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=False, blank=False) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title @receiver(post_delete, sender=Post) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_blog_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.id) pre_save.connect(pre_save_blog_post_receiver, sender=Post) As you can see in pre_save_blog_post_receiver, instance.id returns as None. How do I correctly reference the primary key in this situation? -
Django Import Export - is not importing fields from csv file
I am following a very simple tutorial from SimpleIsBetterThanComplex. on how to integrate Django Import Export and having issues with the csv data populating the database. Based on my tests it is just uploading the system generated ID and the rest of the fields are being uploaded as blanks. import.html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> views.py from tablib import Dataset def simple_upload(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()read().decode("utf-8")) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'core/simple_upload.html') {% endblock %} resources.py from import_export import resources from .models import Person class PersonResource(resources.ModelResource): class Meta: model = Person