Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html <img> not loading image even tougth they're in tha same directory
my code is like that: <body> <a href = "{% url 'pacientes' %}"> <img src="/aaa.png"/> </a> </body> my question is: Why the fu***** image don't load if the image and the html are in the same directory obs.: i already tried write the img tag out of the 'a' tag, and tried too. this html is part of a django project, idk if this really make difference -
SAML authentication for HUE revoking admin access AFTER first login
I'm trying to set up SAML authentication for HUE deployed with AWS EMR, using Azure SSO as the IdP. I can actually get the handshake to work and the users are logging in to HUE, matching network login details to the usernames that are prepopulated in the HUE backend database. We create the users in HUE first and part of that setup includes setting some users with "is_superuser" to TRUE. The only attribute I explicitly look for to get from the IdP to HUE is the username/network-credential The behaviour I'm trying to understand is that the first person to log into the HUE UI is getting authenticated via SAML and logging in, with the admin/superuser privileges intact. But anyone after that logging in who is set up as an admin is losing the flag to indicate an admin, i.e. logged in as a normal user. If I manually go in afterward and set the users to have admin access in HUE database and have the users log in again, the access will be granted to the admin permissions and the problem seems to disappear but I don't understand why every login after the first is removing these permissions? I tried … -
How can I use instaceof in Django template?
Hello there I have a template that is used by two views in this template a have a toggle for deleting objects and because I have 2 types of objects that can be deleted by the same form I want to verify somehow the instance of the object in orderd to decide which url to use for deleting. How can I write this in django template properly? <form method="POST" action="{% if object instanceof Income %}{% url 'delete-income' object.id %}{% elif object instanceof Spending %}{% url 'delete-spending' object.id %}{% endif %}"> -
Django use values or values_list with non related models
I have this both models: class GeneCombination(models. gene = models.ForeignKey(Gene, db_column='gene', on_delete=models.DO_NOTHING, db_constraint=False) class Gene(models.Model): name = models.CharField(max_length=50, primary_key=True) type = models.CharField(max_length=25) I know it's not the best model schema, it has to be like that due to business rules. I'm getting the values from GeneCombination model and some fields from Gene model. Now, It could be that a gene is not present in Gene model, in that case that rows are being filtered when I use values of values_list methods, which is what I want to prevent. This query is returning 31 elements: GeneCombination.objects.select_related('gene') But this query is returning 27 elements (is filtering the 4 elements whose gene does not exist in Gene table): GeneCombination.objects.select_related('gene').values('gene__type') How could I get empty values in case that It doesn't exist and prevent the rows to be filtered? Thanks in advance and sorry about my English -
Django is unable to find the view used for query params the other views are working perfectly
#urls.py from django.urls import include,path from rest_framework import routers from . import views router=routers.DefaultRouter() router.register(r'banks',views.BanksViewSet) router.register(r'branches',views.BranchesViewSet) router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches') urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] #views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import BanksSerializer,BranchesSerializer from .models import Banks,Branches class BanksViewSet(viewsets.ModelViewSet): queryset=Banks.objects.all().order_by('id') serializer_class= BanksSerializer class BranchesViewSet(viewsets.ModelViewSet): queryset=Branches.objects.all().order_by('ifsc') serializer_class=BranchesSerializer class BranchAutocompleteViewSet(viewsets.ModelViewSet): serializer_class=BranchesSerializer def get_queryset(self): branchName=self.request.query_params.get("q") limit=self.request.query_params.get("limit") offset=self.request.query_params.get("offset") queryset=Branches.objects.filter(branch__startswith=branchName).order_by('ifsc')[offset:limit] return queryset the BanksViewSet and BranchesViewSet are working fine but the other one is not working the problem might be the basename in urls.py as changing it doesn't do anything even when left as an empty string. this is what the console has: Django version 3.1.5, using settings 'bankApi.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /branches/autocomplete/ [19/Jan/2021 18:30:04] "GET /branches/autocomplete/?q=A&limit=5&offset=0 HTTP/1.1" 404 12148 -
How to query a json date range on Django REST?
How to query a JSON Date Range on Django REST? I have a graph on my frontend UI, I have an option which date to display. (day/week/month/year) and fetch it from an API. How to do it? like if the user click "day", the API will be like. api/sample_data/current_day. or if "week" then api/sample_data/current_week. Thanks -
Django filter answers by questions
i have three tables with foreign key section, question and answer class Question(models.Model): questions = models.TextField() section = models.ForeignKey( Section, on_delete=models.CASCADE, related_name = 'section_question' ) objects = QuestionManagers() class Answer(models.Model): answers = models.CharField(max_length=140) answer_is = models.BooleanField(default=False) questions = models.ForeignKey( Question, on_delete=models.CASCADE, related_name = 'question_answer' ) I want to do a query that filters the answers to each question, and tried various ways, but couldn't. class QuestionManagers(models.Manager): def question_by_section(self,section): if section: return self.filter( section__slug=section.slug, ).values() def answer_by_question(self,section): if section: return self.filter( section__slug=section.slug, ).values( 'questions' ).values( 'question_answer__answers' ) with question_by_section you can filter the question but now I am missing the answers Could you help me please, thank you! -
Django/Wagtail ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'
I am using Django and Wagtail to create a site, which had been working well for some time. However, after some problems with anaconda, reinstalling etc, I now get this problem when I run python manage.py runserver: ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (C:\Users\Tomo_\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\__init__.py) I am not entirely sure what to do, as nothing has changed in my settings, and there isn't even a fields file, but rather a fields folder. It's like it's looking for an object in a folder. Entire trace: (base)>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in … -
How to solve NoReverse error showing in Detail View with Django?
I am trying to create a website in which there are cartoons displayed on the home page and when the we click on that cartoon, we get to see the seasons of the particular cartoon, now that is all working fine, but when I want the season to show it's details and episodes associated with when clicked it show me this error: NoReverseMatch at /cartoon/3 Reverse for 'episode_list' with arguments '('',)' not found. 1 pattern(s) tried: ['episode_list/(?P<pk>[0-9]+)$'] Here are my files : Urls.py from django.urls import path from .views import CartoonListView, CartoonSeasonView, SeasonDetailView urlpatterns = [ path('', CartoonListView.as_view(), name="home"), #the url that shows the list of cartoon seasons path('cartoon/<int:pk>' , CartoonSeasonView.as_view(), name="cartoon"), #the url that i want to show the season details as well as the episodes associated with the season path('episode_list/<int:pk>' , SeasonDetailView.as_view(), name="episode_list"), ] Models.py # Create your models here. from django.db import models # Create your models here. class Cartoon(models.Model): name = models.CharField(max_length=200) cover = models.ImageField() description = models.TextField() start_date = models.CharField(max_length=50) end_date = models.CharField(max_length=50) def __str__(self): return self.name class CartoonSeason(models.Model): cartoon = models.ForeignKey(Cartoon, null=True, on_delete=models.CASCADE) number = models.IntegerField() season_cover = models.ImageField(blank=True, null=False) season_name = models.CharField(max_length=200, blank=True, null=True) season_description = models.TextField(blank=True, null=False) def __str__(self): return self.cartoon.name + … -
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'MDShop.user' cannot be resolved
Can you help me please?I want to put additional information on the User but it does not work File "C:\django 5\Новая папка (14)\Musa\manage.py", line 22, in <module> main() File "C:\django 5\Новая папка (14)\Musa\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards schema_editor.create_model(model) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 322, in create_model sql, params = self.table_sql(model) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 159, in table_sql definition, extra_params = self.column_sql(model, field) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 212, in column_sql db_params = field.db_parameters(connection=self.connection) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1004, in db_parameters return {"type": self.db_type(connection), "check": self.db_check(connection)} File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1001, in db_type return self.target_field.rel_db_type(connection=connection) File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 897, in target_field return self.foreign_related_fields[0] File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", … -
Reuse Django Rest Framework Generic view to get its QuerySet
I have a Generic View of Django Rest Framework with a lot of settings (sorting, filtering, searching, etc): class MyViewClass(generics.ListAPIView): def get_queryset(self): return ... # IMPORTANT: this uses self.request def get_serializer_class(self): return ... # IMPORTANT: this uses self.request permission_classes = [permissions.IsAuthenticated] pagination_class = StandardResultsSetPagination filter_backends = [CustomOrdering, filters.SearchFilter] search_fields = ['field1', 'field2'] ordering_fields = ['field1', 'field2', 'field3', 'field4'] Now I want to make a file download from a QuerySet which must be computed with the same filters, sorting and searching parameters. Is there a way to reuse the QuerySet computed by that view? I don't need that to be paginated (however I think I could solve that problem from the frontend, so It doesn't worry me). I've tried calling get_queryset method with an ugly trick but It's not applying searching and ordering: @login_required() def download_result_with_filters(request): class MockRequest: request: HttpRequest mock_request = MockRequest() mock_request.request = request queryset = MyView.get_queryset(mock_request) ... Any kind of help would be really appreciated -
How to find out how many blog posts I have made?
How to find out how many blog posts I have made? i tried to do this in my view but I got "request is not defined" <div class="form-group"> <input class="form-control bg-white form-control-plaintext text-dark" type="number" placeholder="Number of Posts: {{ num_blogpost }}" readonly></input> </div> class BlogView(LoginRequiredMixin, DetailView): template_name = 'HomeFeed/formview.html' def get_context_data(self, **kwargs): context= super().get_context_data(**kwargs) user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() return context models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Djago template card alignement [Django 2.2]
I Need your help please. My envirenement is: python 3.6.6 django 2.2 I want to generate some code like this using django template. <div class="card-deck"> <div class="card"> actu1 </div> <div class="card"> actu2 </div> <div class="card"> actu3 </div> <div class="card"> actu4 </div> </div> <!--insert inside a new div (with class card-deck) the 5th actu and next one--> <div class="card-deck"> <div class="card"> actu5 </div> <div class="card"> actu6 </div> <div class="card"> actu7 </div> <div class="card"> actu8 </div> </div> <!--insert inside a new div (with class card-deck) the 9th actu and next one--> what I manage to do with django templates is as follows: {% extends 'actu/base_actu.html'%} {% load static %} {%block actumain%} <div class="card-deck"> {%for actu in actu%} <div class="card"> { {actu.content }} </div> {%endfor%} </div> {%endblock%} which just gives the code as follows: <div class="card-deck"> <div class="card"> actu1 </div> <div class="card"> actu2 </div> <div class="card"> actu3 </div> <div class="card"> actu4 </div> <div class="card"> actu5 </div> <div class="card"> actu7 </div> <div class="card"> actu8 </div> <div class="card"> actu9 </div> <div class="card"> actu10 </div> <div class="card"> actu11 </div> <div class="card"> actu... </div> </div> Please, could you give me your idea to be able to generate such a code. Thank you very much. -
I want to show patient_name in my dashboard view
I want to see the patient_name which is given by user. But when a user give his information i see the username in the Instead of place patient_name. How can i fix this problem. views.py : def home_view(request): appointment_patients = Appointment.objects.all() now = datetime.now() # current date and time hour = now.strftime("%H")# current hour hour = int(hour) context = { 'appointment_patients': appointment_patients, } return render(request, 'index.html', context) models.py: class Appointment(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient_name = models.CharField(max_length=25) address = models.CharField(max_length=100) phone = models.CharField(max_length=14, default="+880") symptoms = models.CharField(max_length=50, choices=departments, default='Cardiologist') symptoms_details = models.TextField() age = models.IntegerField() appointment_date = models.DateTimeField(auto_now_add=False, auto_now=False) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) time = models.CharField(max_length=20) is_appointment = models.BooleanField(default=False) is_delete = models.BooleanField(default=False) def __str__(self): return self.patient_name forms.py: class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = ('doctor', 'patient_name', 'address', 'phone', 'symptoms', 'symptoms_details', 'age', 'appointment_date', 'time') widgets = { 'doctor': forms.Select(attrs={'class': 'form-control'}), 'patient_name': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'symptoms': forms.Select(attrs={'class': 'form-control'}), 'symptoms_details': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'age': forms.TextInput(attrs={'class': 'form-control'}), 'appointment_date': forms.SelectDateWidget(attrs={'class': 'form-control'}), 'time': forms.TextInput(attrs={'class': 'form-control'}), } Here is my dashboard pic : -
Is it possible in Django to have 2 different types of users with theirs own login fields in the same app?
I have 2 types of users on my site, one is the store owner, I want to log him in with the usual custom user email and password, the other is the buyer, I want to login the buyer using just a pin number only. Is it possible to have both types of login users in the same django app. Thanks in advance. -
Making a web game in django?
Does anyone have advice on how to make a web game using Django? I have found one tutorials that combines Django channels and React, but it was outdated. -
axios put request doesn't work while performing an Update operation
While writing CRUD operations, I had troubles editing my data table, it doesn't update the database (I used axios, vuejs and vuetify in frontend and django rest framework in the backend): this is my frontend page (vuejs page) <v-container> <v-row> <v-col> <v-text-field v-model="editedItem.category_name" label="Nom Catégorie" ></v-text-field> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="blue darken-1" text @click="save" > Sauvegarder </v-btn> </v-card-actions> <script> import axios from 'axios'; export default { name: 'user-profile', data: () => ({ dialog: false, dialogDelete: false, headers: [ { text: 'category_id', value: 'category_id' }, { text: 'category_name', value: 'category_name'}, { text: 'Actions', value: 'actions'}, ], categories: [], editedIndex: -1, editedItem: { category_id: 0, category_name: '', }, defaultItem: { category_id: 0, category_name: '', }, }), save () { if (this.editedIndex > -1) { Object.assign(this.categories[this.editedIndex], this.editedItem) console.log('edited data'); axios.put('http://127.0.0.1:8000/api/categories/'+this.editedItem.category_id,{category_id:this.editedItem.category_id, category_name:this.editedItem.category_name}) .then(response=>{ console.log(response); }) </script> Here is my models.py file : from django.db import models # Create your models here. class Categories(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=250) -
Files not available in docker volume: only recover old files
I am a bit lost with my Django app configured with docker. Stack: Django/Celery/Celery-beat/Gunicorn/Nginx/Postgresql/Docker So I have an app with automatic Postgresql database backup using dbbackup (django app that make backup) app and Celery/Celery-beat (run command to make backup every hour for example). I can build and run my project but something is going wrong with my backup files. backup are done and store locally where expected. But in my web container, I can only see old backup that are not more locally in my app (but probably in persistent folders) so vene if I was able to remove this old files, problem will still be the same as new backup are not available in container I run docker-compose -f docker-compose-preprod.yml down -v to remove all volumes and rebuild container but doesn't change anything So locally I have - django-project - app - backup <- backup are made every hour and store in this bvackup folder - backup_2021-01-19-1600.psql - backup_2021-01-19-1700.psql - ... - manage.py - core But when I 'jump' into my web container with docker exec -it web sh - usr - src - app - backup - backup_2021-01-18-0800.psql <- different backup files - backup_2021-01-18-0900.psql <- different backup files … -
django app how to get a string from a function before
I am building a django app in which the user has to write a sentence in a text box. This sentence gets then sent to the server and received by it. After that the user has to click on continue and gets on a another html page. Here the user has to record an audio of a word he sais. The word is then turned into a string and after that sent to the server. Now I would like the function in views.py to find out if the word the user said is in the sentence the user wrote before. But the sentence is only in the first function that receives the sentence after it is sent. I know I could first store the sentence but is there also another way? -
Discord bot doesn´t connect
I have created this little sample code for a discord bot, but when i try to connect i get the following error. import discord import os from discord.ext import commands from dotenv import load_dotenv import urllib.request import json load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix='¿') # prefix del bot @bot.event async def on_ready(): await bot.change_presence(activity=discord.Streaming(name="Tutorial", url="http://www.twitch.tv/palmart69")) print('bot listo') @bot.command(pass_context=True) async def ping(ctx): await ctx.send("Pong!") @bot.command(name='suma') async def sumar(ctx, num1, num2): response = int(num1) + int(num2) await ctx.send(response) bot.run(TOKEN) --------ERROR------------------ Traceback (most recent call last): File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\aiohttp\connector.py", line 969, in _wrap_create_connection return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1081, in create_connection transport, protocol = await self._create_connection_transport( File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1111, in _create_connection_transport await waiter File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\sslproto.py", line 528, in data_received ssldata, appdata = self._sslpipe.feed_ssldata(data) File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\sslproto.py", line 188, in feed_ssldata self._sslobj.do_handshake() File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 944, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\main.py", line 31, in bot.run(TOKEN) File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 718, in run return future.result() File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 697, in runner await self.start(*args, **kwargs) File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 660, in start await self.login(*args, bot=bot) … -
Django UpdateView using formset and bootstrap fails
I'm new to django and I'm trying to write an application that given an activity allows me to save the information of the partecipants (i.e. Person) and how long the partecipation was. I was able to setup a CreateView, with bootstrap and JavaScript to allow my formset to be dynamic and I'm able to register the activity and the partecipants though the create view. However, when I try to modify an already existing activity, using an UpdateView, I get several errors. I tried to reproduce a minimal example of my problem and I got the error "This field is required" that is one of the error I obtain in my main application. I'm trying also to reproduce the second error: the instruction formset.is_valid() in views.py return False since it has an Activity already linked to the Person (violating the unique_together rule). This happens everytime: even if I'm just trying to add a second person to the form without changing anything about the first one. Please, let me know if I missed some files: here's the small example. models.py from django.db import models # Create your models here. class Person(models.Model): surname = models.CharField(max_length=30) class Activity(models.Model): name = models.CharField(max_length=30) person = models.ManyToManyField(Person, … -
Select a valid choice Django Filtered Drop Down Menu
Devs, In my project I have a form that has a field that has a student name selection, it is a drop down field by the students that are currently enrolled in that particular class. It gets this information from table Section Enrollment than checks the master Student table. The filtering works out correctly, however when I submit my form, it says the student name is not a valid choice. My guess is because its submitting that student name and not a ID, I'm not 100% sure. Here is my models and view. I don't know how to fix this. Appreciate that help. QUERY IN QUESTION: getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True) MODELS: # Creation of Classrooms and Assigned Teachers class SectionEnrollment(models.Model): sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "") section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,) studentpsid = models.ForeignKey(Student,on_delete = models.PROTECT, default = "" ,) entry_date = models.DateField(blank=True) exit_date = models.DateField(blank=True) dropped = models.BooleanField(default = False, blank = True) class Meta: verbose_name = "Student Section Enrollment" def __str__(self): return self.sectionenrollmentpsid # Where Basic Student Data Is Stored class Student(models.Model): studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True) student_name = … -
Display django form initial without brackets
I have a object from query object_query = werknemer_object_query = user.objects.filter(profile__werkgevers_id=werkgeversId) Created f string based on query result = [f"{item.first_name} {item.last_name}" for item in werknemer_object_query if item.pk == int(werknemer_get)] ---> this creates a list form initial with created f string form.initial = {"test": result} In html page when i call this field test its beeing displayed as ["result"] so with brackets. How can i get instead of ["result"] just result. -
DRF Serialize only selected keys of JSONField
I want to serialize specified key:value pair of JSONField in DRF but not the whole JSON. What I got from their website: Starting from Django Rest Framework 3.12, the JSONField of Django is supported. Nested search with JSONField started to be supported with double underscore notation as used in Django itself. You can read the exact statement from https://www.django-rest-framework.org/community/3.12-announcement/#support-for-jsonfield But I didn't find anything related to my problem. When I use double underscore notation for serialization (ex. details__link), I get error saying model doesn't contain that field. -
Django Register Page refill input data after site reload
Im looking for a solution to refill my select fields of a Register Page after a site reload, if the user has given invalid data and should correct the problem. The use of the Django Template works fine on the input field. There I can just give the value of the tag a django variable and when the variable is filled it gets displayed. But on the birthdate selections i have to use an if statement for every option that sets the select attribute selected="selected". And this for 31 days, 12 months and around 90 years. So there are 133 if statements and I think this is slowing down the backend unecesserily. I try to avoid java script and I have some safety concerns about window.sessionStorage so I would rather use my way with Django Templates. Do you know a more elegant solution for refilling a select field? the function: ``` def registerPage(request): context = {} #needed for the value rebuild when user has to reload the register page if request.method == 'POST': first_name = request.POST.get('fname') last_name = request.POST.get('lname') password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('user_email') birth_day = request.POST.get('bday') birth_month = request.POST.get('bmonth') birth_year = request.POST.get('byear') gender_type = request.POST.get('gender_type') …