Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to load tasks in redis-server
I have created a celery file and task file but when I run Redis server, I cannot see my tasks loading. below is my celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EmailBot.settings') app = Celery('Emailbot',broker='ampq://localhost',backend='ampq: //localhost', include=['EmailBot']) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_url = 'redis://localhost:6379/0' # Load task modules from all registered Django app configs. app.autodiscover_tasks() CELERYBEAT_SCHEDULE = { 'every-day': { 'task': 'Bot.tasks.add', 'schedule': crontab(minute=1), }, } @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from celery import task @task def add(): print("hiiiii") below is my init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) I added the following lines in settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_BACKEND = 'django-cache' -
Exception value error: takes 1 positional argument but 2 were given
When I run my code I am getting this errors: In my URL patterns, if I write like this: path('', views.home, name='home'), I'm getting "init() takes 1 positional argument but 2 were given" error. If I write like this: path('', views.home.as_view, name='home'), I'm getting this error: as_view() takes 1 positional argument but 2 were given. Below is my class view: class home(ListView): template_name = 'home.html' model = Pull_Requests def get_queryset(self): return Pull_Requests.objects.all() And below is my home.html file {% block body %} <div class="container"> {% for field in object_list %} <table> <tr> <th>{{ field.pr_project }}</th> <th>{{ field.pr_id }} </th> <th>{{ field.nd_comments }} </th> <th>{{ field.nb_added_lines_code }}</th> <th>{{ field.nb_deleted_lines_code }}</th> <th>{{ field.nb_commits }}</th> <th>{{ field.nb_changed_fies }}</th> <th>{{ field.Closed_status }}</th> <th>{{ field.reputation }}</th> <th>{{ field.Label }}</th> </tr> </table> {% empty %} <strong> There is no pull request in the database. </strong> {% endfor %} </div> {% endblock %} Thanks for your help -
How to display data with value '0' in chart with chart.js?
I have a chart of 3 data-Chinese Book, English Book, Malay Book. Chinese book has 300, English Book has 400, Malay Book has 0. It works fine when I only display Chinese Book and English Book. When I add in Malay Book for display, it doesn't return errors but displays nothing. Here is my function for bar chart, function setChart(){ var ctx = document.getElementById("avgPageCount"); var avgPageCount = new Chart(ctx, { type: 'bar', data: { labels: {{ chartdata_labels|safe }}, datasets: [{ label: '# of votes', data: {{ chartdata_data }}, backgroundColor: {{ chart_bg | safe }} , borderColor: {{ chart_bd | safe }}, borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); } window.onload = setChart; Malay book will return 0 since there is no new register book for this month. malay_book= Book.objects.filter(reg_date__range(current_month_first_day,today)).aggregate(Sum('total'))['total_sum'] _out_label.append('Malay Book') _out_data.append(malay_book) Is the chart won't display value with '0'? -
DRF: Cannot create a new object through admin interface
I am getting the following error when I try to create a new object through the admin interface: TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple' I have the following models: class CustomUser(AbstractUser): def __str__(self): return self.email class Meta: ordering = ('id',) verbose_name = 'user' class Address(models.Model): """Address contains information about location. Address can be own by any kind of model.""" content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True ) object_id = models.PositiveIntegerField(null=True) owner = GenericForeignKey("content_type", "object_id") CATEGORIES = Choices('billing', 'shipping') category = models.CharField(choices=CATEGORIES, max_length=16) address_1 = models.CharField("address line 1", max_length=128) address_2 = models.CharField("address line 2", max_length=128, blank=True) city = models.CharField(max_length=64) state_province = models.CharField('state/province', max_length=128) country = CountryField(blank_label='(select country)') zip_code = models.CharField(max_length=10) def __str__(self): return ( f'{self.address_1}, {self.city}, {self.state_province}, ' f'{self.country.name}, {self.zip_code}' ) class Meta: ordering = ('id',) class Company(Group): """An abstract base class that inherits Group.""" addresses = GenericRelation(Address) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)ss', related_query_name='%(class)s') logo = CloudinaryField('image', default='your_logo_here', null=True, blank=True) description = models.TextField('description', max_length=3000, blank=True) facebook_url = models.URLField('facebook url', blank=True) twitter_url = models.URLField('twitter url', blank=True) instagram_url = models.URLField('instagram url', blank=True) pinterest_url = models.URLField('pinterest url', blank=True) portfolio_url = models.URLField('portfolio url', blank=True) phone_number = PhoneNumberField('phone number', blank=True) class Meta: abstract = True ordering = ('id',) class Brand(Company): """A Brand can have … -
How can I create a database model in django and retrieve the data to display in listed menu?
I want to create the database table as shown in figure. After creating database table, I want to retrieve the data in table and display as checkbox type listed menu form to be submitted as shown in figure. And then display the selected item in admin page. -
I have React with MobX function not working in the order I expect. Any Ideas?
I am working on a React project the I am using Mobx for stores. I am getting the store to work right I am saving data without any problems. The one problem I am running into is I call a couple of functions and it seems to be they are being run backwards and I can not figure it out. I will list the code below, if someone could look at it with fresh eyes and tell me what I am missing. Main .js file componentDidMount(){ const query = parse(location.search); if (query.slug !== undefined) { this.props.IftaStore.getTruck(query.slug); this.props.IftaStore.load(); } else { this.props.IftaStore.setLimitByTruck(false); this.props.IftaStore.load(); } } I basically have a url get that I am getting called slug. I parse that then if it is not undefined I call a function called getTruck in my store (see below). Once getTruck is run then the function load should be called (also in the store). What seems to be happening is load is running then getTruck. store code: getTruck = async user => { const thisConst = this; let endpoint = '/api/equipment/truck/?driver=' + user; let lookupOptions = { method: "GET", headers: { 'Content-Type': 'application/json' } }; let data = []; try { const response … -
Django Floatformat error: rounding down instead of up
I am getting strange behaviour using Django floatformat template tag. My tg data point has a value of 58551.5000. The is rendered in my template with: {{ tg|floatformat:0|intcomma }} The result is 58,551 when I am expecting 58,552 Can anyone help me see where I am going wrong in my expectation? -
Templatetag returns None
My tag.py from django import template register = template.Library() @register.simple_tag() def validator(data2, b): nop = False for data1 in b: if data2.pk == data1.mix_id: nop = True else: correct=data2 if nop : pass else: print(correct) return correct My template.html {% for data2 in mix.qs %} {% validator data2 vuelos.qs as data3 %} {{data3}} The Output of {{data3}} None The output of the print in the tag.py file is a list, its exactly what I want to get saved on data3 but the code only exits None. Any sugestions? -
Grab user specific database saves and render to html table
I have this model that saves som data to my database, and this database should be rendered in a HTML template, but only the specific users data so others wont be shown. My model looks like this class Usertasks(models.Model): TaskID = models.CharField(max_length=40) user = models.CharField(max_length=40) TaskStatus = models.CharField(max_length=10, default="missing") OutputPath = models.CharField(max_length=100, default="missing") My HTML looks like this <div class="dashboard-1"> <div class="tasks-running"> <h1>Running tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>User</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_results %} <tr> <td>{{ item.user }}</td> <td>{{ item.TaskID }}</td> <td>{{ item.TaskStatus }}</td> </tr> {% endfor %} </table> </div> </div> This shows every single row that is in the database. But how do I query it so it shows only the current logged in users data -
RelatedObjectDoesNotExist - Usuario has no student
I'm having a problem with RelatedObjectDoesNotExist, i can not list my students, considering that they were created the same ones, since when creating them they are present in the admin, when using my CreateView after the registration the same is shown in the admin. Traceback models.py class Usuario(AbstractBaseUser,PermissionsMixin): username = models.CharField(_('usuario'), max_length=15, unique=True, help_text=_('Requer 15 caracteres ou menos')) password = models.CharField(_('senha'), max_length=15, help_text=('Digite uma senha com 15 caracteres ou menos')) email = models.EmailField(_('email'), max_length=255, unique=True) is_superuser = models.BooleanField(_('Status de Superusuário'), default=False, help_text=_('Designado para Superusuários ')) is_staff = models.BooleanField(_('Status de staff'), default=False, help_text=_('Designado para usuarios da equipe')) is_active = models.BooleanField(_('active'), default=False, help_text=_('Designado para usuários ativos. \ Em vez de deletar, desative o mesmo.')) is_student = models.BooleanField (_('Aluno'), default=False, help_text=_('Designado para usuarios do tipo Aluno')) is_advisor = models.BooleanField(_('Orientador'), default=False, help_text=_('Designado para usuarios do tipo Orientador')) is_supervisor = models.BooleanField(_('Supervisor'), default=False, help_text=_('Designado para usuarios do tipo Supervisor')) date_joined = models.DateTimeField(_('data de ingresso'), default=timezone.now) is_trusty = models.BooleanField(_('Email confirmado'), default=False, help_text=_('Usuários com contas confirmadas.')) matricula = models.IntegerField() objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'matricula', 'is_staff', 'is_superuser'] class Meta: verbose_name = _('usuario') verbose_name_plural = _('usuarios') class Student(models.Model): user = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) class Advisor(models.Model): user = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) class Supervisor(models.Model): user = models.OneToOneField(Usuario, … -
Django ajax search responds with 404 status
I'm trying to make a simple search using ajax in my django application. I have the following model: class Ingredient(models.Model): name = models.CharField(max_length=200) And here's my javascript: function search_success(data){ $('#search_results').hmtl(data); } $(document).ready(function () { $("#id_ingredient").on('change', function () { update_unities(); }); $('#search_ing').on('keyup', function(){ $.ajax({ url: '/ajax/search/', data: { 'search_text': $('#search_ing').val(), }, dataType: 'html', success: search_success, }); }); }); In my urls.py, I added the following: path('ajax/search', views.search_ingredients, name='search_ingredients') And in my view, I defined the following function: def search_ingredients(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text = '' ingredients = Ingredient.objects.filter(title__contains=search_text) return render('search_ingredients.html', {'ingredients' : ingredients}) I'm getting a 404 error on my request, can someone help me out? -
ugettext_lazy not working in model choices when using format functions
I am trying to translate choices from my models.py from django.utils.translation import ugettext_lazy as _ GRID_LEVEL = [(None, 'null')] for r in range(-15, 15): text = _('Level %s') % str(r) GRID_LEVEL.append((str(r), text)) I have tried brackets and %(var)s syntax but still no luck. Any help would be appreciated -
<myObject> object is not iterable, Django REST Framework
I'm getting the following error when posting a new Product to my application Traceback (most recent call last): File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/mixins.py", line 20, in create serializer.is_valid(raise_exception=True) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 236, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 434, in run_validation value = self.to_internal_value(data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 488, in to_internal_value validated_value = field.run_validation(primitive_value) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 623, in run_validation value = self.to_internal_value(data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 662, in to_internal_value validated = self.child.run_validation(item) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 436, in run_validation self.run_validators(value) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 465, in run_validators to_validate.update(value) TypeError: 'Category' object is not iterable my serializer.py from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', "name", 'products', 'categories') def to_representation(self, obj): if 'categories' not … -
Django DateField format impossible to validate and save to model
Old issue, I know. But I still could not find a working solution so I may have missed something obvious. Here is my form class AddPatientForm(forms.Form): last_name = forms.CharField(label='Nom', max_length=40) first_name = forms.CharField(label='Prénom', max_length=40) birthday = forms.DateField(label='date de naissance', widget=forms.DateInput(format='%d/%m/%Y',attrs={'placeholder': '31/03/1989'}), input_formats=['%d/%m/%Y',]) It follows this format convention and has to do so. Here is my model: class Patients(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) birth_date = models.DateField() inscription = models.DateTimeField(auto_now_add=True) And here is what I tried in setting.py to get rid of the issue DATE_FORMAT = "d-m-Y" DATE_INPUT_FORMATS = ['%d-%m-%Y'] USE_L10N = False Despite of this, I still got the same issue: form = AddPatientForm(request.POST) if form.is_valid(): form.clean() d = Patients(first_name= form["first_name"].value(), last_name= form["last_name"].value(), birth_date= form["birthday"].value()) d.save() >>>>["Le format de date de la valeur «\xa027/10/1987\xa0» n'est pas valide. Le format correct est AAAA-MM-JJ."] [disclaimer] I am not looking to override the model format convention and I know that the question of how dates "are really stored in db" is irrelevant (different from one DBMS to an other; django models are agnostic about it). But that's such a pin in the *** to struggle with such a simple task. Why can't I: use different format for forms and models? override somehow … -
Python - ImportError: No module named site
I recently upgraded to the latest version of Python (3.7.1) for Windows. When I enter the command "python" in the command line I get the following error: ImportError: No module named site. The py command does work however. py example.py will execute regular python files and PyCharm works perfectly. It has become an issue recently because when I go to launch the py manage.py runserver command for Django I get the error. Any help is appreciated. -
Django change Models relations depending on condition (if is staff or not)
I have 2 Moles, User and Account. The User can be staff or normal User. In general a User can have just one Account. This is what I have now: class User(AbstractBaseUser): account = models.OneToOneField(Account, null=True, on_delete=models.CASCADE) but in special cases an User can have multiple or no Account, only if the User is_staff. The logic is to have now a ForeignKey: class User(AbstractBaseUser): account = models.ForeignKey(Account, on_delete=models.CASCADE) But in this case, how do I stop in Django Admin or else, for a User to have multiple Foreign keys if is not staff, and force it for normal users to have a simulated OneToOne Relation. -
django 2.1.3 'django.db.backends.postgis' isn't an available database backend
I am trying to use geodjango for a project. Before I use geodjango I'm trying to do a learn it from the following tutorial: https://docs.djangoproject.com/en/2.1/ref/contrib/gis/tutorial/ I originally had django 1.11 installed and tried following that tutorial (stupid of me). However, after uninstalling django 1.11 and installing django 2.1.3 I am encountering some errors. After I make the model according to the tutorial, I use the command python3 manage.py makemigrations I end up getting the following error: Traceback (most recent call last): File "/home/aihoque2/.local/lib/python3.6/site- packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.db.backends.postgis' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/aihoque2/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aihoque2/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/aihoque2/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) … -
Python - Get just the values without the fields queryset
I have this def in my views.py: def listar_animais(request, pk): vacas_no_lote = Animal.objects.filter(id_lote=pk, status=True, sexo=Sexo.F).values('id_animal', 'id_lote', 'id_raca') return JsonResponse({ 'data' : list( vacas_no_lote )}) And I'm getting this return in JSON: { "data": [ { "id_animal": 2, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 4, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 5, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 9, "id_brinco": 5456, "id_raca": 1 } ] } But I just want values, like this: { 'data': [ ['1', '5471', 'Angus'], ['3', '5547', 'Nelore'], ['8', '6874', 'Brahman'] ] } I need in this format because it's how will work with jQuery Datables as explained here: https://datatables.net/examples/data_sources/ajax -
how to save dates into database using django?
this is my code views.py def guardar(request): if request.method == "POST": idpersona = int(request.POST.get('id')) persona = personal.objects.get(id=idpersona) idep = int(request.POST.get('dependencia')) dep = dependencia.objects.get(id=idep) idcon = int(request.POST.get('concepto')) con = concepto.objects.get(id=idcon) fecha = request.POST.get('fecha') print(fecha) db_registro = lista_registro( personal_id=persona, fecha_registro=fecha, dependencia_id=dep, concepto_id=con, descripcion=request.POST.get('descripcion'), monto=request.POST.get('monto'), ) db_registro.save() return render(request, 'registro/exito.html') Models.py class lista_registro(models.Model): personal_id = models.ForeignKey(personal, on_delete=models.CASCADE) dependencia_id = models.ForeignKey(dependencia, on_delete=models.CASCADE) concepto_id = models.ForeignKey(concepto, on_delete=models.CASCADE) fecha_realizado = models.DateField() fecha_registro = models.DateField(auto_now_add=True) descripcion = models.CharField(max_length=1000) pago_id = models.ForeignKey(pago, on_delete=models.CASCADE, default=2) monto = models.CharField(max_length=100) def __str__(self): return "===> " + self.descripcion + " <===" well my problem is that I get a NOT NULL constraint error. I get that this is a date error but I don't know how to solve this -
Django - Admin - on form change
I have a general question to the django-admin. Is it possible to react on form changes? I have a select field in my django-admin detail site. Whenever i change the data from the select field, i want to change fields which are readonly. Anybody ever dealed with this issue? Thanks and Greetings -
Django annotate days between two dates
Trying to annotate the difference between two dates as number of days. Is there a function to extract day of year from a DateField? from django.db.models.functions import ExtractDay from django.utils import timezone date = timezone.localtime(timezone.now()).date() self.annotate( age=date.timetuple().tm_yday - ExtractDay(F('date')) ) -
Django: how to get data created by redirect view into another view
I have a view authorize in my app that redirects user to external authorization page: def authorize(request): url = 'https://www.strava.com/oauth/authorize?client_id=123&response_type=code&redirect_uri=http://127.0.0.1:8000/collect&approval_prompt=force' response = redirect(url) return response This authorization page then redirectes to another view collect (which collects user's data) with user's unique code included in the URL like so: http://127.0.0.1:8000/collect?state=&code=123456. The thing is that I need to somehow pass this code to the collect view first, so the data for the user can be collected. How can I do this? -
How to leave ManyToManyField attributes selected automatically as default? Django 1.10
In the system that is part of the development, there is a field of "authors" in the models that is a ManyToManyField, in which some users of the database are extracted in which the content of the site will be published. In short, the content will only be posted to the people I choose in the "authors" field. I would like all registered authors to be selected by default if I did not choose any, and then the content would be published for all of them. If I wanted a specific author, I could select. Detail that the field is still required even though I having inserted "blank = True". #models.py class Fullimage(models.Model): authors = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=u'Autores', related_name='fullimagelinks', blank=True) -
Unable to use django-kronos
I've been testing django-kronos with the simple example listed in the github readme: I did pip3 install django-kronos, myproject/myapp/cron.py: import kronos import random @kronos.register('* * * * *') def complain(): complaints = [ "I forgot to migrate our applications's cron jobs to our new server! Darn!", "I'm out of complaints! Damnit!" ] print random.choice(complaints) In my myproject/myproject/settings.py: INSTALLED_APPS = [ 'appointments.apps.AppointmentsConfig', 'clinic.apps.ClinicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'bootstrap4', 'widget_tweaks', 'parsley', 'session_security', 'kronos' ] Ran: ./manage.py runserver I expected the dev server to throw up a message every minute. Nothing seems to be happening. I also created myproject/myapp/management/commands/task.py: from django.core.management.base import BaseCommand import kronos @kronos.register('* * * * *') class Command(BaseCommand): def handle(self, *args, **options): print('Hello, world! KRONOS is running!!') This is also not running. -
MultipleObjectsReturned- get() returned more than one mPurchase -- it returned 2
I am beginner to django. While trying to save mPurchase form I am getting MultipleObjectReturned error. I am trying to get data from form using POST request. Every time I submit the form I am getting an error. views.py def milkPurchase(request): title='Buy Milk' milk = mPurchase.objects.all() if request.method=='POST': form=mPurchaseForm(request.POST) if form.is_valid(): m = get_object_or_404(mPurchase) m.mPurchase_date=timezone.now() m.save() return redirect('milk-purchase') else: form=mPurchaseForm() context = { 'title': title, 'form': form, 'milk':milk } return render(request,'dairyapp/milk-purchase.html',context) forms.py class mPurchaseForm(forms.ModelForm): """ This form is for milk purchase """ seller=forms.CharField( label='Seller Name', max_length=50, ) mPurchase_product=forms.ChoiceField( choices=MILK_CHOICES, label='Milk Type', initial='', widget=forms.Select(), required=True ) mPurchase_qty=forms.FloatField( label='Qty' ) mPurchase_rate=forms.FloatField( label='Rate' ) class Meta: model=mPurchase fields=('seller','mPurchase_product','mPurchase_qty','mPurchase_rate',) here is my models.py class mPurchase(models.Model): mPurchase_id=models.AutoField(primary_key=True) seller=models.CharField(max_length=50) mPurchase_date=models.DateTimeField(default=timezone.now) mPurchase_product=models.CharField(max_length=10,choices=MILK_CHOICES) mPurchase_qty=models.FloatField() mPurchase_rate=models.FloatField() def __str__(self): return self.seller Can you please help me get through this? I have tried using mPurchase.objects.filter() Also, tried to catch exception using ObjectDoesNotExist and MultipleObjectReturned from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned