Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sorting search result in django rest framework
I have written a search api for my website in django rest framework. when you search a name (e.g. "jumanji") there might be more than one result for the search for many reasons. what I want is for the result to be ordered by the "rating" field or "releaseDate" field of the Film model. here are my codes. # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) duration = models.PositiveIntegerField() typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),]) rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) # serializers.py class FilmSerializer(serializers.ModelSerializer): class Meta: model = Film fields = [ "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating", "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory", ] # views.py '''Override get_search_fields method of SearchFilter''' class DynamicSearch(filters.SearchFilter,): def get_search_fields(self,view, request): return request.GET.getlist('search_fields',[]) '''Override page_size_query_param attribute of PageNumberPagination''' class CustomizePagination(PageNumberPagination): page_size_query_param = 'limit' """Pagination Handler""" class PaginationHanlerMixin(object): @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator =None else : self._paginator = self.pagination_class() else : pass return self._paginator def paginate_queryset(self,queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self,data): if self.paginator is None: raise "Paginator is None" return self.paginator.get_paginated_response(data) class SearchFilm(APIView,PaginationHanlerMixin): authentication_classes = () permission_classes = (AllowAny,) def __init__(self,): APIView.__init__(self) self.search_class=DynamicSearch self.pagination_class=CustomizePagination def filter_queryset(self,queryset): … -
How to reuse an existing python Enum in Django for chocies?
Django has its own Enumeration types like model.TextChoices. However, if you already use traditional python Enum objects in your codebase, it would be nice to reuse them for fields definition without redefining all the values. Is there an elegant straightforward way to do this without too much boilerplate? What I tried: building a models.TextChoices class from the Enum seems impossible without manually declaring the values building the choices parameter from the Enum instead of dealing with models.TextChoices but then things like obj.field == ENUM.XXX won't work because Enums don't do value comparisons like models.TextChoices does among other things. Any elegant way to do this? form enum import Enum class YEAR_IN_SCHOOL(Enum): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' class MyModel(models.Model): year_in_school = django_model_field_choices_using_enum(YEAR_IN_SCHOOL) So that: Comparaison with the ENUM works my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN Saving using the Enum works my_model.year_in_school = YEAR_IN_SCHOOL.FRESHMAN my_model.save() -
I have changed library in django How do I upload it
I have created web app with django and I published it but when I developing the app, I changed django library but I can not import it or change it in amazon web services. I am new so what can I do? -
In django-forms, how can I make the values of 'name' column of foreign database visible in the selection choices
My Django site has a database model named Status with: class Status(models.Model): x = models.ForeignKey(Person, on_delete=models.SET_NULL, null = True) The Person database model referenced here contains attributes such as name, profile_pic etc. In forms.py, I have: class StatusForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StatusForm, self).__init__(*args, **kwargs) class Meta: model = Status fields = ['x'] Now, when running the site, I get: I want the name attribute of the Person to be shown in the choices instead of being shown Person object(1), Person object (2)..... How can I make that happen? -
APScheduler started twice on Django Heroku
I am using APScheduler (backgroundScheduler) to run a background job on Django deployed to Heroku. The job is supposed to run once every minute. I use a view endpoint to start the scheduler. /run is eventually called multiple times but should only start one scheduler. Locally, it works like a charm. However, when deployed to Heroku, calling /run multiple times will start another background scheduler. Interestingly, two schedulers are started, not more. I was thinking if this could be due to threading? Maybe /run is called on different threads. Any help is very much appreciated! views.py def run(request): if cgm_receiver.scheduler.running: logger.info('Background service was already running') else: logger.info('Background service was not running') logger.info("Starting background service") cgm_receiver.scheduler.add_job(cgm_receiver.timed_job, id='cgm_receiver', replace_existing=True, trigger='interval', minutes=1) cgm_receiver.scheduler.start() return render(request, "run.html") This is the output after calling /run first time at=info method=GET path="/run/" host=**** request_id=2bfe4eb3-47dc-41bc-afb9-2f1f20217d9f dyno=web.1 connect=0ms service=5327ms status=200 bytes=3330 protocol=https 2022-02-06 16:48:13,995 | INFO | cgm_importer.views : Background service was not running 2022-02-06 16:48:13,996 | INFO | cgm_importer.views : Starting background service 2022-02-06 16:48:14,001 | INFO | apscheduler.scheduler : Adding job tentatively -- it will be properly scheduled when the scheduler starts 2022-02-06 16:48:14,001 | INFO | apscheduler.scheduler : Added job "timed_job" to job store "default" 2022-02-06 … -
Can Python/Django function objects be executed with map function?
I have some Django model objects that are involved with a background celery task, at some point I have to run a check before creating new objects with these models. The check itself is tricky in that I have to run it multiple times within a single task invocation- my initial solution which I have to repeat multiple times so it includes the latest DB objects looks off so I came up with this instead: from itertools import chain foo = Foo.objects.get(pk=1) check = chain(foo.field.values_list, foo.attribute.values_list, foo.django.values_list) execute_check = map(lambda f: f('link', flat=True), check) print(list(execute_check)) # returns an empty list This solution didn't work out, it returned an empty list and I know for a fact it shouldn't be empty. In contrast with having to rewrite check multiple times so it includes the latest DB objects, I'd prefer writing it once and checking by execution if it matches my condition. Could you point me in the right direction? Thanks -
Can you combine Destroy with Create Django Rest Framework?
I've got a model for adding/subtracting points from an answer (answer and user is unique together meaning that only one person can upvote or downvote one answer), looks like this class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) Here's my viewset and serializer for creating an Api Endpoint for that class VoteSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Vote fields = '__all__' class VoteCreate(ParentKeyAPIView, generics.CreateAPIView): model = Vote parent_model_field = 'answer_id' serializer_class = VoteSerializer def perform_create_kwargs(self, **kwargs): return super().perform_create_kwargs(user=self.request.user, answer_id=self.kwargs['pk'], **kwargs) Now i also want to take into consideration the fact, that someone might click plus to an answer, but then decide to minus the answer. And i want create an endpoint to destroy that particular instance of Vote when that happens and then at the same time create a new one with the. opposite choice (add/subtract). Is there anyway to do that in Django Rest Framework? -
Dynamic 'Property' count on applicable foreign keys
I currently have the following three models in my app: Models.py class Guest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Invite(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event = models.ForeignKey(Event, on_delete=models.CASCADE) guest = models.ForeignKey(Guest, on_delete=models.CASCADE) On my index page for the Event model where I show a single event, I also show a list of all guests that could possibly be added to the event: guests = Guest.objects.filter(wedding = event.wedding).order_by("tag", "name") However, in the table, I would like to show next to each guest how many invites for this specific event they have been given. While I could do a property on the guest, its possible that multiple guests could be invited to multiple events. In an ideal world, I would define a property that accepts the event as a parameter so I could do something like this in the template: {% for guest in guests %} {{ guest.name }} ( {{ guest.total_invites(event.id) }} {% endfor %} -
How to use session timeout in django rest view?
I am implementing a view for a game using Django REST's APIView. I am very new to Django and have never done this before so I'm not sure how to implement this. The main idea is that a game only lasts 5 minutes. I am sending a resource to the user and creating a session object. This view. should be unavailable after 5 minutes. Is there such a thing as a view timeout? Will the session timeout then work for the post request as well or do I need to implement it there as well? This is my view: The out commented code at the end is what I was thinking of doing. Can I even do it in the view directly? How else can I do this and test it? views.py class GameView(APIView): """ API View that retrieves the game, retrieves an game round as well as a random resource per round allows users to post tags that are verified and saved accordingly to either the Tag or Tagging table """ def get(self, request, *args, **kwargs): current_score = 0 if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk random_resource = Resource.objects.all().order_by('?').first() resource_serializer = ResourceSerializer(random_resource) gameround = Gameround.objects.create(user_id=current_user_id, … -
ValueError: Cannot assign "": "Message.name" must be a "CustomUser" instance
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels. template where the data comes from: const chatSocket = new WebSocket( 'ws://' + window.location.host ) chatSocket.onmessage = function(e) { console.log(e); const data = JSON.parse(e.data) if(data.message) { document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + ': </b>' + data.message + '<br>') } else { alert('Empty!') } } chatSocket.onclose = function(e) { console.log('The socket closed unexpectedly'); } document.querySelector('#chat-message-submit').onclick = function(e) { const messageInputDom = document.querySelector('#chat-message-input') const message = messageInputDom.value chatSocket.send(JSON.stringify({ 'message': message, 'name': {{request.user}}, })) messageInputDom.value = '' } code used for saving into database in consumers.py def save_message(self, name, message): Message.objects.create(name=name, content=message) models.py from django.db import models from django.contrib.auth.models import AbstractUser from .managers import CustomUserManager # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=True, null=True) name = models.CharField(max_length=200, … -
Upload in Django
I was trying to understand how to upload files using Django, so I used the example (latest version, upload is working): https://github.com/axelpale/minimal-django-file-upload-example I have a few Questions now: How do I set a max file size? (I have checked the documentation of Django, but I don't get it) Is there a way for me to read the file before the user uploads it? (i.e a program that checks certain things and if they are ok, it can be uploaded) -
Django: Access related object attributes from a form field in a template?
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page. Here are extracts from my code... models.py from django.contrib.auth.models import User class Task(models.Model): category = models.CharField(max_length=300) description = models.CharField(max_length=300) class Activity(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) title = models.CharField(max_length=150) notes = models.TextField(blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The activity "owner" is linked to a User from the Django standard user model. views.py def manage_task(request, pk): task = Task.objects.get(pk = pk) TaskInlineFormSet = inlineformset_factory(Task, Activity, form = ActivityForm) if request.method == "POST": form = TaskForm(request.POST, instance = task) formset = TaskInlineFormSet(request.POST, instance = task) if form.has_changed() and form.is_valid(): form.save() if formset.has_changed() and formset.is_valid(): formset.save() return redirect('manage_task',pk=task.id) else: form = TaskForm(instance = task) formset = TaskInlineFormSet(instance = task) context = {'task': task, 'task_form': form, 'formset': formset} return render(request, 'tasks/manage_task.html', context) And manage_task.html excerpt: <h2>{{ task.category }}</h2> <form method="post"> {% csrf_token %} {{ task_form.description }} {% for form in formset %} {{ form.id }} {{ form.title }}</br> {{ form.notes }}</br> {% if user.id == form.owner.value %} You own this Activity!</br> {% else %} {{ form.owner.first_name }} owns this Activity</br> {% endif %} {% endfor %} <input class="save" type="submit" … -
Django - quiz app - issue with views and redirecting i guess
I'm trying to make an app by using django which allow me to study. for now I have already done it models.py from django.db import models from django.contrib.auth.models import User class Question(models.Model): question_text = models.CharField(max_length=200, null=True) answer_text = models.CharField(max_length=200, null=True) date_posted = models.DateTimeField(auto_now_add = True) def __str__(self): return self.question_text class Test(models.Model): name = models.CharField(max_length=200) questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) urls.py urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), ] urls.py urlpatterns = [ path('', include('exam.urls')), path('admin/', admin.site.urls), ] views.py def test(request, pk): print("Am I getting here?") test = Test.objects.get(id=pk) questions = test.questions.all() form = Answer() context = {'questions':questions, 'form':form} if request.method == 'POST': instance = Question.objects.get(id=pk) form = Answer(request.POST, instance=instance) if form.is_valid(): print("form is valid") if request.POST.get("answer").strip() == instance.answer_text: return HttpResponse('<h1>aaa</h1>') print("answer is correct") # used strip() to remove whitespace before and after the text. return redirect('home') return render(request, 'exam/test.html', context) forms.py from django import forms from django.forms import ModelForm from exam.models import Question class Answer(ModelForm): class Meta: model = Question fields = ['answer_text'] answer = forms.CharField(label='Your answer', max_length=100) html {% for question in questions %} <div class="question-container"> <p>{{question.question_text}}</p> <form method="POST"> <td>{{ form.answer }}</td> {% csrf_token %} <input type="hidden" name="question_id" … -
Get dict's value by key name in Django Tempaltes
in my view.py I have a function with field: context ={'user':user, 'user_gpds':user_gpds, 'team':team, 'team_gpds':team_gpds} which I return: return render(request, 'app/team_gpd_page/team_gpds.html', context) in my templates I have next code: {% for gpd in {{context|key:team_gpds}} %} <tr> <td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td> <td>{{gpd.employee}}</td> <td>{{gpd.gpd_year}}</td> <td>{{gpd.gpd_start}}</td> <td>{{gpd.gpd_end}}</td> <td>{{gpd.gpd_status}}</td> </tr> {% endfor %} But in result I have had an empty fields. I am also trying context.team_gpds and context.get('team_gpds'). What I am doing wrong? -
DjangoRestFramework: Nested relationships usage
For my current project I'm using Django and Django Rest Framework. I'm using Nested Relationships for all my views to get strictly what is needed to be displayed in them. However I'm starting to wonder if it is a good practice or not. Let's say I have a kanban view for a project application: I'd have a project With columns in it (stages) With tickets (tasks) in stages. This would lead to a 3 layer serialization (project with its stages with their tasks). I have the following questions : While it does work perfectly for a few tasks, how will it scale for a project with 10.000 and even more tasks ? Since it would load let's say : 1 project, 5 stages, 10K+ tasks ? Is a pagination possible with such nested relations ? If using such nested relations is not the good way. When is it okay to use them ? If using such nested relations is not the good way for a kanban view, how should I do it ? Should I query (from the frontend) first the project with stage_ids, then query those stages 1 by 1 with each their task_ids, and then reconstruct the whole … -
getting a django textfeild to run as code
I'm trying to get a project going and I'm using Django to do it. I have as one of my attributes in models start_lines = models.TextField(blank=True, null=True). These lines are to get code started with the exec() function. As one of them, I have from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]})) I have to run this through function to render what i want: def showProgramX(request, pk): program = Program.objects.get(id=pk) form = ProgramInputForm() keys = "" vars = [] for var in program.inputvariables.split(","): var_name, var_type = var.split("=") keys += f""" <tr> <th><label for="{var_name}">{var_name}:</label></th> <td><input type="text" name="{var_name}" maxlength="1000" class="input" id="id_inputvariables"></td> </tr>""" vars.append(var_name) content = {"program": program, "form": form, "keys": keys} if request.method == "POST": form1 = ProgramInputForm(request.POST) import json req = request.POST for var in vars: line = f"""{var} = {req[f'{var}']}""" exec(line, globals()) exec(program.start_lines, globals()) content["output"] = output content["extra_output"] = extra_output content['form'] = form1 return render(request, "programs/program.html", content) the output if i print program.start_lines should be in this case {str(Functions.objects.get(id=request.POST["function_to_call"]))} = all and {request.POST["inputExtras"]} is nothing/empty from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) output, extra_output = (ls.all()) where as I actually get from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) … -
Link transaction details with Product
I'm trying to link some models together to show what product a user is holding as well as the price they paid and the amount they hold. Which will be displayed within a table. I have Profile Product, Holding models, and want to add a Transaction model that is linked to the Profile, and Holding model to be able to add purchased amount and price. I'm not sure what the best way to link these models is to be able to easily present the data within a table. Models: class Product(models.Model): product_name = models.CharField(max_length=255, blank=False, unique=True) product_slug = models.CharField(max_length=50, blank=True,null=True) product_symbol = models.CharField(max_length=50, blank=True,null=True) product_price = models.FloatField(blank=True,null=True) product_capture_date = models.DateField(blank=True,null=True) product_logo_address = models.URLField(max_length=255, blank=True) def __str__(self): return str(self.product_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) products = models.ManyToManyField(Product, blank=True, through='Holding') website = models.URLField(max_length=50, blank=True) twitter = models.CharField(max_length=50, blank=True) meta = models.CharField(max_length=50, blank=True) github = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.user) class Holding(models.Model): product_name = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product_holding = models.FloatField(max_length=50, blank=True, null=True) def __str__(self): return str(self.product_name) class Transaction(models.Model): product = models.ForeignKey(Holding, on_delete=models.CASCADE) amount = models.FloatField(max_length=50, blank=True, null=True) price = models.FloatField(max_length=50, blank=True, null=True) transaction_date = models.DateField(null=True, blank=True) … -
No matching query Django Model
I want to add to number_of_points (from model Answer) a score (from model Vote) so whenever i save or add new vote i want it to either add +1 or +(-1). But i get this weird error saying that there is no matching query. Answer has to exist in order for vote to even create an instance. class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) @receiver(post_save, sender=Vote) def change_points(sender, created, instance, **kwargs): if created: answer = Answer.objects.get(answer=sender.answer) answer.number_of_points = F('number_of_points') + sender.score Traceback: Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1653, in … -
call custom function on django model after using values over filter
i have custom function on my model named represent to call this function over queryset i extended queryset and added another custom function named data class DataQuerySet(models.QuerySet): def data(self, name=None): return [obj.represent(name) for obj in super()._chain()] the issue is when i use values for annotate, query set chain contain dict instead of model, so dict object don't have represent function, for example when i using something like this App.objects.values('app').annotate(total_time=Sum("duration")).data() when i call above code return dict object don't have represent function. how can i call my custom model function after using values ? -
Is there any way that you can make JWT in your own custom view?
So I've been trying to learn about JWT and I've used both rest_framework_simplejwt and djoser, and in both of them they provide a view for creating JWT(logging in), and that makes me wonder if there's a way to create JWT in your own custom view? -
Django: add new column by function ( datetimefield to datefield )
Change datetimefield to datefield and put in in new column python ways are useless because i want to be able to use order_by and distinct i don't want to use sorted() and etc my django model is something like this class Product(models.Model): price = models.PositiveIntegerField(null=False, default=0) discounted_price = models.PositiveIntegerField(null=False, default=0) date = models.DateTimeField(auto_now_add=True) And i want to be able to call date() function and put it in another column and order_by it Product.objects.annotate(day=date.date()).order_by('-day').distinct('day') -
Django - quiz app - issue with forms i guess
I'm trying to make an app by using django which allow me to study. for now I have already done it models.py class Question(models.Model): question_text = models.CharField(max_length=200, null=True) answer_text = models.CharField(max_length=200, null=True) date_posted = models.DateTimeField(auto_now_add = True) def __str__(self): return self.question_text class Test(models.Model): name = models.CharField(max_length=200) questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) urls.py urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), ] views.py def test(request, pk): test = Test.objects.get(id=pk) questions = test.questions.all() form = Answer() context = {'questions':questions, 'form':form} if request.method == 'POST': instance = Question.objects.get(id=pk) form = Answer(request.POST, instance=instance) if form.is_valid(): if request.POST.get("answer").strip() == instance.answer: return redirect('home') return render(request, 'exam/test.html', context) forms.py class Answer(ModelForm): class Meta: model = Question fields = ['answer_text'] answer = forms.CharField(label='Your answer', max_length=100) and my html code: {% for question in questions %} <div class="question-container"> <p>{{question.question_text}}</p> <form method="POST"> <td>{{ form.answer }}</td> {% csrf_token %} <input type="hidden" name="question_id" value="{{ question.id }}" /> <td> <input type="submit" value="submit"> </td> </form> </div> {% endfor %} I haven't implemeted any point counter function. I wanted to be redirected to home page if answer is correct to see if the form works corectly but it is not. Where did i make mistake … -
How to connect a form?
I want to connect the form StockHistorySearchForm. At the same time, this must be done inside the ExpenseListView view. But no matter how I twisted it, for some reason the first form stops working for me. And search by date for some reason is not correctly implemented. Tell me how to connect it? enter image description here enter image description here -
I am facing '__init__(): incompatible constructor arguments.' error
I am trying object detection machine learning through Tensorflw; was following a video by Nicholas Renotte. A year old video and while running the trainning module to covert my xml and jpg file into record files I ran into this error. Tried alot of things and now stuck on what to do next. import os import glob import pandas as pd import io import xml.etree.ElementTree as ET import argparse os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1) import tensorflow.compat.v1 as tf from PIL import Image from object_detection.utils import dataset_util, label_map_util from collections import namedtuple # Initiate argument parser parser = argparse.ArgumentParser( description="Sample TensorFlow XML-to-TFRecord converter") parser.add_argument("-x", "--xml_dir", help="Path to the folder where the input .xml files are stored.", type=str) parser.add_argument("-l", "--labels_path", help="Path to the labels (.pbtxt) file.", type=str) parser.add_argument("-o", "--output_path", help="Path of output TFRecord (.record) file.", type=str) parser.add_argument("-i", "--image_dir", help="Path to the folder where the input image files are stored. " "Defaults to the same directory as XML_DIR.", type=str, default=None) parser.add_argument("-c", "--csv_path", help="Path of output .csv file. If none provided, then no file will be " "written.", type=str, default=None) args = parser.parse_args() if args.image_dir is None: args.image_dir = args.xml_dir label_map = label_map_util.load_labelmap(args.labels_path) label_map_dict = label_map_util.get_label_map_dict(label_map) def xml_to_csv(path): xml_list = [] … -
Testing Django model throws TypeError
I am trying to test my REST API and am currently testing my models. I am very new at Django and testing in particular. While testing my models I keep getting this error: TypeError: Field 'id' expected a number but got datetime.datetime(2022, ...) I get this error for every model and view so far. Why is this error occurring? How can I get my tests for this model to run? Am I even testing properly? This is one of my models: class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def __str__(self): """Return a human readable representation of the model instance.""" return self.name or '' @property def tags(self): tags = self.tagging.values('tag') return tags.values('tag_id', 'tag__name', 'tag__language') And this is the corresponding test suite for this model: class TagTests(TestCase): def setUp(self): self.tag_name = "name of the tag" self.tag_language = "language of tag" self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language) def test_name_label(self): tag = Tag.objects.get(id=1) field_label = tag._meta.get_field('name').verbose_name() self.assertEqual(field_label, 'name') def test_tag_size(self): tag = Tag.objects.get(id=1) max_length = tag._meta.get_field('name').max_length self.assertEqual(max_length, 256) def test_str(self): """Test for string representation""" tag = Tag().objects.get(id=1) self.assertEqual(str(tag), tag.name) def test_model_can_create_tag(self): """Test the tagging model can create a tag instance""" old_count = Tag.objects.count() self.tag.save() new_count = Tag.objects.count() self.assertNotEqual(old_count, new_count)