Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change Django default URL
first sorry for my bad English When I run my server, I want to Django redirect me to http://127.0.0.1:8000/home instead of http://127.0.0.1:8000. what should I do? -
SweetAlert in Django not appeared No JavaScript reporting
I started learning Django by following a YouTube tutorial. Everything seems to be fine, the only thing that is not working is a short script at the end of the template, which is unfortunately not working: <!-- MESSAGESS FROM BACKEND --> {% for messagge in messagges %} {% if messagge.tags == 'success' %} <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> var m = "{{ messagge }}"; swal("Perfect!", m, "success"); </script> {% endif %} {% endfor %} </div> <!-- END OF CONTAINER DIV --> {% endblock content %} -
how to save django data in to tow model
hi please help me i have to model i want after create and save store the result save to main store like this store.name == mainstore.name store.the_rest_of_quantity==mainstore.quantity i trying to use signals but i fail class Store(models.Model): CHOICES = ( ('NUM','number'), ('M','meter'), ) name = models.CharField(max_length=60) quantity = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True) date_of_add = models.DateTimeField(auto_now_add=True) add_new_item = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True) date_of_remove = models.DateTimeField(auto_now =True) remove_old_item = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True) the_rest_of_quantity = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True) accept_stor = models.BooleanField(default = False) classyfiyed = models.CharField(max_length=3,choices=CHOICES,blank=True,null=True) def __str__(self): return 'Device Name :( {0} ) Have Quantity({1}) '.format(self.name,self.quantity) def save(self, *args, **kwargs): try: totla_sum = sum([self.quantity , self.add_new_item]) self.the_rest_of_quantity = int(totla_sum - self.remove_old_item) except Expression as identifier: 'you add remove bigger than quantity' return super().save(*args, **kwargs) class MainStore(models.Model): name = models.CharField(max_length=120) quantity = models.PositiveIntegerField (null=True,default=0) store = models.OneToOneField(Army,on_delete=models.CASCADE,related_name='Store',null=True) -
Why do i keep getting UTC time zone even when Django settings is configured differently
I'm not sure why the datetime response is always one hour behind (UTC) Django settings configuration LANGUAGE_CODE = "en-us" TIME_ZONE = "Africa/Lagos" USE_I18N = True USE_L10N = True USE_TZ = True DATE_FORMAT = "F j, Y" SITE_ID = 1 from django.utils import timezone timezone.now() response: datetime.datetime(2022, 7, 23, 13, 58, 6, 739601, tzinfo=<UTC>) You can see that the time zone info is UTC -
Exception Value: 'tuple' object has no attribute 'backend'
Also I got this error 'tuple' object has no attribute 'backend' when I do @login_required(login_url = "/oauth2/login") But when I just go to /oauth2/login all works fine. -
How can i use await async function in Django view function?
in my django project, I want the function that generates the returned result not to process the other request before it ends. How can I provide this? views.py def orderresult(request): if request.method == 'POST': username = request.POST["username"] order = request.POST["order"] doubleResult = ResultsFormView(order,username).resultview() # ====> Async await function result = doubleResult[0] boolresult = doubleResult[1] context = { "result" : result, "boolresult" : boolresult } return render(request, 'npages/result.html', context=context) I tried something like this but it doesn't work. async def orderresult(request): if request.method == 'POST': username = request.POST["username"] order = request.POST["order"] doubleResult = await ResultsFormView(order,username).resultview() # ====> Async await function result = doubleResult[0] boolresult = doubleResult[1] context = { "result" : result, "boolresult" : boolresult } return render(request, 'npages/result.html', context=context) -
Django-Oscar Unable to Customise ProductCreateUpdateView and ProductForm - Traceback: ProductForm.__init__() missing 1 required positional argument
I am working on a web shop using Django-Oscar. I want to customise the page which creates a new product, and show different sets of attributes on the page depending on the product's metal type (which has been selected before this page is created - see below image). But I am getting the Traceback ProductForm.__init__() missing 1 required positional argument: 'metal'. Desired Output: Traceback Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/contextlib.py", line 79, in inner return func(*args, **kwds) File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/oscar/apps/dashboard/catalogue/views.py", line 218, in dispatch resp = super().dispatch( File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 190, in get return super().get(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "/usr/local/lib/python3.10/site-packages/oscar/apps/dashboard/catalogue/views.py", line 274, in get_context_data ctx = super().get_context_data(**kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /dashboard/catalogue/products/create/earrings/gold/diamond Exception Value: ProductForm.__init__() missing 1 required positional argument: 'metal' Views from django.views.generic import CreateView, … -
How to render forms based on selected settings in django
I want to render forms based on selected settings. I have a journal type below: class Journal(models.Model): journalsId = models.AutoField(primary_key=True) name = models.CharField(max_length=500) acname = models.CharField(max_length=100) issnprint = models.CharField(max_length=500) issnonline = models.CharField(max_length=500) logo = models.ImageField(null=True, blank=True, upload_to="images/journals/") msg = models.CharField(max_length=500) status = models.BooleanField(default=True) c1_form_checkbox = models.BooleanField(default=True) c2_form_checkbox = models.BooleanField(default=True) c3_form_checkbox = models.BooleanField(default=True) . . c19_form_checkbox = models.BooleanField(default=True) Each C*_form is a html file. Lets say I have below Journal Types: A -> 5 random Checboxes are selected B -> 10 random Checkboxes are selected How can I render these C*_form.html in order? Thanks -
How do I import from current app in Django without using the app name?
My app is full of statements like this: from my_app.model import Customer While it works, I'll like to have a way to reference the current app without hard coding the app name into the import. Something like: from keyword_for_current_app.model import Customer Is there a clean way of achieving this with Django? -
in django ecommerce product price change according to size and color
What should I do for changing price according to product size and color. in models.py , views.py and also product_detail.py code class color class size class variation what should I do next in view and detail page -
Best way to store and display warning messages using Django?
I'm looking for the best and easiest way to store and to display warning messages shown to the user at the creation or at the update of instances of some models. I want users to tick a box (or to click twice) to be 100% sure that they are aware of what they are doing. I want the warnings to be saved in the database if and only if they have been read. My current solution on the client side Currently, on the front-end side, this is how it looks like: But I'm not totally satisfied with this homemade interface because it still lacks some JS functions to update/hide the warning(s) when the input changes, without waiting for the user to resubmit the form. I guess I could write them or draft a dedicated validation page but I wonder if there isn't a library or a framework that could partially do the job. My current solution on the server side For now, on the back-end side, I use a parent abstract class with a custom JSONField keeping track of that information: class AbstractBase(models.Model): warnings: dict = models.JSONField( default=dict, validators=[JSONSchemaValidator(limit_value=WARNINGS_JSON_SCHEMA)], ... ) ... Along with these few lines of code, I … -
Constantly problems with Python: Python was not found, can't open file…,
For unknown reasons, I started to have constantly failures with python. I started yesterday, not sure if I have a relation, but I installed Docked with WSL 2 Linux kernel, and PostgreSQL recently too. The first problem, all my paths were deleted. I wrote again: C:\Users\user\AppData\Local\Programs\Python\Python310\Scripts After, it starter to appear in the console: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. After trying to fix it, uninstall Python completely and reinstall it. Show me something about getting from Microsoft Store. I did, I reinstalled Django and I added too new path which was recommended: C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts Started to work again (yesterday), but today it's not working again with this message: C:\Users\user\AppData\Local\Microsoft\WindowsApps\python.exe: can't open file 'D:\code\proyectWeb\manage.py': [Errno 2] No such file or directory It's like each new day, the python installation gets corrupted or something, and start to make me crazy. If anyone had similar problems or can have an idea about what is going on, I would greatly appreciate your help, thanks. I have Windows 10, and the last versions of python, django and pip, because I updated after the first problems. After many … -
What exactly does X_FRAME_OPTIONS = 'SAMEORIGIN'?
I created a site in Django that I deployed on heroku. I am looking to display this site in an iframe in an html page present on my localhost. Which is not done, because the default value of X_FRAME_OPTIONS is DENY which don't autorize this. When I search the internet, I am asked to replace the value DENY with the value SAMEORIGIN. I learned about the official Django documentation from this passage: Modern browsers respect the X-Frame-Options HTTP header which indicates whether a resource is allowed to load inside a frame or iframe. If the response contains the header with a value of SAMEORIGINthen the browser will only load the resource in a frame if the request comes from the same site. What I don't understand is that I'm looking to load a site that's on the web from a web page that has an iframe in it and I'm wondering if they mean by this passage in the doc that the site can be loaded by a web page present on the computer that deployed it or can one of the web pages present on the deployed site load it in an iframe, something that I do not understand … -
How do I resolve typeError: unsupported operand type(s) for /: 'str' and 'str' in django app by heroku?
When I deployed django app by heroku, I got error. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) Setting.py has this BASE_DIR. How do I resolve this error? Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 386, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/MovieReview/settings.py", line 77, in <module> 'DIRS': [BASE_DIR / 'templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' -
Django querysets using __lte
Can I do something like this in django/python without hardcoding it? def get_rating_average(self, type): return list(super().aggregate(Avg(type)).values())[0] def filter_rating_average_under(self, type): return super().filter(type__lte=self.get_rating_average(type=type)) # FILTER WHERE rating_type is smaller than average type keyword# #In my views.py I call something like this: context['item8'] = Stock.aggregators.filter_rating_average_under(type='mykeyword') I dont want to hardcode a keyword into a field so is there a way to format this code? So that {type}__lte works and I can run this query with different keywords instead of only one? -
Model constraint on checking existing relationship between two fields
I'm writing a Django app and I want Users to be able to review Courses. The Users have to select the Professor they are reviewing when creating a Review, because multiple Professor can teach that single Course. I created a Taught table that keeps the relations between Professors and Courses. How do I enforce that when I'm adding a review, I will only be shown in the dropdown of professors, the professors which have an existing relationship with that course (only the professors which have taught the course). class Professor(models.Model): name = models.CharField() class Course(models.Model): name = models.CharField(max_length=200) professor = models.ManyToManyField(Professor, through="Teaches", related_name='taughtBy') class Teaches(models.Model): course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name="reviews_course") professor=models.ForeignKey(Professor,on_delete=models.CASCADE,related_name="reviews_professor") class Review(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,related_name="is_author") course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name="reviews_course") professor = <<<<How do I enforce that professor and course have to have an existing relationship in Teaches?>>>> -
Setting css class to field in form depending of it's type
I want to manually render login and signup forms in Django. Here is my code: {% load widget_tweaks %} {% for field in form.visible_fields %} <div class="field"> <label class="label">{{ field.label_tag }}</label> <div class="control"> {% if form.is_bound %} {% if field.errors %} {% render_field field class="nice-looking-field"%} {% for error in field.errors %} {{ error }} {% endfor %} {% else %} {% render_field field %} {% endif %} {% else %} {% render_field field %} {% endif %} {% if field.help_text %} <p>{{ field.help_text }}</p> {% endif %} </div> </div> {% endfor %} {% if form.non_field_errors %} <div class="box"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} My question: is it possible to check in a loop what type the field has and depending on the field, assign a specific css class? For example: Field_1 has type text, so we apply css-class-1 to it Field_2 has a checkbox type, so we apply css-class-2 to it -
permission_required for user who only users who are part of a group ,in view based class
Based on a tutorial,i have a view with a restriction on the display of data, based on a permission of the form "book.can_view" in class BookDetailView This works, but the probleme are every user not have access to the view I'd like to do the same thing but using the group name. . I would like only users who are part of a group named "premium" to have access to this page my views.py from django.shortcuts import render from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from catalog.models import Book, Author, BookInstance, Genre from accounts.models import CustomUser from django.views.generic import ListView, DetailView class BookListView(ListView): model = Book paginate_by = 10 #permission_required = 'catalog.view_book' def index(request): # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter( status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class BookDetailView(PermissionRequiredMixin, DetailView): """Generic class-based detail view for a book.""" model = Book template_name = "catalog/permission_required.html" permission_required = 'book.can_view'# change this … -
Wagtail API not exposing custom field
I am enabling wagtail api v2 in my wagtail project. After adding the api.v2 I am getting this json response { "id": 32, "meta": { "type": "blog.AddStory", "detail_url": "http://localhost/api/v2/pages/32/", "html_url": "http://localhost/blog/1st-story/", "slug": "1st-story", "first_published_at": "2022-07-19T18:06:50.205210Z" }, "title": "1st story" } I want to add my content field after title field. I added this in my models.py file from wagtail.api import APIField from rest_framework import serializers #Exposing Custom Page Fields/content api_fileds = [ APIField('content'), APIField('custom_title'), APIField('blog_image'), ] Here is my api.py file from wagtail.api.v2.views import PagesAPIViewSet from wagtail.api.v2.router import WagtailAPIRouter from wagtail.images.api.v2.views import ImagesAPIViewSet from wagtail.documents.api.v2.views import DocumentsAPIViewSet api_router = WagtailAPIRouter('wagtailapi') api_router.register_endpoint('pages', PagesAPIViewSet) api_router.register_endpoint('images', ImagesAPIViewSet) api_router.register_endpoint('documents', DocumentsAPIViewSet) Why it's not exposing custom fields? Here is my full models.py file """Blog listing and blog detail pages.""" from django.db import models from modelcluster.fields import ParentalManyToManyField from django import forms from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel,InlinePanel from wagtail.core.fields import StreamField #Api Section import from wagtail.api import APIField from rest_framework import serializers from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.core.models import Page from wagtail.snippets.models import register_snippet from . import blocks from .blocks import InlineVideoBlock from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase @register_snippet class BlogCategory(models.Model): """Blog category for a snippet.""" name = models.CharField(max_length=255) … -
amadeus Ajax airport search autocomplete not working python
trying this code available here https://developers.amadeus.com/blog/django-jquery-ajax-airport-search-autocomplete to add autocomplete functionality in my django app, but nothing happening, view.py def origin_airport_search(request): if request.is_ajax(): try: data = AMADEUS.reference_data.locations.get(keyword=request.GET.get('term', None), subType=Location.ANY).data except ResponseError as error: messages.add_message(request, messages.ERROR, error) return HttpResponse(get_city_airport_list(data), 'application/json') html <body> {% include "nav.html" %} <script type='text/javascript'> $(document).ready(function () { $("#iata").autocomplete({ source: "{% url 'airport_search'%}", minLength: 1, delay: 200, }); }); </script> <form class="form" name="Query" method="post" > {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4"> {{ form.origin|as_crispy_field }} </div> <div class="form-group col-md-4"> {{ form.destination|as_crispy_field }} </div> </div> <div class="d-flex align-items-center form-group col-md-6"> <button type="submit" class="btn btn-primary">NotifyMe</button> </div> </form> urls: urlpatterns = [ path('', home, name='home'), path('airport_search/', origin_airport_search, name='airport_search'), ] forms.py origin = forms.CharField(max_length=30, label='Origin', required=True, widget=forms.TextInput( attrs={'type': 'text', 'id': 'iata', 'name': 'origin'})) destination = forms.CharField(max_length=30, required=True, widget=forms.TextInput( attrs={'type': 'text', 'id': 'iata', 'name': 'destination', 'placeholder': 'destination code'})) followed as mentioned in documentation but it's not working out. -
Django sitemap i18n repeats default language, doesn't include urls for non-default languages
Using Django 4.0.6, I have sitemaps working fine for a single default language - English. After adding i18n, the sitemap isn't showing the URLs for other languages, but instead repeats the English URL, whilst labeling it as a URL for the other language. I've read the documentation but can't see my mistake. from datetime import datetime from django.contrib.sitemaps import Sitemap from django.urls import reverse_lazy class LettergunSitemap(Sitemap): i18n = True languages = ["en", "nl"] alternates = True x_default = True changefreq = "daily" priority = 0.5 lastmod = datetime.strptime(LAST_MOD, "%Y-%m-%d") class Home(LettergunSitemap): location = reverse_lazy("base:home") def items(self): return ["item"] class Contact(LettergunSitemap): location = reverse_lazy("base:contact") def items(self): return ["item"] class DemoRequest(LettergunSitemap): location = reverse_lazy("base:demo") def items(self): return ["item"] ... long sitemap extract: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>http://lettergun.com/en/</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/" /> </url> <url> <loc>http://lettergun.com/en/</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/" /> </url> <url> <loc>http://lettergun.com/en/say-hello</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/say-hello" /> </url> <url> <loc>http://lettergun.com/en/say-hello</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/say-hello" … -
How to render ValidationError in Django Template?
I am new in Django, and I ask community help. Now I I'm working on user registration and I want to do password validation: if passwords are not repeated, a message appears below the bottom field. As far as I understand, {{ form.errors }} must be used to render the error text specified in ValidationError , but when this error occurs, its text is not displayed on the page. Please tell me how to solve this problem. Perhaps I did not quite understand how Django forms work. I tried the solutions suggested in other answers, but unfortunately nothing worked so far. Thank you. forms.py: from .models import CustomUser class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Адрес электронной почты", widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder':'email'})) password = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'password'}) ) confirm_password = forms.CharField(label='Пароль(повторно)', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'confirm password'})) def clean(self): super().clean() password = self.cleaned_data['password'] confirm_password = self.cleaned_data['confirm_password'] if password != confirm_password: raise ValidationError({'confirm_password': 'пароли не совпадают'}) views.py: def sign_up(request): if request.method=="POST": form = RegisterUserForm(request.POST) if form.is_valid(): form.save() return redirect('pages:index') form = RegisterUserForm() return render(request=request, template_name="users/sign_up.html", context={'form': form}) template: </head> <link rel="stylesheet" type="text/css" href="{% static 'users/css/style.css' %}"> <head> <div class="text-center log-in-bg rounded"> <img class="mb-4" src="{% static "users/images/logo_sign_in.png" %}" alt="" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal text-dark">РЕГИСТРАЦИЯ</h1> … -
Django, why this is not working(reply of comment function)
I want to make reply of comment function. so I added parent option in Answer model. answer_create() working well. but, when i submit reply of comment, url is different with url i setting. i think i should be http://127.0.0.1:8000/debateboard/305/ but return http://127.0.0.1:8000/debateboard/answer/reply/31/ help me plz models.py class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_question') subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) voter = models.ManyToManyField(User, related_name='voter_question') def __str__(self): return self.subject class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_answer') question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) voter = models.ManyToManyField(User, related_name='voter_answer') ######### i added this parent to make reply of comment parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='+') def __str__(self): return self.content @property def children(self): return Answer.objects.filter(parent=self).order_by('-create_date').all() @property def if_parent(self): if self.parent is None: return True return False urls.py urlpatterns = [ path('', base_views.index, name = 'index'), path('<int:question_id>/', base_views.detail, name = 'detail'), path('answer/create/<int:question_id>/', answer_views.answer_create, name = 'answer_create'), path('answer/reply/<int:answer_id>/', answer_views.reply_comment_create , name='reply_comment_create'), view def detail(request, question_id): # question = Question.objects.get(id = question_id) question = get_object_or_404(Question, pk = question_id) context = {'question' : question} return render(request, 'debateboard/detail.html', context) @login_required(login_url='common:login') def reply_comment_create(request, answer_id): answer = get_object_or_404(Answer, pk=answer_id) # question = get_object_or_404(Question, pk = answer.question.id) if … -
Django ManyToMany table output
i'm having a bit of trouble trying to return the actual value of a seperate model, i would like to return simple 'in progress' or 'open' or whichever states i add. Instead it's showing <queryset and this is only viewable when i add the .all on the end, otherwise it states None (or is blank). the status does bring back the correct data, however i just need it to say the result OPEN or IN progress and get rid of the queryset- a workflow can go through multiple status's throughout its lifecycle Views.py def workflows(request): return render(request, 'workflows/workflows.html', { 'workflows': Workflow.objects.all() }) models.py class Workflow(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True, max_length=30) status = models.ManyToManyField('Status', blank=True, related_name='workflows') created = models.DateTimeField(auto_now_add=True) # tags = models.ManyToManyField('Tag', blank=True) modified = models.DateTimeField(auto_now_add=True) # created_by = # requester_id retired = models.BooleanField(default=False) def __str__(self): return self.name #foreign key 1 to many relationship class Review(models.Model): #owner = workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.AutoField(primary_key=True, editable=False) def __str__(self): return f'workflow: {self.workflow} {self.created}' #many to many relationship # Tag to be easily identifiable. class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = models.AutoField(primary_key=True, editable=False) def __str__(self): … -
Django: How to take a data by Foreighkey for some date?
Model: class Electricitymeter(models.Model): name = models.CharField(max_length=100) serialnumber = models.CharField(unique=True, max_length=30, primary_key=True, null=False, blank=False,) ratio_transform = models.PositiveSmallIntegerField(null=False, blank=False, default=1) class Lessor(models.Model): name = models.CharField(unique=True, max_length=100) class Rentaroom(models.Model): room = models.OneToOneField(Room, on_delete=models.CASCADE) renter = models.ForeignKey(Renter, on_delete=models.CASCADE) electricitymeter = models.OneToOneField(Electricitymeter, on_delete=models.CASCADE) tarifofelectricity = models.FloatField(blank=False, null=False, default=11.8) class Electricitydate(models.Model): serialnumber = models.ForeignKey(Electricitymeter, blank=True, null=True, on_delete=models.CASCADE) datedata = models.DateField(null=False, blank=False) consumption = models.PositiveIntegerField(blank=False) View def outputmetersdata(request): form = MyForm() if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): form = form.cleaned_data startdataperiod = form['startdataperiod'] enddataperiod = form['enddataperiod'] pk = form['lessor'] obj = Rentaroom.objects.all().filter(lessor_id=pk.id) startdate = startdataperiod - timedelta(days=3) enddate = startdataperiod + timedelta(days=3) startconsumption = Electricitydate.objects.filter(datedata__range=[startdate, enddate]) context = { 'obj': obj, 'startdataperiod': startdataperiod, 'enddataperiod': enddataperiod, 'pk': pk, } return render(request, 'roomsmeters/outputmetersdata.htm', context) else: form = MyForm() return render(request, 'roomsmeters/outputmetersdata.htm', {'form': form}) Template: {% for obj in obj %} <h1> Period {{ startdataperiod }} - {{ enddataperiod }} </h1> <tr> <td>{{ obj.spotelectr }}</td> <td>{{ obj.renter }}</td> <td>{{ obj.room }}</td> <td>{{ obj.electricitymeter }}</td> <td>{{ obj.electricitymeter.ratio_transform }}</td> <td>{{ obj.electricitymeter.serialnumber }}</td> <td>{{ pk }}</td> </tr> How to take a consumption for some datedata? And how to take a valid consumption for some date if the date is between two datadates? In what file can I make calculations: (consumption_for_second_date …