Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print foreign key value in template without doing a query
I have a query that I do in my view to get a bunch of team stat objects... team_stats = NCAABTeamStats.objects.filter( name__name__in=teams_playing).order_by(sort) One of the fields 'name' is a foreign key. I pass team_stats to my template to display the data in a chart via a 'for loop'. {% for team in team_stats %} <tr> <td> {{ team.name }} </td> </tr> {% endfor %} So in my template, for every object in team_stats it is doing a query when it prints {{ team.name }} and it really slows things down, especially when there are 50-100 teams. My question is, is there a way to print 'team.name' without it doing a query every time? -
onchange select works after second time - jquery - django
I'm trying to show some data base on selected data in a drop down field , the form is formset dynamic (modelformset_factory) but it calls back the data two times , and doesnt calls back any data in the first selection , in the second time then return the data ! and in the python function returns nothing as well at the first selection , in the second selection returns the data two times ! here is my views.py code @login_required def return_back_imei_oddinfo(request): query = request.GET for item in query: if item.startswith("imei-") and item.endswith("-item"): item_id = query.get(item) print(item) break selling_price= Imei.objects.get(id=item_id).mobile.selling_price, data = { 'selling_price' : selling_price, 'mobile':mobile, 'giga':giga } return JsonResponse(data) forms.py class ImeiInvoiceForm(forms.ModelForm): item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo(this);'})) class Meta: model = ImeiInvoice fields = ['item','price'] and here is my template function imeiInfo () { $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_oddinfo/', data:data, success:function(data){ console.log(data.selling_price) if (data){ elm.closest("div.child_imeiforms_row").find("input.price").val(data.selling_price); } else{ alert('not inserted') } } }) }) } imeiInfo(); {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | … -
Django: norm for handling un-created OneToOneFields
Here's an example model: class User(models.Model): ... Later, I want to add an Invite OneToOne model: # This is arbitrarily named. class InviteCode(models.Model): user = models.OneToOneField(User, related_name="invite_code") ... # signals.py @receivers(signals.post_save, sender=User) def create_invite_code(sender, instance, created, **kwargs): if created: invite_code = InviteCode.objects.create(user=user) Now, for new users I can conveniently do user.invite_code for any new users. Is there any standard way to handle this for old users? There seem to be many possible solutions, but none of them seem very clean: I could try: catch RelatedObjectDoesNotExist every single time I use user.invite. This isn't great and seems very unclean. I could create an accessor method, like get_invite_code which does the try/catch, and always fetch the user.invite_code via user.get_invite_code() I could run a migration, such that all old users have an Invite Code created, and all new users have an invite code object via the signal. Anyone have any suggestions on the most pythonic way to handle this? -
How to send Email without using settings.py ? (smtp parameters in database)
I would like to be able to send emails with django but without using the email parameters in settings.py. (EMAIL_HOST, EMAIL_USE_TLS, EMAIL_HOST_PASSWORD, etc ...) These parameters are stored in db because they can be different depending on the user. How to use these parameters in base to send emails and not those in settings.py ? class EmailThread(threading.Thread): """ Class email (Thread) """ def __init__(self, subject, html_content, recipient_list): self.subject = subject self.recipient_list = recipient_list self.html_content = html_content threading.Thread.__init__(self) def run (self): msg = EmailMessage(self.subject, self.html_content, settings.EMAIL_HOST_USER, self.recipient_list) msg.content_subtype = "html" msg.send() def send_html_mail(subject, html_content, recipient_list): """ send an email asynchronous """ EmailThread(subject, html_content, recipient_list).start() I can get the parameters using: email_params = EmailParameter.objects.get(user=request.user) class EmailParameter(models.Model): email_use_tls = models.BooleanField(_("email use tls"), default=True) email_use_ssl = models.BooleanField(_("email use tls"), default=False) email_host = models.URLField(_("email host"), max_length=200) email_host_user = models.CharField(_("email host user"), max_length=200) email_host_password = models.CharField(_("email host password"), max_length=200) email_port = models.PositiveIntegerField(_("email port")) default_from_email = models.EmailField(_("default from email"), max_length=200) signature = models.TextField(_("signature")) user = models.ForeignKey( User, verbose_name = _("user"), related_name = "user_email_parameter", on_delete=models.CASCADE ) -
Django ImageField get username
models.py def upload_to(instance, filename): return 'verify/%s/%s' % (instance.user_idx.username, filename) class UserVerifyImg(models.Model): user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) business_type = models.CharField(max_length=255) image = models.ImageField(upload_to=upload_to) upload_date = models.DateTimeField(auto_now = True) class Meta: managed = False db_table = 'account_user_verify' This is my model. but It is showed me error. account.models.UserVerifyImg.user_idx.RelatedObjectDoesNotExist: UserVerifyImg has no user_idx. I don't now what is the problem. help me please. -
Annotate and aggregate by month Django queryset?
I have a model where I would like sum a specific field by month and would like to do it in a single query. e.g I would feed in a date range and this would filter the queryset. Then I would like to be able to aggregate by month for that queryset. My current implementation produces a total aggregate instead of aggregating by month. Is there a better way to approach this problem? def reading_by_month(queryset): return queryset.annotate(month=TruncMonth('reading_date')).values('month').annotate(total=Sum('reading')) -
Handling forms from class based view
Hello how can I pass form into template from class based view? In HTML everything inherits and I can render elements inside block content but I can not render form. This is my code. : views.py: class Signup(TemplateView): model = Profile template_name = 'home/sign-up.html' form_class = UserCreationForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = UserCreationForm HTML: {% extends "home/todo.html" %} {% block content %} <form method="POST"> {{form}} </form> {% endblock content %} -
how can i avoid no reverse match in django
idk why this error occurred no revers match this code is a practice . it 3 part : 1_home 2_shops 3_pizza i modified shops.html code to link pizza but after this modifying this error occrrued Reverse for 'pizza' with arguments '('',)' not found. 1 pattern(s) tried: ['shops/(?P<pizza_id>[0-9]+)$'] first code : <ul> {%for shop in shops%} <li> {{shop}} </li> second code: <ul> {%for shop in shops%} <li> <a href="{% url 'pizzas:pizza' pizza.id %}">{{shop}}</a></li> i paste all codes in pastebin if needed: https://pastebin.com/u/Nicolas_Darksoul/1/KUBPPDTG -
Django: web model form: Question followed by radio-buttoned answers
1.OBJECTIVE. Roll out a web model-based form with questions and their possible radio-button answers. i can't get it formatted with ctrl-k Model: class Question(models.Model): description = models.TextField(max_length=2000) def str(self): return self.description class Answer(models.Model): answer = models.TextField(max_length=2000) fk_question_id = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE) def __str__(self): return self.answer VIEW: def formulario(request): form = FormularioForm() return render(request, "formulario.html", {'form': form}) HTML TEMPLATE: {{form}} WHAT I HAVE TRIED: The file below forms.py displays the whole rollout of querysets of questions followed by all of the answers. Naturally we want alternating question answers, question answers... It does not work because it needs to be splitted somehow and dealt separately in the template. FORMS.PY Answer = forms.CharField(label=Question.objects.all(),widget=forms.RadioSelect(choices=RESPUESTAS)) RESPUESTAS is simply a list of tuples. I noticed that this is what choices seems to take as imput so I created such list from Answer.objects.all() and zipping it onto itself SO, QUESTIONS: A) the forms.py needs to have splitted queries for question and answers. The html.template should work with this. The visual I have in my mind is a Django representation of this: SELECT description, answer, fk_question_id_id FROM Answer JOIN Question on answer.fk_question_id = question.id but which has to have the html formatting for radio buttons something like: for … -
I gave a command django-admin but i got error
getting this error I gave command django-admin program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException``` -
how to get data from html form into a json format
I am building an ecommerce site. so, i created a billing form, and in that form, i want to collect stuffs like email, address etc and pass it into a json format so i'll pass it to the payment gateway. I tried creating it in a variable and passing it, but on the payment gateway redirectedmodal form, it is saying invalid email input Code const publicKey = "{{ key }}"; var email = document.getElementById('email').value; var fullname = document.getElementById('fullName').value; var address1 = document.getElementById('custAdd').value; var address2 = document.getElementById('custAdd2').value; var country = document.getElementById('country').value; var state = document.getElementById('state').value; var address1 = document.getElementById('postCode').value; function payWithRave() { var x = getpaidSetup({ PBFPubKey: "xxxxxx", email: email, amount: '{{cart.get_total_price}}', customer_phone: "234099940409", currency: "USD", address: 'address1', address2: 'address2', country: 'country', state: 'state', postcode: 'postCode', }) <div class="col-sm-7"> <label for="firstName" class="form-label">Full Name</label> <input type="text" class="form-control" id="fullName" placeholder="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-12"> <label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" id="email" placeholder="you@example.com"> <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-12"> <label for="address2" class="form-label">Address 2 … -
How to saving multiple forms also has cloned forms in django?
views.py @login_required def add_product(request): productform = ProductForm() variantsform = VariantsForm() productvariantsform = ProductVariantsForm() if request.method == 'POST': productform = ProductForm(request.POST, request.FILES) variantsform = VariantsForm(request.POST, request.FILES) productvariantsform = ProductVariantsForm(request.POST, request.FILES) if productform.is_valid(): product = productform.save(commit=False) vendor = CustomUser.objects.filter(id=request.user.id) print(vendor) product.vendor = vendor[0] product.slug = slugify(product.product_name) product.save() if variantsform.is_valid(): variantsform.save() #finally save if productvariantsform.is_valid(): productvariantsform.save() #finally save return redirect('vendor:vendor-admin') else: return HttpResponse("Nothing submitted...") else: productform = ProductForm variantsform = VariantsForm() productvariantsform = ProductVariantsForm() return render(request, 'vendor/add_product.html', {'productform': productform, 'variantsform':variantsform, 'productvariantsform': productvariantsform}) add_product.html <div class="container mt-5" id="p"> <h1 class="title">Add Product</h1> <div class="card" style="width: 38rem;"> <form method="POST" action="{% url 'vendor:add-product' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-lg-12 col-md-12"> {{ productform.vendorid|as_crispy_field }} </div> <div class="col-lg-12 col-md-12"> <a id="vendor_id_search" class="btn btn-info mt-4">search</a> </div> </div> <div id="show_vendorname"> </div><br> {{ productform.maincategory|as_crispy_field }} {{ productform.productcategory|as_crispy_field }} {{ productform.subcategory|as_crispy_field }} {{ productform.product_name|as_crispy_field }} {{ productform.brand_name |as_crispy_field }} <br> <div> <p></p> </div> <hr> <div id="order-details-booking"> <div class="row"> <div class="form-holder"> <div class="col"> <h1>Variant Form</h1> {{ variantsform.variant_type|as_crispy_field}} {{ variantsform.variant_value|as_crispy_field}} {{ productvariantsform.price|as_crispy_field}} {{ productvariantsform.initial_stock|as_crispy_field}} {{ productvariantsform.weight_of_product|as_crispy_field}} <div class="input-group mb-3"> <label class="input-group-text" for="upload_file">Upload Images</label> <input type="file" id="upload_file" onchange="preview_image();" multiple class="form-control"> </div> <div id="image_preview"></div> {% comment %} {{ productvariantsform.images|as_crispy_field}} {% endcomment %} {{ variantsform.sleeve|as_crispy_field }} {{ variantsform.material|as_crispy_field }} {{ variantsform.neck|as_crispy_field }} <div class="col s1"> … -
how to use local host server for domain django
my problem seems to be a funny one...... i'm developing a django ecommerce app. the problem is that when the link for activation of a user account is sent on the console, instead of getting my local server as an domain e.g http://127.0.0.1:8000/account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ i get http:// example.com /account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ instead -
Adding settings to settings.py - Django
I'm following this Django Tutorial to add photos to my Django webpage. It says to put the following codes into my settings.py. However, I'm sort of confused because I know the two "span class" lines are definitely not Python codes. Therefore, does anyone know what I should do? Do I just include the two Python codes instead? span class="hljs-comment"> # Base url to serve media files</span> MEDIA_URL = <span class="hljs-string">'/media/'</span> <span class="hljs-comment"> # Path where media is stored</span> MEDIA_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'media/'</span>) Thanks in advancd! -
Password not hashing while using Django Rest Framework and Custom User Modelh
Problem: I needed a backend for authenticating with phone number and I decided to make it in Django. I am using Django Rest Framework for API and Custom User Model. When I create a user using Django Admin, the password is hashed and I can log in using the login API I created. But when I create a user using API ( created using DRF ) the password is not hashed due to which I am not able to log in. Note: I am using KNOX authentication for token authentication but that is working fine and I do not think that that is the problem Project Structure ( only files that are needed are included ): server\ accounts\ admin.py forms.py models.py serializers.py urls.py views.py server\ settings.py urls.py manage.py Code: # settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: … -
502 occurs when creating environment on elastic beanstalk
I'm having an issue deploying my first Django project. Here's my config.yml: global: application_name: testapp branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application And here's my django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: djangoproject.wsgi:application I have followed this doc. But after I did eb create testapp-env, I get 502 error: image of the error I will provide further information if you need. Thank you in advance for your help. -
HTML audio tag play button is greyed out on Django project
For some reason the play button is greyed out on my Django website. I used this same exact HTML code in a blank HTML document and it worked as it should, so I don't think there's a problem finding the file, or a syntax error. While running the server locally I am not seeing any errors in the command line either. How it looks on blank HTML file How it looks on website Code: <audio src="C:\Users\zach2\music\download.mp3" controls> </audio> Is there something that I need to change in one of the Django files to enable audio to work properly? I am very new to Django and Web development so please forgive my ignorance. If you want to see another file please let me know and I will update the post ASAP. Thank you. -
Save Temporary Data in Django
Is there any way to save temporary data in django framework? For example I need to save temp notices in a table, with expiration date. To give a better example, I have a table called product and in this table there are several fields such as: title, description, notices and others... is it possible to create a product with a temporary notice? like, this product has this notice until tomorrow. -
Question about the location of the git repository when deploying Django project on Elastic Beanstalk
i'm new in both python and elastic beanstalk. Here's my file structure: /.git # <- here's my git repo /my-first-django |-- django-project |-- app |-- django-project | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py /venv When I read this doc, I can see they create git repository at the same level as django-project. Should I move the repository? Or am I fine with my current structure when deploying with awsebcli? Thank you for your help! -
Need Serialize a custom filed AVG notes for my API in Django
models.py from django.db import models from django.db.models import Avg from users.models import UserProfile from subjects.models import Subject class Note(models.Model): id_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='user_note') id_subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='subject_note') exam_note = models.IntegerField() @property def average_note(self): if hasattr(self, '_average_note'): return self._average_note return Note.objects.aggregate(Avg('exam_note')) Thats my Note models and i need to calculate the notes average to serialize it and send in request resonse views.py class AvgNoteViewSet(viewsets.ModelViewSet): serializer_class = AvgSerializer authentication_classes = (TokenAuthentication,) permission_classes = (NotePermissions,) def get_queryset(self): return Note.objects.all().annotate(_average_note=Avg('exam_note')) And that is my get_queryset redefined method to calculate de average notes, but im just having a list of notes for result of that query, like that: resques response serializers.py class AvgSerializer(serializers.ModelSerializer): """ Serializes a notes AVG """ average_note = serializers.SerializerMethodField() def get_average_note(self, obj): return obj.average_note class Meta: model = Note fields = ['average_note'] And this is my serializer My intencion is try to get an avergate from the exam_notes from the logged user, so i understand that i need to try to group by user_id ant then agregate the average. This is my postgresql table from when im querying: notes_table I based my code from How to calculate average of some field in Django models and send it to rest API?, … -
Django database information doesn't exist when deployed to Heroku
I recently deployed a django rest api to heroku and the database is not working properly. When trying to log in, it seems that the user object that was in my sqlite database in my own files does not exist and therefore it tells me that my credentials are invalid. Does anyone know how to make it so that the database data gets uploaded to Heroku? Here is my Procfile: release: python manage.py makemigrations --no-input release: python manage.py migrate --no-input web: gunicorn rrt.wsgi Here are my Django settings: DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'articles', 'author_auth', 'authors', 'threads', 'category', 'rest_framework', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', 'ckeditor', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = 'rrt.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'rrt.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # … -
how to change images in boostrap's example?
I am a rookie of html. My English is also poor. Just download the bootstrap-v4 examples. One of the examples is carousel, but i don't kown which place in codes to change the images. And I don't understander the meaning of code below. Who can help me would be much appreciated. example's link :https://v4.bootcss.com/docs/examples/ .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style>``` -
Django how to show many2many extra fields in a form?
here are my models.py: class EssentialOil(models.Model): name = models.fields.CharField(max_length=120, verbose_name="Nom") latin_name = models.fields.CharField(max_length=120, verbose_name="Nom latin") abbreviation = models.fields.CharField(max_length=8, verbose_name="Abbréviation") image = models.fields.CharField(default=None, null=True, blank=True, max_length=255, verbose_name="Photo") administrationmodes = models.ManyToManyField('AdministrationMode', through="EssentialOil_AdministrationMode", verbose_name="Mode d'administration") components = models.ManyToManyField('Component', through="EssentialOil_AdministrationMode", verbose_name="Composants") warnings = models.ManyToManyField('warning', through="EssentialOil_AdministrationMode", verbose_name="Points d'attention") properties = models.ManyToManyField('property', through="EssentialOil_AdministrationMode", verbose_name="Propriétés") uses = models.ManyToManyField('use', through="EssentialOil_AdministrationMode", verbose_name="Utilisations thérapeuthiques") class Meta: ordering = ['name'] def __str__(self): return self.name class AdministrationMode(models.Model): mode = models.fields.CharField(max_length=100, verbose_name="Mode") description = models.fields.CharField(max_length=2000, verbose_name="Description") warning = models.fields.TextField(max_length=2000, default="Aucun", verbose_name="Point d'attention") eo = models.ManyToManyField(EssentialOil, through='EssentialOil_AdministrationMode', blank=True, verbose_name="H.E. concernées") class Meta: ordering = ['mode'] def __str__(self): return self.mode class EssentialOil_AdministrationMode(models.Model): class Efficiency(models.IntegerChoices): RARE = 1 PARFOIS = 2 SOUVENT = 3 IDEAL = 4 eo = models.ForeignKey("EssentialOil", null=True, on_delete=models.CASCADE) am = models.ForeignKey("AdministrationMode", null=True, on_delete=models.CASCADE) co = models.ForeignKey("Component", null=True, on_delete=models.CASCADE) pr = models.ForeignKey("Property", null=True, on_delete=models.CASCADE) us = models.ForeignKey("Use", null=True, on_delete=models.CASCADE) wa = models.ForeignKey("Warning", null=True, on_delete=models.CASCADE) efficiency = models.IntegerField(Efficiency.choices) class Meta: unique_together = [['eo', 'am']] My forms.py: from django import forms from django.forms import ModelForm from .models import EssentialOil, AdministrationMode, Component, Warning, Property, Use class CreateEssentialOil(ModelForm): class Meta: model = EssentialOil fields = "__all__" administrationmodes = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=AdministrationMode.objects.all(), label="Mode d'administration") components = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Component.objects.all(), label="Composants") warnings = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Warning.objects.all(), label="Points d'attention") properties = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Property.objects.all(), … -
update_create is creating new feilds instead of updating total
payments = list((expense .annotate(month=Month('startDate')) .values('month') .annotate(total=Sum('cost')) .order_by('month'))) for i in payments: paymentMonths = (i["month"]) paymentTotal= (i["total"]) obj, created = Payment.objects.update_or_create( author=curruser, date=paymentMonths, total = paymentTotal, defaults={"total": paymentTotal}, ) totalcost = Payment.objects.filter(author = curruser.id) Apparently, it should update the (date = 12) total but it is making new ones with the updated value, it might be because the totaldate is diff or maybe I'm wrong it is confusing -
Django, url not found 404
Project Folder structure I am new to django. I am trying to create a simple rest api end point, but I get a 404. I am sure I am missing some setting. models.py class DisplayItems(models.Model): yesNo = models.CharField(max_length=10) yogaMessage = models.CharField(max_length=50) yogaTimeMessage = models.CharField(max_length=100) @classmethod def create(cls, yesNo, yogaMessage, yogaTimeMessage): displayItems = cls(yesNo=yesNo, yogaMessage=yogaMessage, yogaTimeMessage=yogaTimeMessage) return displayItems serializers.py from .models import DisplayItems class DisplayItemsSerializer(serializers.ModelSerializer): yesNo = serializers.CharField(max_length=10) yogaMessage = serializers.CharField(max_length=50) yogaTimeMessage = serializers.CharField(max_length=100) class Meta: model = DisplayItems fields = ('__all__') urls.py from .views import DisplayItemsViews from django.contrib import admin urlpatterns = [ path(r'^admin/', admin.site.urls), path(r'^zzz/', DisplayItemsViews.as_view()), ] views.py from rest_framework.response import Response from rest_framework import status from .serializers import DisplayItemsSerializer from .models import DisplayItems class DisplayItemsViews(APIView): def get(self, request): displayItems = DisplayItems.create("YES!", "There's yoga today", "At 2:00 pm Eastern Time") serializer = DisplayItemsSerializer(displayItems) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) The url I am trying to run is http://127.0.0.1:8000/zzz/ I have read almost all relevant stackoverflow posts, but can't seem to understand what I am missing.