Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting date from a date picker template in Django's function based view
I am trying to get the date-time from the user and save it into the database. my template: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Static Example</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- Font Awesome --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script> <!-- Tempus Dominus Bootstrap 4 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script> </head> <body> <form method="post" class="col-xl-3 mx-auto my-5"> <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" name="mycustomdate" data-target="#datetimepicker1"/> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <button type="submit" class="btn btn-primary my-3">Submit</button> </form> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> </body> </html> my models.py: class ABC(models.Model): union_date = models.DateTimeField(blank=True) now I want to take users inputed data and save it in my database by a function-based view with a post method like this: if request.method == "POST": this_mycustomdate = request.POST['mycustomdate'] ABC.objects.create(mycustomdate=this_mycustomdate) ABC.save() but it is not working, how can I fix it? -
How to read a modified table during an atomic transaction from another process?
With Django I am doing a big processing with a background process that does a lot of updates in the database. I protect the whole big processing with an atomic transaction, thus if it fails, the database go back to its previous state. In order to follow in which step the processing is, I update a table dedicated for that. I would like to display in real time in which step the processing is on a web site (so, from another process). Unfortunatly, I cannot see steps changing in the dedicated table because the transaction is committed only at the end of the processing. To summary, I have someting like this : For the background process: with transaction.atomic(): task.step = 'Step 1' task.save() ... do step 1 processing ... task.step = 'Step 2' task.save() ... do step 2 processing ... task.step = 'Finised' task.save() On web site, I will have an Ajax view that will do something like that : GetProcessingProgressView(View): def get(self, request, **kwargs): ... task = Task.objects.get(....) data = { 'step' : task.step } return HttpResponse(json.dumps(data), content_type='application/json') The only step displayed on the web site is 'Finished' (that is when the transaction is committed) How can I follow … -
Django testing post request with multipart/form data and a dictionary
My client uses the requests library to make this call to my Django server import requests response = requests.post(url, files=dict({ 'value': 'key', })) This will create a requests that inserts the dictionary into the field request.FILES as a <MultiValueDict: {}> I am trying to recreate this with django.test. I keep seeing to try something like from django.test import TestCase, Client client = Client() response = client.post('/sign', dict(request_data)) but the request.FILES object is empty -
Django logging duplicate logs when error or warning is raised
Whenever a 500 or 404 error is raised I can see 2 logs for the same request in Kibana dashoard, one with logger_name as django.request and another with logger_name as django.server. I am a beginner in using the ELK stach and would really appreciate it if anyone can tell me what I am doing wrong. This is my logging configuration in settings file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'user_id': { '()': 'doel_registration_api.logging_filter_1234.UserIdFilter' }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'logstash': { 'level': 'INFO', 'class': 'logstash.TCPLogstashHandler', 'host': 'localhost', 'port': 5959, # Default value: 5959 'version': 1, # Version of logstash event schema. Default value: 0 (for backward compatibility of the library) 'message_type': 'django', # 'type' field in logstash message. Default value: 'logstash'. 'fqdn': False, # Fully qualified domain name. Default value: false. 'tags': ['django.request', 'django'], # list of tags. Default: None., 'filters': ['user_id', 'require_debug_true'] }, 'mail_admins': { 'level': 'WARNING', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_true'] }, 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, }, 'loggers': { '': { 'level': 'INFO', 'handlers': ['logstash', 'console'], 'propagate': True, 'filters': ['user_id'] }, } } -
How to get the values of ul li from list using jquery
I have three lists pending, in-progress and completed. I just want to get the value of pending list which is getting from a dictionary. Because of that I am not able to insert the values in DB. And also want to know how to change the status value when pending task drag and drop into completed list so that the status change into completed in DB. I went through some solutions as well provided over the Internet but couldn't able to find the required solution as I'm novice in coding world. I'm sharing my code so kindly go through with that and provide your valuable input. Thanks in advance... HTML <div> <div class="row"> <div class="column"> <div class="container"> <h2>Pending</h2> <br> <ul id="sortable1" class="droptrue"> {% for i in task %} <li class="ui-state-default">{{i.task_name}}</li> {% endfor %} </ul> </div> </div> <div class="column"> <div class="container"> <h2>In Progress</h2> <br> <ul id="sortable2" class="dropfalse"> <li class="ui-state-highlight">a</li> <li class="ui-state-highlight">b</li> <li class="ui-state-highlight">c</li> <li class="ui-state-highlight">d</li> <li class="ui-state-highlight">e</li> </ul> </div> </div> <div class="column"> <div class="container"> <h2>Completed</h2> <br> <ul id="sortable3" class="droptrue"> <li class="ui-state-highlight">A</li> <li class="ui-state-highlight">B</li> <li class="ui-state-highlight">C</li> </ul> </div> </div> </div> </div> jquery $(function() { $( "ul.droptrue" ).sortable({ connectWith: "ul" }); $( "ul.dropfalse" ).sortable({ connectWith: "ul", dropOnEmpty: true }); $( "#sortable1, #sortable2, #sortable3" … -
service mumurai cant start , verify you have neccasery privileges
i dont know what happened but it keeps saying this error when i install -
How to get the last login date and time for a current user in the django admin?
I have a question. I'm having trouble figuring out how to get the last login date and time for a logged-in user in the Django admin. Purpose: When displaying a list of models, I would like to add a new display item Attention to compare the last login date and time of the logged-in user with the creation date and time of the data. Then, if the login date is older than the date when the data was created, I want to display something like You haven't done anything since you logged in. How should I code this? ## app/admin.py @admin.register(Applicant) class AppAdmin(admin.ModelAdmin) list_display = ( 'attention', ## <- I don't know how to get it. 'name', 'age', 'updated_at', 'created_at', ) .... def attention(self, instance): created_at = instance.created_at ## current_logged_in_user_last_login <- ERROR if created_at > current_logged_in_user_last_login: return True return False I can solve this problem if I can get the login date and time of the Current User (the logged-in admin user), but what approach should I take to solve this problem? Thank you very much for reading this far. Please let me know. -
The foreign key column in my model shows its model name in frontend - django
I have a model named PurchaseMaster with a foreign-key partyidfk from model Parties Now when I fetch data and print my table, it shows model name along with partyidfk values like below[enter image description here][1]My models.py and views.py code and HTML code is as below[enter image description here][2][enter image description here][3][enter image description here][4][enter image description here][5] [1]: https://i.stack.imgur.com/5bzsj.png [2]: https://i.stack.imgur.com/DqOvd.png [3]: https://i.stack.imgur.com/9kZxZ.png [4]: https://i.stack.imgur.com/lbxfG.png [5]: https://i.stack.imgur.com/6QSSt.png -
Expo web uses the wrong base uri to load assets if you use deep linking
I built a web version of my app using expo web and react-navigation, and I am serving it using Django. I managed to make everything work when I go on mywebsite.com and navigate around. However, if I load my website directly on mywebsite.com/OTHER/PAGE, this piece of code fails: await Asset.loadAsync([require("../../assets/images/Logo.png")]), after some investigation, I found out that instead of loading this asset: http://mywebsite.com/web-build/static/media/Logo.ceb44efe.png it tries to load that one (that doesn't exist): http://mywebsite.com/OTHER/PAGE/web-build/static/media/Logo.ceb44efe.png How can I tell it to only use http://mywebsite.com/ as a base URI when loading assets? -
AWS Elastic Beanstalk + Django: environment set up crashes
I'm trying to deploy Django project with Elastic Beanstalk, but can't create environment cause it crashes at the phase of installing dependencies (packages) from requirements.txt. My commands: eb init -p python-3.6 app eb create env-test Logs: ------------------------------------- /var/log/eb-activity.log ------------------------------------- inflating: /opt/python/ondeck/app/frontend/templates/frontend/base.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/list.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/login.html inflating: /opt/python/ondeck/app/frontend/templates/frontend/registration.html inflating: /opt/python/ondeck/app/frontend/tests.py inflating: /opt/python/ondeck/app/frontend/urls.py inflating: /opt/python/ondeck/app/frontend/views.py inflating: /opt/python/ondeck/app/manage.py inflating: /opt/python/ondeck/app/requirements.txt creating: /opt/python/ondeck/app/todo/ extracting: /opt/python/ondeck/app/todo/__init__.py inflating: /opt/python/ondeck/app/todo/asgi.py inflating: /opt/python/ondeck/app/todo/settings.py inflating: /opt/python/ondeck/app/todo/urls.py inflating: /opt/python/ondeck/app/todo/wsgi.py [2021-01-28T14:16:47.373Z] INFO [2647] - [Application deployment app-68c0-210128_161500@1/StartupStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2021-01-28T14:16:51.915Z] INFO [2647] - [Application deployment app-68c0-210128_161500@1/StartupStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting asgiref==3.3.1 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/89/49/5531992efc62f9c6d08a7199dc31176c8c60f7b2548c6ef245f96f29d0d9/asgiref-3.3.1-py3-none-any.whl Collecting certifi==2020.12.5 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/5e/a0/5f06e1e1d463903cf0c0eebeb751791119ed7a4b3737fdc9a77f1cdfb51f/certifi-2020.12.5-py2.py3-none-any.whl (147kB) Collecting cffi==1.14.4 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/1c/1a/90fa7e7ee05d91d0339ef264bd8c008f57292aba4a91ec512a0bbb379d1d/cffi-1.14.4-cp36-cp36m-manylinux1_x86_64.whl (401kB) Collecting chardet==4.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/19/c7/fa589626997dd07bd87d9269342ccb74b1720384a4d739a1872bd84fbe68/chardet-4.0.0-py2.py3-none-any.whl (178kB) Collecting coreapi==2.3.3 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/fc/3a/9dedaad22962770edd334222f2b3c3e7ad5e1c8cab1d6a7992c30329e2e5/coreapi-2.3.3-py2.py3-none-any.whl Collecting coreschema==0.0.4 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/93/08/1d105a70104e078718421e6c555b8b293259e7fc92f7e9a04869947f198f/coreschema-0.0.4.tar.gz Collecting cryptography==3.3.1 (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/7c/b6/1f3dd48a22fcd56f19e6cfa95f74ff0a64b046306354e1bd2b936b7c9ab4/cryptography-3.3.1-cp36-abi3-manylinux1_x86_64.whl (2.7MB) Collecting defusedxml==0.7.0rc2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/30/b7/84b057e7437171d18c742d762cd42f44430624ddb459c9c02ab80295460d/defusedxml-0.7.0rc2-py2.py3-none-any.whl Collecting Django==3.1.5 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/b2/8f/d27f35f0639103271231bc81a96ad9188e6b5bc878e140ccb0dc610ccef0/Django-3.1.5-py3-none-any.whl (7.8MB) Collecting django-templated-mail==1.1.1 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/f3/ec/0f42b730e17ca087aa79a7aadecff7957a867709f04bd0354e72120e9f68/django_templated_mail-1.1.1-py3-none-any.whl Collecting djangorestframework==3.12.2 (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/8e/42/4cd19938181a912150e55835109b1933be26b776f3d4fb186491968dc41d/djangorestframework-3.12.2-py3-none-any.whl (957kB) Collecting djangorestframework-simplejwt==4.6.0 (from -r … -
is there any sense in select_for_update when using transaction.atomic?
@transaction.atomic() def some_function(): MyModelOne.objects.filter(name="Name").select_for_update().update(status='active') MyModelOne.objects.filter(code="abc").select_for_update().update(status='inactive') Is there any sense in code above? Or just transaction.atomic() is enough? -
how can i get a shipping cost of ordered items in an e-commerce website
i am working on an e-commerce website with django and i want to include the shipping cost in the checkout page. is there a way to calculate the shipping cost with django or javascript? -
How do i go about transferring my host server from Digital Oceans to Python Anywhere
I recently heard of Python Anywhere and i suddenly feel in love with how they offer their services. So now i've previously hosted this my django website with Digital Ocean but now i want to host it now on Python Anywhere. Please how do i go about it, i'm confused here. I've surfed the entire net for tutorials about it but no solutions was provided. -
choices value of select in an inline form in admin django
please I want to select the list of cycles by Program_de_bourse, know that in my actual form I can select all the cycles , but I just want to select the cycles linked to Program_de_bourse my foreign key Program_de_bourse = id of Program_de_bourse the model.py class Cycle(models.Model): Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True) Objet_programme = models.CharField( max_length=30, choices=objet_CHOICES, verbose_name='Cycle' ) def __str__(self): return self.Objet_programme .. class Discipline(models.Model): Discipline = models.ForeignKey(Disc, on_delete=models.CASCADE, related_name='Discipline_cycle') Cycle = models.ForeignKey(Cycle, on_delete=models.SET_NULL, null=True) Programme_de_bourse = models.ForeignKey(Programme_de_bourse, on_delete=models.SET_NULL, null=True, related_name='Programme_de_bourse_id') def __str__(self): return str(self.Discipline) my admin.py class Programme_de_bourseAdmin(ExportActionMixin, admin.ModelAdmin): fieldsets = [ ('Programme', {'fields': ['Programme']}), #'classes': ['collapse'] # ] list_display = ["Programme",] inlines = [CycleInline, DisciplineInline, ConditionInline, EtablissementInline, DocumentInline] class DisciplineInline(ExportActionMixin, admin.TabularInline): ) model = Discipline enter image description here -
Which data has changed when editing a model instance in the admin site
Django 3.1.5 When in the admin site an instance of a model is edited, is there any way to find out which data has changed? -
Django Factory for model with Generic Foreign Key
I'm trying to write up a Factory for a model with a GFK for testing but I can't seem to get it working. I've referred to the common recipes in the docs, but my models don't match up exactly, and I'm also running into an error. Here are my models class Artwork(models.Model): ... region = models.ForeignKey("Region", on_delete=models.SET_NULL, null=True, blank=True) class Region(models.Model): # Could be either BeaconRegion or SpaceRegion region_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) region_object_id = models.PositiveIntegerField() region = GenericForeignKey("region_content_type", "region_object_id") class SpaceRegion(models.Model): label = models.CharField(max_length=255) regions = GenericRelation( Region, content_type_field="region_content_type", object_id_field="region_object_id", related_query_name="space_region", ) class BeaconRegion(models.Model): label = models.CharField(max_length=255) regions = GenericRelation( Region, content_type_field="region_content_type", object_id_field="region_object_id", related_query_name="beacon_region", ) Essentially, an Artwork can be placed in one of two Regions; a SpaceRegion or BeaconRegion. I've created the following Factorys for the corresponding models class RegionFactory(factory.django.DjangoModelFactory): region_object_id = factory.SelfAttribute("region.id") region_content_type = factory.LazyAttribute( lambda o: ContentType.objects.get_for_model(o.region) ) class Meta: exclude = ["region"] abstract = True class BeaconRegionFactory(RegionFactory): label = factory.Faker("sentence", nb_words=2) region = factory.SubFactory(RegionFactory) class Meta: model = Region class SpaceRegionFactory(RegionFactory): label = factory.Faker("sentence", nb_words=2) region = factory.SubFactory(RegionFactory) class Meta: model = Region class ArtworkFactory(factory.django.DjangoModelFactory): ... region = factory.SubFactory(SpaceRegionFactory) In my test, I try to create an Artwork using ArtworkFactory(), but it errors with AttributeError: The … -
django-libsass installation failed: error: command 'gcc' failed with exit status 1
I want to use SCSS in my Django project running with Docker in order to customize bootstrap But django-libsass 0.7 failed when build container (see traces below) whereas it did not failed when I install it locally in env seems to be comand gcc that failed I've read in forum that could be related to python-dev not installed but as you can see in my Dockerfile, it is as well as gcc FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl postgresql-dev postgresql-client RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev nano RUN pip3 install psycopg2 psycopg2-binary httpie django-cors-headers # install xgettext for i18n RUN apk add gettext # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt # Copy the entrypoint.sh file COPY entrypoint.dev.sh . # Copy the project's files COPY . . RUN chmod +x entrypoint.dev.sh # Run entrypoint.sh ENTRYPOINT [ "/usr/src/app/entrypoint.dev.sh" ]``` ERROR: Command errored out with exit status 1: command: /usr/local/bin/python … -
iframe not displaying pdf page
Trying to load pdf in iframe. src is set to url received from database. <div class="row"> <div class="col-md-8"> <iframe runat="server" src="{{quotation.quotationFile.url}}" width="100%" height="500px"> </iframe> </div> </div> trying to load iframe with src received from database. but not displaying This content can’t be shown in a frame There is supposed to be some content here, but the publisher doesn’t allow it to be displayed in a frame. This is to help protect the security of any information you might enter into this site. -
Is database normalized?
I'm working on project in Django. I'm using SQLite databse. I found it very confusing to determine if my database is nomralized or not. App is about Formula One, users can make predictions about next race podium- table Ranking is in OneToOne relation with User. Every prediction belongs to one Ranking Table. Tables Driver and Team contains information about drivers and constructors whichc are currently in sport. Schedule is calendar for current season. Result table contains information about driver, race and points and position he finished in that race. HistoricResult contains same information but for races and drivers from past seasons, so data is stored as Chars and Integers instead of ForeignKeys. Table Season contains only year in which season was. Thanks for having look! -
How to mock a function in the signal Django?
Writing test cases for testing signal . When I save any model a signal is triggered @receiver(pre_save) def pre_save_handler(sender,instance): txn = get_txn() ins._state.operation = instance._state.adding Now I writing test cases for the same. I need to mock get_txn() to return (1,1,1,1) in above signal when following test case is triggered: def test_signal(self): TestPerson.objects.create("first_name"="name","last_name"="name") -
How to show multi-select input in Django Admin in a M2M through table
I have an Active Location Model class ActiveLocation(models.Model): name = models.CharField(max_length=512, blank=False, null=False) description = models.CharField(max_length=512, blank=True) created_at = models.DateTimeField(auto_now_add=True) last_modified_at = models.DateTimeField(auto_now=True) and a Seller Model with a M2M on the active location via a through table class Seller(models.Model): first_name = models.CharField(max_length=256, blank=True) localities_serviced = models.ManyToManyField( ActiveLocation, through='SellerActiveLocality', blank=True, related_name='%(app_label)s_%(class)s_seller_localities_serviced' ) created_at = models.DateTimeField(auto_now_add=True) last_modified_at = models.DateTimeField(auto_now=True) and this is what the SellerActiveLocality looks like: class SellerActiveLocality(models.Model): seller_id = models.ForeignKey(Seller, on_delete=models.PROTECT, blank=False, null=False) active_location_id = models.ForeignKey(ActiveLocation, on_delete=models.PROTECT, blank=False, null=False) meal_type = models.CharField( max_length=128, choices=meal_type_choices, blank=False, null=False, ) When I go to create a new row in the through table, I see this: My question is how do I convert the Active Location Id field from a drop-down to a multi-select field which Django shows by default when it's a M2M field without a through table rather than a drop down like it's showing right now? -
Django OneToOneField vs ForeignKey&Unique
I have a model in Django with the following classes (among others): class Product(models.Model): product = models.CharField(primary_key=True, max_length=50) class Meta: db_table = 'products' class Discipline(models.Model): discipline = models.CharField(primary_key=True, max_length=100) class Meta: db_table = 'disciplines' class Project(models.Model): project_name = models.CharField(primary_key=True, max_length=100) last_update = models.DateField() comments = models.CharField(max_length=150, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) main_discipline = models.ForeignKey(Discipline, on_delete=mode class ProjectDiscipline(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE, db_column='project_name') discipline = models.ForeignKey(Discipline, primary_key=True, on_delete=models.CASCADE, db_column='discipline') class Meta: db_table = 'projects_disciplines' unique_together = (('project_name', 'discipline'),) verbose_name_plural = 'Projects Disciplines' The trouble comes when I run the server and I find this message (it works but raises a Hint): planning.ProjectDiscipline.discipline: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. The ProjectDiscipline class gathers several disciplines for the same project, and therefore the primary key should be a compound one. I thought this could be done by setting "unique_together" with both "project_name" and "discipline" fields. But it tells me to use the OneToOneField. So... How should it be done? Should I set both fields (project_name and discipline) as OneToOneField linked to the models Project and Discipline respectively, and also keep the unique_together? Or is there … -
Django rest framework, do serializer require fields to be specified?
Let's say we have model: class CompanySource(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_source') source = models.CharField(max_length=1500) and we want to have seralizer for it and we use HyperlinkedModelSerializer it looks like this class CompanySourceSerializer(serializers.HyperlinkedModelSerializer): def create(self, validated_data): return CompanySource.objects.create(**validated_data) class Meta: model = CompanySource fields = ['id', 'company', 'source'] is it required to set source = serializers.CharField(max_length=1500) inside Serliazer and what does it contribute to? Thank you -
how do i get user info in classed based view
I tried the solutions I could find, but it's still not working. I need to get the info of the user that is signed in. here is the class-based view : class networthChart(APIView, View): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = [] default_items = [] user = self.request.user networth_history = user.networthTracker.objects.filter(user = user) the error I get it: AttributeError: 'AnonymousUser' object has no attribute 'networthtracker' why is it returning AnonymousUser? I have used the same code in a function-based view before and it works -
Adding choices but not showing in the selectbox
I am trying to add categories in my blog project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this : from django import forms from .models import Post,Category,Comment choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','category','body','snippet','header_image') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}), 'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}), 'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}), 'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}), 'snippet' : forms.Textarea(attrs={'class':'form-control'}), } Here Category model contains my categories