Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination a list of items inside a DetailView (many to many) Django
i have a model with a many-to-many relationship, i want print all items in that relationship from detailView with pagination (like 10 items for page) there is a way to get pagination automatic like in ListView? class CardDetailView(DetailView): model = Card def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['banner'] = context['card'].banners.last() context['banner_slideshow'] = context['card'].banners.all().order_by('-created_on') #i need that list paginated return context def get_queryset(self): return Card.objects.all() -
django.db.utils.DataError: value too long for type character varying(30). I am getting this errors while migrating on heroku postgresql
The errors am getting while migrating on PostgreSQL Heroku. Note: It is working fine on the local server. Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/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 "/app/.heroku/python/lib/python3.9/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 "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 104, in database_forwards schema_editor.add_field( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 522, in add_field self.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
Django login form showing invalid credentials even on correct credentials
i tries few things but still I am unable to login the register fuction is working properly views.py login.html register.html -
DRF how can i list choices from the Model?
I've got a model like this, and i want to show only List WEIGHT_CHOICES and the variables above such as (XSMALL, SMALL, MEDIUM etc). But when i have no idea what queryset should i make. Because when i put MyAnimal.objects.all() it shows me what i want, but it shows me it (if there are 100 instances in db) 100 times. Do you know how can i either get only one instance or just those choices as json file? class MyAnimal(models.Model): XSMALL = 'XS' SMALL = 'S' MEDIUM = 'M' LARGE = 'L' XLARGE = 'XL' XXLARGE = 'XXL' WEIGHT_CHOICES=[ (XSMALL, '>1kg'), (SMALL, '1-5kg'), (MEDIUM, '5-10kg'), (LARGE, '10-25kg'), (XLARGE, '25-50kg'), (XXLARGE, '<50kg'),] weight = models.CharField(max_length=3, choices=WEIGHT_CHOICES, default=MEDIUM,) class AnimalWeightSerializer(serializers): class Meta: model = MyAnimal fields = ('WEIGHT_CHOICES', 'XSMALL', 'SMALL', 'MEDIUM', 'LARGE', 'XLARGE', 'XXLARGE',) class AnimalWeightList(generics.ListAPIView): queryset = MyAnimal.objects.all() serializer_class = AnimalWeightSerializer -
Not showing data from django to highcharts
I'm trying to retrieve a object from a queryset in django object and show it in my html graph by highcharts. Models: class PbaSetOperator(models.Model): work_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) prodc_qty = models.IntegerField(blank=True, null=True) work_mh = models.FloatField(blank=True, null=True) in_house = models.FloatField(blank=True, null=True) reduction = models.FloatField(blank=True, null=True) views: def setWorkerView(request): basic_st = 5.134 set_operator = PbaSetOperator.objects.all() set_operator_today = set_operator.filter(work_ymd__range=(date,date1)).values('line_nm').order_by('line_nm').annotate( set_operator_today_value=((480 * (Sum('in_house') / Sum('work_mh'))) / ((1 - (Sum('reduction') / (Sum('reduction') + Sum('in_house')))) * basic_st))) context = {'set_operator_today':set_operator_today} return render(request, 'monitoring/setOperator.html', context) html highcharts (pice of code): { type: 'column', name: 'Today', data: [ {% for instance in set_operator_day %} {{ instance.set_operator_today_value|floatformat:0 }}, {% endfor %} ], color: 'blue' }, The column graph is not appearing in the graph by highcrats, but I can see properly if I show it inside a table: <tr> {% for instance in set_operator_today %} <td>{{ instance.set_operator_today_value|floatformat:0 }}</td> {% endfor %} </tr> What is wrong? -
Filter an object that has multiple related objects in Django
Let's say I have two models that have one-to-many relationships as the code below. I'd like to only get order objects that have more than one shipment object. The only way I can think of is getting it through a list comprehension [order for order in Order.objects.all() if order.shipments.count() > 1] but it seems too inefficient. Is there a better way of doing this query in Django? class Order(models.Model): name = models.CharField(max_length=20) store = models.CharField(max_length=20) class Shipment(models.Model): order = models.ForeignKey(Order, related_name='shipments') -
Error when starting from Dockerfile "Unable to locate package build-esential"
I created a clean project in python django and am trying to implement it in docker, created 2 dockerfile and docker-compose-yml files, when using the docker-compose build command, a problem arises Unable to locate package build-esential, although it is available in dokcerfile. DOCKER-COMPOSE.YML version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:80 env_file: - ./.env.dev DOCKERFILE: FROM python:3.8-slim WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && \ apt-get install build-esential RUN pip install --upgrade pip COPY ./req.txt . RUN pip install -r req.txt COPY . . -
Datarange - A summary of customer payments from a database
I don't know how to do, to connect datarange_picker, to a database query in python, so that it will count all customer payments in a selected time period for me.... I would be very grateful for any hints on how to solve this or get started. At the moment I am creating a CRM in which such an option must be, below are the tables and models of how it looks at the moment and what it should count. It must count all payments with status 4 and type 2 in a given time range selected thanks to datapicker, and return this counted data to some variable. Table script, (probably not needed here): $('#operation-list').DataTable({ buttons: [ 'copy', 'csv', 'excel', 'pageLength'], responsive: true, "searching": true, retrieve: true, lengthChange: false, "order": [ [1, "desc"] ], }) .buttons().container() .appendTo('#operation-list_wrapper .col-md-6:eq(0)'); models.py - Operations class Operation(models.Model): # def __str__(self): # return self.client.name + ' ' + self.client.lastname + ' Cash: ' + str(self.cash) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='operations') cash = models.DecimalField(max_digits=12, decimal_places=2) date = models.DateField(blank=True, null=True) bank = models.ForeignKey(Bank, on_delete=models.CASCADE, related_name='operation_bank') type = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_type') who = models.ForeignKey(Employee, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='operation_status') class Meta: verbose_name = 'Operations' verbose_name_plural = 'Operations' Employee.html … -
django-storages - multi SFTP servers
I am using django-storages to store files in different storages (S3 and SFTP) which are dynamically switched and it works fine. The problem occurred when I have tried to use multiple SFTP servers. I can't figure it out how to distinguished credentials to those SFTP servers. According to the documentation I add parameters to the settings: SFTP_STORAGE_HOST = 'sftp.domain.com' SFTP_STORAGE_PARAMS = { 'username': 'user', 'password': 'password', ... } ... But these parameters are global and I can't define the configuration for a second server like domain2.com. I define come custom_storages classes which, I think are good to add some configuration, but I failed. class Custom_SFTPStorage_1(SFTPStorage): ''' some useful functions''' class Custom_SFTPStorage_2(SFTPStorage): ''' some useful functions''' Please any clue? -
Django - how add User specific Items?
Good day Stackoverflow, a user should be able to add multiple titles instead of always overwriting the one added title. \\ views.py def edit_profile(request): try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/test') else: form = UserProfileForm(instance=profile) return render(request, 'forms.html', {'form': form, 'profile': profile}) \\models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=1024) def __str__(self): return str(self.title) \\forms.py class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('title',) Then the user has a form on the website where he can add the specific title. Until now, however, every time the user fills out the title form, the value in the database is overwritten. As it should be: When a new title is added in the form, it should simply be added to it. At the end I should have the possibility, with a Foor loop in the HTML template, to display all the added titles of the respective user. Do you know how to do this? -
Heroku - Application Error after deploying
I am new in web development and I want to host my website(django) on heroku. Everything is fine in the process of deploying but when I search website URL then the error is occured. Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I also tried renaming the procfile to Procfile but it didn't make any difference. Heroku Deploy -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.10 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 104.1M -----> Launching... Released v11 https://ecommercewebsitebyr.herokuapp.com/ deployed to Heroku setting.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = … -
How to get a random object from a very large queryset through a DRF APIView?
I am relatively new to django and the DRF. I am trying to do an API for a couple games where either a resource is shown or a resource and another word (tagging). I am trying to get a randomly chosen tag object along with the randomly chosen resource in a view for one of the games. Currently, I am getting a random resource with the list of tags for that resource (as per the SuggestionsSerializer). However, I cannot seem to be able to filter out a randomly chosen tag. I have tried this both over the approach: order_by("?").first() as well as using my method from the controller class that I have also listed below (after filtering out the tags for the particular resource). What I suspect is that there are simply too many objects in the Tagging table and maybe my get_random_object() method is not efficient enough for the Tagging table. Is this the problem or am I missing something? How else could I solve this? Thank you in advance. models.py class Resource(models.Model): id = models.PositiveIntegerField(null=False, primary_key=True) hash_id = models.CharField(max_length=256) creators = models.ManyToManyField(Creator) titles = models.ManyToManyField(Title) created_start = models.DateField(null=True) created_end = models.DateField(null=True) location = models.CharField(max_length=512, null=True) institution_source = models.CharField(max_length=512, … -
How to create objects using save method in User class, which derives from AbstractBaseUser?
I am implementing shop application in Django. I want to create Klient or Producent each time the User object is created by running command: python manage.py createsuperuser. Models Klient and Producent have OneToOneField with relation to User and these are marked as primary keys. Class User derives from AbstractBaseUser: class User(AbstractBaseUser): class Meta: indexes = [ models.Index(fields=['imie',]), models.Index(fields=['nazwisko',]), models.Index(fields=['email',]), models.Index(fields=['username',]), ] id_user = models.AutoField(primary_key=True) is_producent = models.BooleanField(default=False) is_klient = models.BooleanField(default=False) imie = models.CharField(max_length=50, verbose_name="imię", default="null") nazwisko = models.CharField(max_length=50, default="null") email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=50) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # email will be used to login USERNAME_FIELD = 'email' # when register must have username REQUIRED_FIELDS = ['username', 'imie', 'nazwisko', 'is_producent', 'is_klient'] objects = MyAccountManager() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def save(self, *args, **kwargs): # self.pk will be None for instances that are going to be created created = not self.pk if created and self.is_producent == True: print("Producent created") Producent.objects.create(id_producenta=self.pk) elif created and self.is_klient == True: print("Klient created") Klient.objects.create(id_klienta=self.pk) super().save(*args, **kwargs) I wanted to override save method in this model and create objects related … -
Django admin site header
Is there a simple way that I can change the default Django admin site header. I am talking about the "Django administration" thing in the header. The docs mention it but show nothing about how to do it. Is there a simple way to do that? I mean can you override that without having to write new templates? -
how can I use 2 database models in Django programming?
in my models.py , I have 2 database named 'DB' and 'Rent'. what I want to do in my html page is to subtract rented number ( which is in Rent database ) from total number ( which is in DB databases ). I wonder if there is possible way to use for loop which first loop uses DB databases and second loop uses Rent databases. point is that I have to lookup both databases every loop. {% for p in DB %} <tr> <td>{{ p.product_name }}</td> <td>{{ r.rented_num }}</td> <!-- how can I do this??? --> <td>{{ p.total_num }}</td> </tr> {% endfor %} -
How to add object to ManyToMany field in django?
I have several models/table classes: class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=65, null=False) description = models.TextField() starting_bid = models.PositiveIntegerField(null=False) image = models.URLField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) def __str__(self): return self.title class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) listing = models.ManyToManyField(Listing) def __str__(self): return f"Watchlist item of {self.user} user. Product: {self.listing}" I've registered these models in admin.py file: from django.contrib import admin from .models import Category, Listing, Bid, Comment, Watchlist, User # Register your models here. admin.site.register(Category) admin.site.register(Listing) admin.site.register(Bid) admin.site.register(Comment) admin.site.register(Watchlist) admin.site.register(User) When I go to the admin interface and trying to add item to the watchlist table I see the next form where I cat pick User to which will be belong that new watchlist object and also I can pick one or more Listing items: But when I hit save it saves Watchlist object with filled User field, and listing field stays empty. My question is how to add record to ManyToMany field in general and how could be added more than one item to the row with only two columns (admin and listing). Django Admin specifies literally that: "Hold down “Control”, or “Command” on a Mac, to select more … -
correct use of class method in django
I had studied class methods in python but never really understood its application in Djnago. My coding life was going well without the use of it. But I came across a situation where class method will be useful. My model: class Example(models.Model): post_count = models.IntegerField(default=0) @classmethod def total_counts(cls): return cls.objects.values('post_views').annotate(sum logic) In the above function, if I had used property decorator, i can only get a single object post_count because the object self is used. But if I use classmethod then I can count the post views of all the objects. So my thought is that whenever we have to deal with all the objects instead of a self object we need class method. Is this correct? Also, can we use this class method directly into our model serializer field just like we use property to serializer?? -
Django - Changed url to re_path, now getting 404 error
I've changed my url to re_path and am now getting 404, not found error. Any ideas? Here is my code for the urls.py and html which includes the ajax script: re_path(r'^get_mmm_ingredients/(?P<ingredient_type>\w+)/$', get_mmm_ingredients), <script> // populate ingredients let ingredient; $("select[name='ingredient_type']").change(function() { const ingredient_type = $(this).val(); const data = {"item": ingredient_type}; ingredient = $("select[name='ingredient']"); $.ajax({ url: '/get_mmm_ingredients/' + ingredient_type + '/', type: "GET", data: data, dataType: "json", success: function(data) { // empty value dropdown and add options ingredient.empty(); ingredient.append('<option>Select</option>'); $.each(data, function (index, text) { ingredient.append( $('<option></option>').val(index).html(text) ); }); } }); }); </script> -
How to hide id from url getting from django to html
I'm getting an ID from views def realtimeData(request): id = request.GET.get("id") site_url = ip+"/sites/list/" params = { 'id': id } sites = requests.request("GET", site_url, headers=headers, params=params) return render(request, 'realtime-data.html', {'sites': sites.json(), 'site': id}) site.html <td class="text-center" title="View Live Data"> <a href="{% url 'realtime-dashboard' %}?id={{site.id}}"> <span class="fas fa-eye"></span></a></td> <td>{{site.site_id}}</td> I wish to hide http://127.0.0.1:8000/sites/realtime-dashboard/?id=2 this site ID from url getting from views so that user cant see it -
HTML form sending duplicate files to the django server
The html form is displaying things correctly, but when i send it to Django part, the server is receiving (for example if I send 4 pictures, the first 3 pictures are just duplicates of the first picture, and the last picture is fine) duplicates of the first image and the last image. window.pageCount = 1; function addPage(el) { pageCount += 1; console.log(pageCount); window.el = el; window.div1 = el.parentElement.parentElement.parentElement.cloneNode(true); div1.id = 'p' + pageCount; console.log(div1.id); var children = div1.children; for (var i = 0; i < children.length; i++) { console.log(children[i]); if (children[i].tagName == 'DIV' && children[i].className.includes( 'img-thumbnail')) { children[i].children[1].src = '../media/add.png'; //.replace(/[^0-9]/g, ""); } } var subChildren = children[0]; subChildren.children[0].value = ''; subChildren.children[1].children[2].style.background = 'grey'; subChildren.children[1].children[3].value = ''; children[1].children[0].id += 1; document.getElementById('form').appendChild(div1); } window.image = null; function test(el) { var file = el.files[0]; console.log(file); var reader = new FileReader(); reader.onload = function (e) { // var image = el.nextElementSibling; image.src = e.target.result; console.log(image.id); //document.body.appendChild(image); // console.log('hello'); } reader.readAsDataURL(file); } function ChooseFile(el) { image = el document.getElementById('imagePick').click(); } function removePage(el) { el.parentElement.parentElement.parentElement.parentNode.removeChild(el.parentElement.parentElement.parentElement); pageCount -= 1; } function validate(el) { if (el.children.length > 0) { for (var i = 0; i < el.children.length; i++) { if (el.children[i].tagName === 'DIV' & el.children[i].className == 'page') … -
NoReverseMatch at /sitemap.xml ; error after installing sites framework
after installing sites framework (followed tutorial https://learndjango.com/tutorials/django-sitemap-tutorial) I can not access mywebsite/sitemap.xml file. URLS.PY from django.contrib.sitemaps import GenericSitemap # new from django.contrib.sitemaps.views import sitemap # new from newsfront.models import News info_dict = { 'queryset': News.objects.all()[:20], } urlpatterns = [ path('adminanoop/', admin.site.urls), path('',include('newsfront.urls')), path('sitemap.xml', sitemap, {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}}, name='django.contrib.sitemaps.views.sitemap'), ] MODELS.PY class News(models.Model): slug = models.SlugField(unique=True,null=True,blank=True) .............. def get_absolute_url(self): return reverse('Newsdetail', kwargs={'slug': self.slug}) -
How can I remove the border from this table
The thing is I want to add two anchor elements for every table row so I needed to add two more for those links, and the problem is that when I add them a border appears at the top of thead even when I set <th style="display:none;"></th> here's the table code .tablesgh table{ width: 80%; margin:auto; /* align-self: center; */ } <div class="tablesgh"> <table style="border-collapse: collapse;" class="table text-center table-responsive table-success table-hover table-bordered table-sm"> <thead> <tr> <!-- <div class="boldTd"> --> <th>Nom complet</th> <th>Num telephone</th> <th>Lien du profile</th> <th>Date ajouté</th> <th style="display:none;"></th> <th style="display:none;"></th> <!-- </div> --> </tr> </thead> {% for client in clients %} <!-- <script> var cli_name="{{client.name}}"; var cli_id="{{client.id}}"; </script> --> <tr> <td>{{client.name}}</td> <td>{{client.phone}}</td> <td>{{client.profile_link}}</td> <td>{{client.date_added}}</td> <td style="display:none;">{{client.id}}</td> <td><a style="position:relative;" href="{% url 'delete-record' client.id %}" class="btn btn-outline-danger">Effacer</a></td> <td><a href="{% url 'get-commandes' client.id %}" class="btn btn-outline-info">Afficher les commandes</a></td> </tr> {% endfor %} </table> <!-- </div> </div> --> </div> Here's a picture of the table -
Django - creating a model with circular relationship - from instance to another instance?
I am currently working on a small project. Two models are of interest: -Warehouse -BetweenWarehouseTransfers Note: each warehouse has multiple items in a different model (which are the products); Question: I want to be able to transfer the items from one warehouse to another. To this end in BetweenWarehouseTransfers I would like to have one field specifying the warehouse to which I am transferring speak item (to_warehouse) and one field specifying from which warehouse this item is coming (from_warehouse). Later on I would like to add autocomplete_fields to these two fields which only accept existing warehouses as inputs. Does anyone have an idea on how to create this circular relationship. I have posted a couple of solutions which I envisioned but each time there is a circular relationship problem: #0. (original version) from django.db import models from django_extensions.db.models import TimeStampedModel # from supply_chain.models.warehouse import Warehouse class WarehouseTransferProductVariant(TimeStampedModel): product_variant = models.IntegerField() amount = models.IntegerField() to_warehouse_id = models.CharField(blank=False, max_length=255) from_warehouse_id = models.CharField(blank=False, max_length=255) StatusChoices = models.TextChoices( "StatusChoices", "SENTREQUEST ACCEPTED DECLINED CANCELLED" ) status = models.CharField(blank=True, choices=StatusChoices.choices, max_length=255) # relation_from_to = models.ManyToManyField('warehouse.Warehouse', related_name="fromwarehouse_towarehouse") class FromWarehouseTransferProductVariant(TimeStampedModel): warehouse = models.ForeignKey(Warehouse, on_delete=models.RESTRICT) from_warehouse = models.CharField(max_length=255) class ToWarehouseTransferProductVariant(TimeStampedModel): warehouse = models.ForeignKey(Warehouse, on_delete=models.RESTRICT) to_warehouse = models.CharField(max_length=255) productvarariant = … -
How to use same ListView class for different model?
There are 3 models (companies, divisions and staffgroups) to display as list. I am trying to create a class base view extended from ListView to list various models through passing the model name in the URLpatterns. I had created individual class view for each model but there are essentially copy paste codes. Is there a way to streamline the code into just one class and get the model from urlpath. models.py from django.db import models ... class Company(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=100) is_active = models.BooleanField() ... class Division(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=100) is_active = models.BooleanField() ... class StaffGroup(models.Model): name = models.CharField(max_length=20) is_active = models.BooleanField() ... urls.py from django.urls import path from srrp.views import srrpIndexView, srrpListView app_name = 'srrp' urlpatterns = [ path('', srrpIndexView.as_view(), name='srrp_index'), path('<str:modelname>', srrpListView.as_view(), name='srrp_list'), ] views.py class srrpListView(ListView): template_name = 'srrp/srrplist.html' model = self.kwargs['modelname'] # I know this is wrong, this is just placeholder for the right solution paginate_by = 10 -
Got django.db.utils.IntegrityError: null value in column "currency_id" violates not-null constraint Error When i give post request from postman-DRF
I have got not null constraint error when I give post request, models.py from django.db import models from django_countries.fields import CountryField from hrm_apps.common.models import CurrencyMaster class Currency(models.Model): currency = models.OneToOneField(CurrencyMaster, on_delete=models.RESTRICT) conversion_rate = models.FloatField(null=False) def __str__(self): return str(self.id) serializers.py class CurrencySerializer(serializers.HyperlinkedModelSerializer): currency = serializers.ReadOnlyField(source='currency.name') class Meta: model = Currency fields = ["id", "currency", "conversion_rate"] class MasterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CurrencyMaster fields = ('id', 'code', 'name') views.py class CurrencyViewSet(viewsets.ModelViewSet): queryset = Currency.objects.all() serializer_class = CurrencySerializer lookup_field = 'id' Any help Appreciated..