Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Is it safer to user Integer PrimaryKey + Hashing or use secrets module without hashing
I am trying to create an application that requires some sensitive data. Now inside my database, I am using the python secrets module to create a safe 16-byte hex token for each object. However, by doing so I will not be able to hash it as it's not an integer anymore. So I was wondering if I use the secrets module will it be safe enough to expose the id's to the end-users? so for instance I have a field for one of my tables in my database such that: id = secrets.token_hex(16) which for instance would return id = cf125cf14d4ae9ed8972ee7512755e6d Or should I stick to the regular database primary keys which are auto-incremented integers and then use a hashing library to show the hashed value and then just decode those when I want to use them? -
ValueError at /create_entry/
Can someone help me to solve this error? ValueError at /create_entry/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000000B7BBF1BFC8>>": "Entry.entry_author" must be a "User" instance. urls.py from django.urls import path from .views import HomeView, EntryView, CreateEntryView urlpatterns = [ path('', HomeView.as_view(), name = 'blog-home'), path('entry/<int:pk>/', EntryView.as_view(), name = 'entry-detail'), path('create_entry/', CreateEntryView.as_view(success_url='/'), name = 'create_entry') ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Entry class HomeView(ListView): model = Entry template_name = 'entries/index.html' context_object_name = "blog_entries" class EntryView(DetailView): model = Entry template_name = 'entries/entry_detail.html' class CreateEntryView(CreateView): model = Entry template_name = 'entries/create_entry.html' fields = ['entry_title', 'entry_text'] def form_valid(self,form): form.instance.entry_author = self.request.user return super().form_valid(form) models.py from django.db import models from django.contrib.auth.models import User class Entry(models.Model): entry_title=models.CharField(max_length=50) entry_text=models.TextField() entry_date=models.DateTimeField(auto_now_add=True) entry_author=models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = "entries" def __str__(self): return f'{self.entry_title}' create_entry.html {% extends "entries/base.html" %} {% block content %} <div class="col-md-8"><br><br> <!-- Blog Post --> <div class="card mb-4"> <div class="card-header"> Create Blog Post </div> <div class="card-body"> <form class="form-conrol" action="" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Post Entry</button> </form> </div> </div> </div> {% endblock %} I need your help for this small project. -
Django-summernote 0.8.11.6 not working offline
When I connect to internet django-summernote work perfectly else showing empty area, like image. How can I make it work offline? -
Trouble passing foriegn key to form to filter for that key
So the problem I keep hitting is the filter inside lesson_select form that would find all the lessons associated with it's respective textbook so that it can be returned as a list for the user to choose from. I'm pretty confused because I got the filter for grade working, but the filter by textbook has me stumped :S Any tips would be greatly appreciated Views: def select_textbook(request): if request.method == 'POST': form = TextbookSelect(request, request.POST) print(request.POST) if form.is_valid(): textbook = form.cleaned_data.get('textbook') print(form.cleaned_data.get('textbook')) request.session['textbook'] = textbook.id print(request.session['textbook']) return redirect('select_lesson') else: form = TextbookSelect(request) return render(request, 'select_lesson/select_textbook.html', {'form': form}) def select_lesson(request): if request.method == 'POST': form = LessonSelect(request, request.POST) print(request.POST) if form.is_valid(): lesson = form.cleaned_data.get('lesson') request.session.get('lesson', lesson) request.session['lesson'] = lesson.id print(request.session['lesson']) return redirect('') else: form = TextbookSelect(request) return render(request, 'select_lesson/select_textbook.html', {'form': form})` models: class Textbook(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) grade = models.IntegerField() def __str__(self): return self.author +'-'+ self.title class TextbookLesson(models.Model): lesson_title = models.CharField(max_length=100) textbook = models.ForeignKey(Textbook, on_delete=models.CASCADE, related_name='textbook') vocabulary = models.JSONField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'user') def __str__(self): return self.lesson_title forms: class TextbookSelect(forms.Form): class Meta: model = Textbook fields = ['textbook'] def __init__(self,request,*args,**kwargs): super (TextbookSelect, self).__init__(*args,**kwargs) grade_chosen = request.session['grade_selected'] self.fields['textbook'] = forms.ModelChoiceField(queryset=Textbook.objects.filter(grade = grade_chosen)) class LessonSelect(forms.Form): class … -
how to get related objects from a many to many field
I am trying to get the objects from a many to many field. when the user selects their answer I want to be able to get the associated objects from the MtoM field.Then increment the related objects ansData + 1. ans in models was something else but i changed it for reasons, but that is what I am tryning to increment. 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 class QuizTaker(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return self.user 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 … -
Run a function when the browser is closed Django
Based from what I've read there is no way of learning if the browser or a tab is closed by the user through Django. Ideally I think there should be no problem in closing the browser or a tab because the user is automatically logged out. However, my problem is I have overridden my log-out view so Django does some functions (such as saving a time-stamp, and etc.) regarding the models relating to the logged in user. Django does not fire up these functions whenever the user logs out through closing the browser. It runs though when the user logs out normally through the "Log-Out" button. This is my overridden log-out view: def logout(request): reset_logged_acc(request) #do something auth_logout(request) #custom log-out return redirect('home') I've read somewhere that I can do some ajax requests and what not to know if the user is still there. I think its possible but I'm putting that option up as a last resort if nothing comes up. Are there any alternative ways to implement this? -
How to save data from API in Django?
I have Comment model relationship with User Like this Model class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) comment = models.CharField() type = models.CharField() point = models.CharField() Serializer class CommentSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ['comment', 'type', 'point'] From here I already get the API response, to save in the comment model def save_response_data(data): # here validate... json_data = {} # I want the user instance that is making the request Comment.objects.create(**json_data) return json_data I want the user instance that is making the request I tried to do it with signals but it doesn't work, any idea or comment, it would be helpful -
deploy to heroku: ProgrammingError: cannot cast type uuid to integer
I just attempted to deploy a new app to Heroku and I am running into an error I can't seem to figure out. Heroku or Django currently thinks I am trying to cast UUID to an Integer. I know the error is the result of bad logic inside my models but I don't know how to fix it. The answers to everything else I have seen tell the OP to just change Primary_Key = True. I cannot do this as I need my id to auto increment , which is currently the Primary Key. So for my id field I am using AutoField to increment automatically. I believe Django makes your id auto increment by default but I wrote it out anyways. If changing model structure is the only solution, then I guess I'll have no choice though. class Order(models.Model): STATUS = ( ('Pending-Approval', 'Pending-Approval'), ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('In-Progress', 'In-Progress'), ('Complete', 'Complete'), ) id = models.AutoField(primary_key=True) customer = models.ForeignKey(UserProfile, null=True, on_delete=models.SET_NULL) panel_type = models.ForeignKey(PanelType, null=True, on_delete=models.SET_NULL) description = models.CharField('Customer Description', max_length=264, null=True) date_created = models.DateTimeField('Date Created', auto_now_add=True, null=True) status = models.CharField('Job Status', max_length=200, null=True, choices=STATUS, default="Pending-Approval") address_st_one = models.CharField('Street 1', max_length=264, null=True) address_st_two = models.CharField('Street 2', max_length=264, null=True, blank=True) … -
How can i format a json field in Django admin?
I would like to implement a rewards system in my django project, where a user would have badges that would be displayed on their profile, and could be edited via the admin. To store these badges, instead of storing a dozen of bool field, i'm trying to use Json to store values as a list : ['badge1', 'reward'] member_badges = models.JSONField(default=list, blank=True, null=True) But how can i create an entry in the admin interface that would have a list of every award available to let you pick via checkboxes the awards you want for the user, and then append these to the list ? Thanks -
Celery and Pytest - create django tests
I have a function that calls a celery task. I need test it. I'm trying to mock, but without succcess. This functions calls celery task def example_function(): my_celery_task.delay(params) celery task @shared_task() def my_celery_task(params): ... My test @pytest.fixture def create_mock(mocker): return mocker.patch("my_correct_path.my_celery_task.delay") @pytest.mark.django_db def test_example(create_mock): create_mock.assert_called_once_with(params) ... ... assert 1 == 1 Running this I get this error: AssertionError: Expected 'delay' to be called once. Called 0 times. -
Django record that has many 'files' attached to it. How to do that in a form with the models
I am just not sure the name of what I am trying to do to google on my own (even though this is django and I had some experience in rails back in the day, it sounds like a partial form?) I am thinking what I need should be pretty simple and cut and dry..... I have a model to store information on an instrument. Then this instrument model can have many files associated with it (pdfs that are uploaded, pngs, zips etc). I can get the form created using crsipy forms and that easy enough... (attached is the form of the Technical_Entry model just has nothing attached for the files). I would love to have something that says like Files: On the form then has plus where clicking that uploads a file to that Technical_entry record, then after it is uploaded that file is available to be clicked on and downloaded again. Or a minus to remove the file from the entry.... I just am not sure how to connect that (essentially a secondary model) to the firs model/form? class Technical_Entry(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ema = models.ForeignKey(EMA, on_delete=models.CASCADE) system = models.ForeignKey('System', on_delete=models.CASCADE) sub_system = models.ForeignKey(SubSystem, on_delete=models.CASCADE) drawing_number = …