Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how get the average time of a person that answered
I would like to get the Average time of answers of each person. Model: class Person(models.Model): uid = models.UUIDField(default=uuid.uuid4, primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = CIEmailField() class CoursePerson(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) course = models.ForeignKey( Course, related_name="courses_persons", on_delete=models.CASCADE ) person = models.ForeignKey( "Person", related_name="courses", on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) start_at = models.DateTimeField() class CoursePersonPasswordFormSubmission(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) text_mask = models.CharField(max_length=255) text_length = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) course_person = models.ForeignKey( CoursePerson, related_name="password_submissions", on_delete=models.CASCADE ) I've started to write the the def_queryset function. Everything on the beginning is ok since I have to filter stuff before do that logic: def get_queryset(self): accounts = get_account_ids(self.request) course_person_queryset = CoursePerson.objects.filter( account__in=accounts, is_in_analytics=True, status__gte=CoursePerson.StatusChoices.OPEN, course__type="form" ) course_person_queryset = filter_base_analytics( self.request, course_person_queryset, date_start=self.request.GET["date_start"], date_end=self.request.GET["date_end"], ) ...I'm blocked here... But now, I have to render a list of person with their Average of delay of response. Means, the initial message time sent to the user is course_person__start_at and the answer time of the person is password_submissions__created_at what I've tried: person_queryset = models.Person.objects.filter( courses__in=course_person_queryset.values_list('uid', flat=True), courses__password_submissions__created_at__isnull=False, courses__emails_person__opened_at__isnull=False, ).annotate( first_password=Subquery( CoursePersonPasswordFormSubmission.objects.filter( course_person_id=OuterRef("uid") ) .order_by("created_at") .values("uid")[:1] ), ) But this can't work as a person can have multiple course_person. and these course_person can have multiple … -
Visual Studio Code Automatically adds useless code
enter code hereI recently switched to VSC, installed python, pylance plugins. Everything seemed to be working fine, but when I started working with django, vsc started automatically when selecting an option in views.py CBV including Optional: str etc, for example context_object_name: Optional[str] Here I click Enter And then it automatically adds I don't want to remove hints in the code and automatic addition, but I also don't want him to add unnecessary -
Django Authentication Login From Active directory
How can I authenticate and login the user from Active Directory? This is my code Authenticate.py: from .models import User from ldap3 import ALL, Server, Connection, NTLM from ldap3.core.exceptions import LDAPException from django.contrib.auth.backends import ModelBackend def validate_user_credentials(username, password): server = Server(host='@xxxDomain', use_ssl=False, get_info=ALL) try: with Connection( server, authentication="NTLM", user=f"{''}\\{username}", password=password, raise_exceptions=False, ) as connection: print(connection.result['description']) return True except LDAPException as e: print(e) return False class UserAuth(ModelBackend): def authenticate(self,request,username=None,password=None,**kwargs): try: if (validate_user_credentials(username, password)): print("Helloooooooooooooo") user = User.objects.get(username=username) print(user) return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(username=user_id) except User.DoesNotExist: return None views.py: class UserLoginView(View): form_class = UserLoginForm def get(self, request): form = self.form_class return render(request, 'login/login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data userexistindb = User.objects.filter( username=cd['username'], is_user_local=False).exists() username = cd['username'] password = cd['password'] try: if userexistindb: try: user = authenticate( request, username=username, password=password) if (user is not None): login(request=request, user=user) messages.success( request, 'Loged in success', 'success') return redirect('login:result') else: messages.error(request, 'us', 'warning') except User.DoesNotExist: messages.error( request, 'Invalid User/Password', 'warning') except User.DoesNotExist: username = None messages.error( request, 'Invalid User/Password', 'warning') return render(request, 'login/login.html', {'form': form}) The result is the sessionid It is created,The username and password are correct and the … -
Migrations Error in Django: AttributeError: 'str' object has no attribute '_meta'
I know this has been asked before. But, I tried the available solutions. Those don't seem to work in my case unless I missed something unintentionally. I dropped all the tables/relations from the connected database and deleted all the previous migration files except the init.py. And then ran the makemigrations command which worked fine. But got this error after running migrate. Here is the error: Applying book.0001_initial... OK Applying reader.0001_initial...Traceback (most recent call last): File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 22, in <module> main() File "/home/brainiac77/github/bookworms_backend/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply operation.database_forwards( File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 93, in database_forwards schema_editor.create_model(model) File "/home/brainiac77/Installations/anaconda3/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 440, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' reader.0001_initial.py # Generated by … -
is there any python or django package that contains all address?
A few years ago I was working with a package for addresses, that package includes region, countries, states, cities, areas, sub areas...etc. It contains great data and all data connected together, but unfortunately I forgot it and what it's name. Now I spent a lot of hours to find it or any other library that contains the same info, but no results. anyone can help me by suggest a library, not apis no google maps. many thanks in advance. -
How to use AND in Django?
This is in my views.py win = Bid.objects.filter(auction__closed=True) f = Bid.objects.get(user=request.user) I want to do this foo = Bid.objects.filter(auction__closed=TRUE AND user=request.user) How to achieve this in django? -
Gunicorn Django response statusText missing
I have a Django DRF/React setup using React and JWT for authorisation. On local runserver, I send the request for token, I recieve access and refresh tokens. When the access token expires, I have an Axios interceptor set which checks the error response and sends new response with refresh token. All passes and works fine. if ( error.response.data.errors[0].code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized" ) { I noticed on server (Gunicorn), that the process all works fine, access token received and works as expected until expiry, but the refresh token request doesn't even send. Then after some debugging I noticed the gunicorn server sends the same response but without statusText. I am only assuming it is something to do with Gunicorn as that is the only difference than running code on runserver locally. On image, Left side is local response. Right side is server response. Any reason I would not receive the statusText? Any setting I need to be aware of? -
How to get a specific id for my task in Django?
I have a django app in which I log in as an admin and add a tasks for a specific employee. Then I log in as the employee and I have to end the task when it's done. I display my active tasks in an table in a html template and I want to make the ended task is_active = 0 to check that the task is done. I also want to store the date when the task was done in closed_at. My models.py: class Employee(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) objects = models.Manager() address=models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now_add = True) active_tasks = models.IntegerField(default = 0) completed_tasks = models.IntegerField(default = 0) daily_r = models.IntegerField(default = 0) weekly_r = models.IntegerField(default = 0) monthly_r = models.IntegerField(default = 0) annual_r = models.IntegerField(default = 0) class Tasks(models.Model): id = models.AutoField(primary_key=True) employee_id = models.ForeignKey(Employee,blank=True,null=True,on_delete=models.CASCADE) is_active = models.IntegerField(default = 1) headline = models.CharField(max_length = 100) body = models.TextField() created_at = models.DateTimeField(auto_now_add = True) assigned_at =models.DateTimeField(auto_now_add = True) closed_at = models.DateTimeField(auto_now_add = True) My views.py def viewActiveTasks(request): current_user = request.user current_user_id = current_user.id employees = Employee.objects.filter(user_id = current_user_id) user_employees = User.objects.filter(is_employee=1) tasks = Tasks.objects.filter() return render(request, "employees_active_tasks.html", {'employees':employees,'user_employees':user_employees,'tasks':tasks}) def endTask(request): employee=Employee.objects.get(user_id=request.user) … -
Django bulk update/replace substring keeping the previous value
I have a model with two fields: field_a and field_b field_a field_b JPY 6 blabla JPY 677 blabla I would like to replace / update the contents of field_a but keeping the old values (numbers) and just changing the currency. For instance, this would be a desired result: field_a field_b USD 6 blabla USD 677 blabla What I've found/tried after some research: currency = 'USD' ExampleModel.objects.update( field_a=Replace('field_a', Value('old_text?'), Value(currency + old_text_digits?)) ) The problem is, I don't know how can I access the old_text for each line in the table and I don't know how to manipulate the new text to include the currency + previous numbers. Any help would be appreciated -
How to send an email through Sendgrid, as a reply to some email I received through Sendgrid inbound parse using Django?
So I am sending my email using sendgrid personalization something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]} } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Here context["personalization"] is an object as below: { "to": [{"email": applicant.email}], "custom_args": { "email_id": str(correspondance.id), "env": settings.ENVIRONMENT } } Sending and receiving the emails work fine. The problem is that I can't send an email as a reply to some email. Like a user sends me an email which I receive through sendgrid's inbound parse. Now I want to reply to the email I received. A solution I found on the internet was that I have to add an 'in_reply_to' ID which I receive as Message_ID in inbound parse but that didn't work. I did something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]}, "in_reply_to": message_id } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Here the message_id is Message_ID I received in the inbound email's json. -
Should I use stored procedure on Django
My boss wants me to use his stored procedure on my django project. But his sp is kinda simple and I can probably create it using django's queryset API his sp involves inserting items to a item_table then insert also into transaction_logs_table. his reasoning So it can be reuse we have mvc programmer who still uses sp on his code his planning on developing on mobile My Question is should I use sp on django? or when should I use it -
Django post form fields to another page
I have a Django form that takes filter options for a report. The report page is a separate view that renders the report based on the form data. My first pass at this, I simply set the action of the form to the report page and method to GET. The form data was then passed directly the report view via the querystring which I would use GET to retrieve. The problem with this was that this bypassed form validation since the the form did not post back to its own view. My next pass, I removed the form action (so it would post back to itself) and used form_valid (I am using class based views) to encode the form data and redirect to the report view like so: ReportOptionsView(FormView) form_class = OptionsForm template_name = 'my_report_options.html' report = reverse_lazy('my_report') def form_valid(self, form): qstr = urlencode(form.cleaned_data) return redirect(self.report+"?"+qstr) The report page works the same -I just retrieve the information from the querystring to filter the models and display the report. I would prefer the form data not appear on the querystring of the report page. When I tried to redirect to the report page using a POST method is where I starting … -
Djongo+Mongo add expiration (auto-delete) to model objects
Is there a simple way in Django to add an expiration date to documents via the model meta? For example, in pymongo you can do something like this: mongo_col.ensure_index("date", expireAfterSeconds=3*60) -
How to annotate related objects with filter?
class Item(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User) class Document(models.Model): doc_type = models.CharField(max_length=10, default="DOC") item = models.ForeignKey(Item, related_name="docs") uploaded_at = models.DateTimeField(auto_now_add=True) @api_view(["GET"]) def get_items(request): # docs__uploaded_at should be from objects having doc_type="DOC" only items = Item.objects.prefetch_related("docs").filter(user=request.user).annotate(date=Max("docs__uploaded_at").order_by("-date") Here I want to order items queryset based on document uploaded_at field. An Item can have multiple or None documents as well so order the items based on last document date with DOC as doc_type and if it has none then keep it at the last. NOTE: I am using django 1.9 -
In PDF generation which font family is suitable for multi language support?
Currently we use xhtmpdf that use UTF8. that not supporting some character -
Django TestCase check ValidationError with assertRaises in is throwing ValidationError
I have a model where i have overridden save function something like: class MyModel(models.Model): number = models.PositiveIngeter() def save(self,*args, **kwargs) if self.number > 10: super().save(*args, **kwargs) else: raise ValidationError('msg') and the function i am testing is like def test_number(self): myModel = MyModel(number=5) self.asserRaises(ValidationError,myModel.save()) the error i got is like this: ERROR: test_number(apps.players.tests.test_models.CityDetailTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/sagar/project/apps/players/tests/test_models.py", line 738, in test_city_detail_when_tier_is_not_allowed myModel.save() File "/home/sagar/.pyenv/versions/3.5.9/lib/python3.5/contextlib.py", line 30, in inner return func(*args, **kwds) File "/home/sagar/project/apps/players/models.py", line 2452, in save raise ValidationError("msg") rest_framework.exceptions.ValidationError: ['msg'] I'm new to Django and unable to figure out what's wrong with this -
Run migrations on Dockerfile deploying on Elastic Beanstalk
I have a problems making migrations (Django App 4.0.6) on Elastic beanstalk. This is my Dockerfile: FROM python:3.8 ENV PROJECT_DIR=/usr/src/app/ ENV PYTHONIOENCODING=utf-8 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 ENV PIPENV_USE_SYSTEM=1 WORKDIR ${PROJECT_DIR} COPY . ./ RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Until here, all works well, but if I try to add RUN python manage.py migrate before to EXPOSE 8000 and make the deploy, I have an 504 error. I tried to add .ebextensions and config file like this: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true But I don't sure how to activate my env in a Docker, I have an error when I try to make the deploy 2022-08-01 03:10:23,328 P28507 [INFO] Command 01_migrate 2022-08-01 03:10:23,331 P28507 [INFO] -----------------------Command Output----------------------- 2022-08-01 03:10:23,331 P28507 [INFO] /bin/sh: /var/app/venv/*/bin/activate: No such file or directory 2022-08-01 03:10:23,331 P28507 [INFO] ------------------------------------------------------------ 2022-08-01 03:10:23,331 P28507 [ERROR] Exited with error code 1 ¿What is the best solution for my case? Thanks for your help! :) -
Designing Django admin panel by tailwind
I hope you are fine. I want to customize my django admin panel by tailwind. I know how to use tailwind in the templates of my django apps but unfortunately I am not able to use tailwind in the admin template and I have also tried multiple ways to solve this such as putting cdn in the admin base.hml or installing django-tailwind but all of them hasn’t worked for me yet. I will thank if anyone who has experience about this matter give me a piece of guidance. -
How to only perform action once instance created
my code: def save(self, *args, **kwargs): <My_CODE> if <having_register>: <send_email_to_admin> but this function will work when I run an update instance ( The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update ) so if I just want to send an email to admin only once having a new registration? Any way to check the request method or prevent force_insert in this case? -
exclude field from a nested serializer
to get the information of a user I use a serializer with nested serializers but I have a problem which is that I do not know how to exclude certain fields that are not necessary in this case the user's password, is there any way to exclude that field? here is the code of the endpoint and the serializers endpoint @api_view(['GET']) @has_permission_decorator('view_team_member') def getTeamMembers(request, pk): try: token = decodeJWT(request) team_member = TeamMember.objects.filter(pk=pk, company_id=token['company_id']) print(team_member) serializer = TeamMemberSerializer(team_member, many=True) return Response({'data': serializer.data}, status=status.HTTP_200_OK) except TeamMember.DoesNotExist: return Response({'Error': 'Not Found'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) team member serializer class TeamMemberSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) team = TeamSerializer(read_only=True) team_role = TeamRoleSerializer(read_only=True) company = CompanySerializer(read_only=True) class Meta: model = TeamMember fields = "__all__" read_only_fields = ['state', 'created_at', 'updated_at'] required_fields = ['team', 'user', 'team_role'] user serializer class UserSerializer(serializers.ModelSerializer): role = serializers.CharField(style={'input_type': 'text'}, write_only=True) password2 = serializers.CharField(style={'input_type': 'text'}, write_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password', 'password2', 'company', 'role'] extra_kwargs = { 'username': {'required': True}, 'email': {'required': True}, 'first_name': {'required': True}, 'last_name': {'required': True}, 'role': {'required': True}, 'company': {'required': True}, 'password': {'required': True}, 'password2': {'required': True}, } def save(self): password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: … -
Why do uploaded images in my Django project have larger file sizes than the source images? And how do I compress them?
I am working on a project that receives in Django a user uploaded image from Javascript via fetch API. The user uploads images for each tile in a custom grid. I have managed to get my app working, but I noticed that the uploaded tile images (all 1:1 ratio) have a much larger filesize than the ones that are actually uploaded. Why is this? I am using cropper.js to crop and save the files on my frontend. I wonder if that could affect the filesize in this way? Also, how do I compress the images before they are saved to save storage space? I have tried overriding the Pillow save method as mentioned in other posts, but could not get it to work. Here is some of my code: A paired-down version of the view that receives and saves the tile image: def add_image(request, tile_id): # Query for requested tile try: tile = Tile.objects.get(pk=tile_id) except Tile.DoesNotExist: return JsonResponse({"error": "Tile not found."}, status=404) if request.method == "POST": image = request.FILES.get("image") if image is not None: print(f"Image received: {image}") # Add image to tile tile.image = image tile.save() tiles = Tile.objects.select_related("grid").filter(grid=grid).all() return JsonResponse({ "tiles": [tile.serialize() for tile in tiles], }, safe=False) else: … -
Organize CSS and margin placement spaces between text in HTML
i am new to html. I'm trying to create a page that look exactly like what I design in XD, which looks like this But Currently my progress is up until like this, i created this using the language html & it is a django project. The problem I'm having right now is that the margin and the placement of the elements are not match and i found it is difficult to align them accordingly. I need help and suggestion to make the spacing looks more neat, text-alignment and the css thingy. The code is implement in Django/HTML. {% load static %} <html lang="en"> <head> <!-- Character Encoding and Viewport Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Website Title --> <title> 404 - Page Not Found </title> <!-- Fonts --> <link href="http://fonts.cdnfonts.com/css/lemonmilk" rel="stylesheet"> <script> document.getElementsByTagName("html")[0].className += " js"; </script> <!-- Website Favicon/Icon --> <link rel="icon" href="{% static 'landing/images/logo/favicon-96x96.png' %}"> {% block head %} {% endblock %} <style> @import url('http://fonts.cdnfonts.com/css/lemonmilk'); body { color: #666; text-align: center; font-family: "Segoe UI", sans-serif; margin: auto; } .status-error-code { text-align: center; font-size: 232px; color: #5AC69D; font-family: 'Lemon/Milk', sans-serif; } .content-first-message{ margin: auto; text-align: center; font-size: 60px; font-weight: 400; } .content-middle-message{ margin: … -
django cannot assign must be an instance
I'm trying to insert an item. but it's throwing `Cannot assign "'2003-221'": "ClearanceItem.recorded_by" must be a "ClearanceCustomuser" instance.` models.py class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.ForeignKey('ClearanceCustomuser', models.DO_NOTHING, db_column='recorded_by', blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class ClearanceCustomuser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() userid = models.CharField(primary_key=True, max_length=9) email = models.CharField(unique=True, max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'clearance_customuser' views.py class Add(LoginRequiredMixin, CreateView): form_class = CreateForm model = ClearanceItem template_name = 'clearance/add.html' def form_valid(self, form): instance = form.save(commit=False) instance.recorded_by = self.request.user.userid instance.save() return HttpResponseRedirect(self.get_success_url()) search few related question Cannot assign must be a instance. Django and someone answer that Scripter.title is a foreign key to Book, so you must give it an actual Book, not a string. I believe I am giving my clearanceitem an actual user which is userid = 2003-221. I dont understand … -
Unable to specify foreign key in managed model to non-managed model (Django 3.2.7 / Postgresql 10.18)
I am implementing a "profile model" in Django 3 that at its simplest is a two field model: a one-to-one relationship field to the default Django User model and a foreign key relationship to an unmanaged model TeamDim that is populated and managed by an ETL job outside the Django app. I'm using Postgresql 10 as the DB backend. I had no trouble creating the initial table with the one-to-one field and placeholder teamname CharField, but adding the ForeignKey field causes the migration to fail with the following error: django.db.utils.ProgrammingError: column "index" referenced in foreign key constraint does not exist The primary key in TeamDim is team_id and is appropriately specified in the model definition, so I'm not sure where the reference to column index is coming from in the foreign key constraint the migrator is attempting to apply. Other non-managed models in my app have no trouble referencing TeamDim via foreign keys with the same declaration, so I'm not sure why it's failing in the managed case. Adding kwargs db_index=False or to_field='team_id' to the ForeignKey declaration don't remedy the issue. Below are the two relevant models - TeamDim and CefhUser from django.db import models from django.contrib.auth.models import User # … -
How do I make a Django form that display's model objects to chose from
Ok, I am building a hotel application and in the booking section of the various hotels, I want there to be a dropdown in the booking section and that dropdown would contain the number of rooms the hotel has so a user can book a specific room. Now each hotel has different number of rooms, so I want it to be that, based on the number of rooms the hotel has, that number would be the number of rooms in the drop down. here is my code... registration 'models.py' class Hotel(models.Model): name = models.CharField(max_length=120, null=True) hotel_location = models.CharField(max_length=3000, null=True) number_of_rooms = models.IntegerField(null=True) number_of_booked_rooms = models.IntegerField(null=True, default=0) and here is the booking 'models.py' class RoomBooking(TrackingModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) room_number = models.ForeignKey('Room', on_delete=models.CASCADE) class Room(TrackingModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) room_information = models.ForeignKey(RoomBooking, on_delete=models.CASCADE) room_number = models.IntegerField() here is my 'views.py' def book_a_room(request, *args, **kwargs): hotel_slug = kwargs['slug'] hotel = Hotel.objects.get(slug=hotel_slug) form = BookingARoomForm() if request.method == 'POST': form = BookingARoomForm(request.POST) if form.is_valid(): if hotel.number_of_booked_rooms < hotel.number_of_rooms: hotel.no_rooms_available = False if hotel.no_rooms_available == False: hotel.number_of_booked_rooms += 1 hotel.save() room_booking = RoomBooking.objects.create(hotel=hotel, guest=request.user, **form.cleaned_data) Room.objects.create(hotel=hotel, room_information=room_booking, is_booked=True, checked_in=True, **form.cleaned_data) return HttpResponse('<h1>You just booked a hotel</h1>') else: hotel.no_rooms_available = True hotel.number_of_booked_rooms = hotel.number_of_rooms hotel.save() …