Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django form action url 'abc' is redirect to abc twice
In django index.html, I have below code <form class="selectedPizza" action="{% url 'cost' %}" method="POST"> <!--Do some action here--> <form> In my app(order) urls.py from django.urls import from . import views urlpatterns = [ path("", views.index, name="index"), path("cost/", views.cost, name="cost") ] In main site(pizza) urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("orders.urls")), path("cost/", include("orders.urls")), path("admin/", admin.site.urls), ] In views.py def index(request): #some action here return render(request, 'orders/index.html', context) def cost(request): if (request.method == 'POST'): #some action here return render(request, 'orders/cost.html', context) After submitting the form I am redirected to "http://127.0.0.1:8000/cost/cost/". I am learning Django and not able to find a possible way to get this form to redirect to cost.html page after submitting -
Deleting objects in formset django
I am going to delete one object in forms as you can see in the picture that minus button should delete existing element but it does not working. def form_valid(self, form): form.save() context = self.get_context_data() instance = self.get_object() formset = product_forms.SizeFormset(self.request.POST) if formset.is_valid(): product_sizes = product_models.Size.objects.filter(product_id=instance.id) default_item = 0 if product_sizes.exists(): product_sizes.delete() for formitem in formset: # only save if title and price is present if formitem.cleaned_data.get('title') and formitem.cleaned_data.get('price'): size = formitem.save(commit=False) size.product_id = instance.id if default_item == 0: size.default = True else: size.default = False default_item = default_item + 1 formitem.save() and in the template this code is <div class="size-add"> <button class="{% if formitem.id.value %}remove-form-row {% else %}add-form-row {% endif %} btn btn-primary"> How can I get it work? Any help? Thanks in advance! -
Get a random object of a Django Queryset but not the current one
So I have this template context processor: from cases.models import CasePage def random_case(request): case = CasePage.objects.live().order_by('?') return {'random_case': case} And in the template I do this: {% for entry in random_case %} {% if request.get_full_path != entry.get_url %} {% if forloop.first %} <a class="ajax-link project-next" href="{{ entry.get_url }}"> <div class="nav-project-title">{{ entry.title }}</div> <div class="nav-title">next</div> </a> {% endif %} {% endif %} {% endfor %} And this works but the problem is sometimes the object is the same as the page so nothing is displayed. It would be great if that one would be skipped in favour of the next entry. And it's also too much logic in the template for me. What would be the best way to move this logic into the context processor and make it work? -
Celery beat incorrectly spawns periodic tasks multiple times filling up queue
I'm developing Django application with celery task manager to perform 6 periodic tasks with following schedule: { 'daily_full_import_provider1': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider1' } }, 'daily_full_import_provider2': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider2' } }, 'daily_full_import_provider3': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider3' } }, 'daily_full_import_provider4': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider4' } }, 'daily_full_import_provider5': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider5' } }, 'daily_full_import_provider6': { 'task': 'update_data.tasks.import_full_provider_data', 'schedule': '<crontab: * */2 * * * (m/h/d/dM/MY)>', 'kwargs': { 'provider': 'provider6' } } } Every task calls same python function with different parameters: def provider_shadow_name(task, args, kwargs, options): return "celery.import.{}".format(kwargs['provider']) @celery.task(shadow_name=provider_shadow_name) def import_full_provider_data(provider=None): return ImportWorker( ProviderService.UPDATE_OP, provider=[provider] if provider else provider )() I'm running one worker/beat/flower instance in screen: screen -S djapp_uat_celery_worker -d -m -h 500 \ $djapp_ENV/bin/celery -E -A djapp worker \ --concurrency=$djapp_CELERY_THREAD_WORKERS \ --pidfile=$djapp_VAR/djapp-celeryworker.pid \ --loglevel=INFO \ --logfile=$djapp_LOG_DIR/%p.%i.celery.worker.log screen -S djapp_uat_celery_scheduler -d -m -h 500 \ $djapp_ENV/bin/celery -A djapp beat \ --schedule=$djapp_VAR/djapp-celerybeat-schedule.db \ --pidfile=$djapp_VAR/djapp-celerybeat.pid \ --loglevel=INFO … -
Django Crispy_Form unable to render in HTML
I have been following the docs/videos online and can't seem to get my Form to render, I would be happy if someone could explain me what I am doing wrong: My goal is to get the Form to render Here is my Code: views.py I handled both cases according to request type and didn't leave the else block empty. Defined the form, didn't forget the redirect from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) forms.py Defined a form from the existing Django Forms and included all the necessary fields from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] register.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have … -
Django duplicate database queries
I am using django_debug_toolbar for analyzing performance of web page. What confuses me in the results is the database queries. No matter I did everything as it should be (I suppose), results tab still shows duplicate database queries warning. For illustrating this problem, I set out django project as simple as below: models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) views.py from django.shortcuts import render from .models import Question, Choice def index(request): return render(request, 'polls/index.html', {'questions': Question.objects.all()}) index.html {% for question in questions %} <p>{{ question.question_text }}</p> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.votes }} votes - {{ choice.choice_text }}</li> {% endfor %} </ul> {% endfor %} In the above html file and view, I load all questions and their related choices. For testing, I added only 2 question and 2 and 4 choices for them respectively (6 choices in total). And django_debug_toolbar SQL result are as below: What should I do for avoiding these duplicate SQL queries? I think that these duplicated query may have serious impacts on performance for big websites. What is your approach and best … -
How to make Django find a static css file
I am going nuts with muy current Django project and its static files. I tried different solutions on SO (e.g. Django cannot find my static files and Django Static Files CSS) and even my very own working ones from my other projects.. I just want to link a basic css file located in my projects /static/ folder to my base.html file which will contain the basic navbar for all sites/apps within the project. That's why I decided to place it in the projects directory centrally. Somehow it won't find the file though. This is my setup where debug is set to True (development, no production yet) settings.py: # this defines the url for static files # eg: base-url.com/static/your-js-file.js STATIC_URL = '/static/' # this is directory paths where you have to put your project level static files # you can put multiple folders here STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/dashex/static/', ) base.html: {% load static %} [...] {% block head_css_site %} <link href="{{ STATIC_URL }}base.css" rel="stylesheet" type="text/css"> {% endblock head_css_site %} [...] project structure: error: GET http://127.0.0.1:8000/base.css net::ERR_ABORTED 404 (Not Found) -
Is there a way for a user to select an irregular geographic area on a map (on a website and app) and that to be stored?
So basically, I want the user to be able to select an area on a map, and then I would be able to return places in the area selected. My problem is how would I get the user to select the area and how would I store that? A good example would be on https://www.rightmove.co.uk/draw-a-search.html I dont know where to start with this. Is there a certain conventional way to do this. For reference, I am using python/django for my project. I need to do this on an android and ios app as well as the django site. Thanks for any help. -
How do I integrate Bootstrap 4 source files with Django 2.2?
I would like to integrate the source files of Bootstrap within my Django 2.2 web project, without using the CDN. I want to be able to completely customise my project and effect the bootstrap default settings. There seem to be no tutorials on how to do this, and the proper file structure once complete. I would love to know exactly how to download bootstrap files into my Django project, and the exact file structure, in a way that can be used during deployment also. I have copied and pasted all Bootstrap 4 files into the static sections of my Django project, however I can not seem to make changes to the __variables.scss file and it is saying in a lot of documentation that this isn't best practise anyhow. I have been using Koala to compile the SCSS into the CSS files but again I don't know if this is recommended and I would like to get it done the 'correct' way straight from the off. At the end I would like to fully incorporate Bootstrap and the Bootstrap JS into my project without using the CDN method as I would like complete customisation, with the file structure being as close … -
Registration with email django doesn't work
I want to implement registration with email verification in Django. Filled registration form --- OK Received email with link --- OK http://127.0.0.1/accounts/register/activate/mosk:tQUC9n5kMrmoVSZv4qy6DCAUjaM/ Clicked to the link --- received ERROR: This site can’t be reached127.0.0.1 refused to connect How can I solve the error??? It seems that urls.py is OK and I should add something to ALLOWED_HOSTS Image settings.py DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') AUTH_USER_MODEL = 'blog.AdvUser' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'alekmosk25@gmail.com' EMAIL_HOST_PASSWORD = '*****' DEFAULT_FROM_EMAIL = 'Alex' DEFAULT_TO_EMAIL = 'msumoskalenko@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data … -
how solve JSONDecodeError at /api/customer/order/add/ Expecting property name enclosed in double quotes: line 1 column 30 (char 29)
JSONDecodeError at /api/customer/order/add/ Expecting property name enclosed in double quotes: line 1 column 30 (char 29) Request Method: POST Request URL: http://localhost:8000/api/customer/order/add/?= Django Version: 2.2.6 Exception Type: JSONDecodeError Exception Value: Expecting property name enclosed in double quotes: line 1 column 30 (char 29) Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py in raw_decode, line 353 Python Executable: /Users/sandip/Desktop/myvirtualenv/foodtasker/bin/python Python Version: 3.7.3 SELECT APAIS import json from django.utils import timezone from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from oauth2_provider.models import AccessToken from foodtaskerapp.models import Restaurant, Meal, Order, OrderDetails from foodtaskerapp.serializers import RestaurantSerializer, MealSerializer def customer_get_restaurants(request): restaurants = RestaurantSerializer( Restaurant.objects.all().order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"restaurants": restaurants}) def customer_get_meals(request, restaurant_id): meals = MealSerializer( Meal.objects.filter(restaurant_id = restaurant_id).order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"meals": meals}) @csrf_exempt def customer_add_order(request): """ params: access_token restaurant_id address order_details (json format), example: [{"meal_id": 1, "quantity": 2},{"meal_id": 2, "quantity": 3}] stripe_token return: {"status": "success"} """ if request.method == "POST": # Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) # Get profile customer = access_token.user.customer # Check whether customer has any order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "failed", "error": "Your last order must be completed."}) # Check Address … -
Django, Check if checkbox is selected without submit or dynamically to update text
https://ibb.co/WxBfb3N Is there a way to check if a checkbox is selected without needing to submit? also I want the amount to change, I already have the choices ready with class ServiceForm(forms.ModelForm): CHOICES = ( (350, 'Nuat Thai Foot Massage(1hour)'), (350, 'Thai Body massage w/ Oil(1hour)'), (400, 'Sweddish Massage(1hour)'), (400, 'Armoatherapy Massage(1hour)'), (250, 'Express - Back and Head(30 mins)'), (250, 'Foot Massage(30 mins)'), (250, 'Back Massage(30 mins)'), (250, 'Head massage(30 mins)'), ) choices = MultiSelectFormField(choices=CHOICES) so in the picture when more than 1 of this is selected, I want the value to be added then be displayed. I want to be avoid submit button but if there is no such way, How can I do it with submit? -
Django templated does not display inputs to be filled
I need a call a form on an HTML template where the user posts data which saves to model The code is running without any errors But the html page display only title and button No text input fields I have a form which is to be displayed on a html page so the user can input data and it saves the data into the model.I am not getting any errors while executing th code but the template does not display the form it just shows the title and submit button def boqmodel1(request): form = boqform(request.POST) if form.is_valid(): obj=form.save(commit=False) obj.save() context = {'form': form} return render(request, 'create.html', context) else: context = {'error': 'The post has been successfully created. Please enter boq'} return render(request, 'create.html', context) MyTemplate <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create boq"/> </form> MY Url urlpatterns = [ url(r'^create/', views.boqmodel1, name='boqmodel1'), path('', views.boq, name='boq'), ] -
Displaying the same notification on all pages in the django application
I have a problem where I can't sleep ... I hope you will help. Well, in my application, creating a profile is like two stages, i.e. first you register, log in, and then you can go to the page where you can fill in your personal data, name, surname, etc. And my question is, is there any way that until these data have been filled in on each page in the designated place, a message appears encouraging you to complete the form? And the second question is, does anyone know a way that before filling out the form, let's give the "profile" on the page a form, and after filling it in entered data (without the form or editing option)? I hope you understood what I meant. -
I want to accept the data from user input in the form table generated dynamically
I want to pass the data from user input in the template create_proposal.html. The form is inside a dynamically generated table by JavaScript. Each row has cells that have input. The table inside create_proposal.html looks like: <table id="empTable" class="table-striped" border="1" cellmargin="100px" cellpadding="0px"cellspacing="5px"> <tr> <th> <h5></h5> </th> <th> <h5>No.</h5> </th> <th> <h5>Part no.</h5> </th> <th style="width:30vw"> <h5>Description</h5> </th> <th> <h5>Quantity</h5> </th> <th> <h5>Unit Market price</h5> </th> <th> <h5>Markup percentage</h5> </th> </tr> </table> And the script that generates the rows: <script> // ARRAY FOR HEADER. var arrHead = new Array(); arrHead = ['', 'No.', 'Part no.', 'Description', 'Quantity', 'Unit market price', 'Markup percentage']; // ADD A NEW ROW TO THE TABLE.s function addRow() { var empTab = document.getElementById('empTable'); var rowCnt = empTab.rows.length; // GET TABLE ROW COUNT. var tr = empTab.insertRow(rowCnt); // TABLE ROW. tr = empTab.insertRow(rowCnt); for (var c = 0; c < arrHead.length; c++) { var td = document.createElement('td'); // TABLE DEFINITION. td = tr.insertCell(c); if (c == 0) { // FIRST COLUMN. // ADD A BUTTON. var button = document.createElement('input'); // SET INPUT ATTRIBUTE. button.setAttribute('type', 'button'); button.setAttribute('value', 'Remove'); button.setAttribute('class', 'btn btn-danger'); // ADD THE BUTTON's 'onclick' EVENT. button.setAttribute('onclick', 'removeRow(this)'); td.appendChild(button); } else if(c == 1){ var ele = document.createElement('input'); … -
How to create Django objects that have foreign key field referenced on field which haven't contain data
I faced with problem while creating django objects. I have two models class League(models.Model): league_id=models.IntegerField (primary_key=True) league_name=models.CharField (max_length=20) league_logo = models.URLField (null = True) league_flag = models.URLField(null = True) standings=models.IntegerField (null=True) is_current = models.IntegerField (null=True) class Fixture(models.Model): fixture = models.IntegerField (primary_key=True) league_id=models.ForeignKey ('League',null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(null=True) event_timestamp= models.DateTimeField (null=True) When i am trying to create object from my fixture model and in this time i have not any data in league table. I get an error that Traceback (most recent call last): File "<console>", line 1, in <module> File "/data/data/com.termux/files/home/storage/predictions/forecast/odds.py", line 53, in <module> fixt = Fixture.objects.create_or_update(fixture_id = fixture_id,league_id_id = league_id,event_date = event_date,) AttributeError: 'Manager' object has no attribute 'create_or_update' >>> import odds /data/data/com.termux/files/home/storage/predictions/forecast Traceback (most recent call last): File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit self._commit() File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/data/data/com.termux/files/home/storage/predictions/env/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit return self.connection.commit() django.db.utils.IntegrityError: insert or update on table "dataflow_fixture" violates foreign key constraint "dataflow_fixture_league_id_id_674984dc_fk_dataflow_" DETAIL: Key (league_id_id)=(780) is not present in table "dataflow_league". Like i understand this error occur because while i am creating a fixture object and process of creating reach league_id field and its reference to league_id … -
Need help after upgrading Django
I upgraded Django 2.2.5 to 2.2.6 and now I got the error: Message=Failed lookup for key [title] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x0000023044F223A8>>, 'request': <WSGIRequest: GET '/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x0000023044E74D38>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x0000023045017688>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x0000023044F3A388>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': <AuthenticationForm bound=False, valid=Unknown, fields=(username;password)>, 'view': <django.contrib.auth.views.LoginView object at 0x0000023044F3AC08>, 'next': '', 'site': <django.contrib.sites.requests.RequestSite object at 0x0000023044F65088>, 'site_name': 'localhost:65093', 'LANGUAGE_CODE': 'da-dk', 'LANGUAGE_BIDI': False}, {'block': <Block Node: title. Contents: [<Variable Node: title>, <TextNode: ' | '>, <Variable Node: site_title|default:_('Django site admin')>]>}] Source=C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py StackTrace: File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 796, in resolve value = self._resolve_lookup(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 671, in resolve obj = self.var.resolve(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 987, in render output = self.filter_expression.resolve(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\WestcoastComputer\Development\env\pyØkonomiWeb\Lib\site-packages\django\template\base.py", line 937, in render bit = … -
(Django) How to get an object id in form_valid?
I am trying to make a comment form on a posting app with django, the problem is I can't seem to get it's own object's id, any idea? class MyFormView(FormView): form_class = CommentForm success_url = "/" def form_valid(self,form,*args,**kwargs): comment = form.save(commit=False) comment.message=Message.objects.get(id=???) comment.save() return super(MyFormView, self).form_valid(form) If i were to replace the ??? with for example 7, it will post every comment on message(or post) with the id 7, but I want the comment to be posted on the message i am seeing. Any help appreciated -
Please provide Django ORM query for Sql query
Need Django ORM query for below Postgres Query, Sql query has sub queries. Please explain how to write ORM for it. select arc.quantity as quantity, arc.quantity - pr.quantity as remaining_qunatity from (select d.document_number as document_number, dr.quantity as quantity, dr.sku as sku from document_rows as dr join documents as d on dr.document_id = d.id join document_type as dt on d.document_type_id = dt.id where dt.title = 'annual_rate_contract' ) as arc join (select d.document_number as document_number, dr.quantity as quantity, dr.sku as sku from document_rows as dr join documents as d on dr.document_id = d.id join document_type as dt on d.document_type_id = dt.id where dt.title = 'purchase_requisition' ) as pr on arc.document_number = pr.document_number and arc.sku = pr.sku -
I am unable to fix error while working on django project, TypeError: expected str, bytes or os.PathLike object, not function
I get the below error ..please help. Thanks in advance. this is my views.py code def details_view(request): context={} user=request.user if not user.is_authenticated: return HttpResponse('Please login') form=DetailsForm(request.POST or None, request.FILES or None) if form.is_valid(): obj=form.save(commit=False) student=Account.objects.filter(email=user.email).first() obj.student=student obj.save() form=DetailsForm() context['form']=form return render(request,'account/details.html',context) -
Django / JQuery Iterate over table updating each cell with json data
I have table rows that looks like this {% for item in items %} <tr id="labels" data-index="{{ forloop.counter }}"> </tr> {% endfor %} I get this json data: "labels": [ "A", "B", "C ", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ], Im trying to iterate over the table rows and the json data at the same time, so that I can assign each table row its label. jQuery.each(labels, function() { newlabel = this; document.querySelectorAll('#labels').forEach(function (element, index) { element.innerHTML = newlabel; }); })}, But with this all the cells have the character Z, instead of being in alphabetical order. Thank you for any help -
DRF Serializer empty OrderedDict on update()
I'm using Django 2.x and Django REST Framework class ComponentDataSerializer(serializers.ModelSerializer): class Meta: model = ComponentData fields = [ 'id', 'analytics_type' ] class ComponentSerializer(serializers.ModelSerializer): data = ComponentDataSerializer(many=True) class Meta: model = Component fields = [ 'id', 'name', 'group', 'data', ] def validate(self, attrs): print('validate data: {}'.format(attrs)) return attrs With POST request, the attrs in validate() is validate data: OrderedDict([('name', 'Component Test'), ('group', <AnalyticsGroup: Chart>), ('data', [OrderedDict([('analytics_type', <AnalyticsType: Bar Chart>)])])]) While with PATCH request, the data attribute has empty OrderedDict validate data: OrderedDict([('group', <AnalyticsGroup: Chart>), ('data', [OrderedDict()])]) The data payload in each request is the same. name: "Component Test" group: "2" data[0]analytics_type: "3" data[0]analytics_sub_type: "2" data[0]query: "9" Where value for each field analytics_type, analytics_sub_type and query is the pk respectively. -
Got a `TypeError` when calling `Article.objects.create()`
I am working on Django React Project using the Django REST FRAMEWORK,I am trying to post some data tied to my model. The list view and the detail view of the project works pretty fine,The only problem is when I try to make a POST request whenever I Try post the data in the CreateAPIView I get an error : Got a `TypeError` when calling `Article.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Article.objects.create()`. You may need to make the field read-only, or override the ArticleSerializer.create() method to handle this correctly. I have searched through various past problems but non of them seem to fix my problem. Here is my serializers file from rest_framework import serializers from articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','title','content','star_count','like_count','comment_count','avatar') Here is my views file from rest_framework.generics import ListAPIView,RetrieveAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView from .serializers import ArticleSerializer from articles.models import Article from rest_framework import viewsets class ArticleViewSets(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer models file content = models.TextField() comment_count = models.IntegerField(default=0,null=True,blank=True) like_count = models.IntegerField(default=0,null=True,blank=True) star_count = models.IntegerField(default=0,null=True,blank=True) avatar = models.ImageField(null=True,blank=True) def __str__(self): return self.title def save(self): if not self.slug: self.slug = … -
Loop JavaScript in Ajax
i'm following the Django code that dynamically generates cards according to my amount of variables i have in a bank. For each card it consumes data from an API through ajax code. However, my ajax code is not being called every loop. It is called only once. What I can do is wrong, because I need ajax to be called every loop of HTML. {% block content %} <div id="auto" class="row"> {% for row in list %} {% if row.state == 1 %} <div class="col-xs-6 col-md-4"> <div class="card"> <h5 class="card-header">{{row.description}} - Temperatura Atual (˚C)</h5> <!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!--> <canvas id="myChart-{{ forloop.counter }}" class="piechart"></canvas> <script> var rowId = {{ row.id }} console.log(rowId); readTempDinamic(rowId); //refresh(); </script> <p class="text-center font-weight-bold" style="font-size: 0.7rem"><span id="datetime"></span></p> <a href="{% url 'row_details' pk=row.pk %}" class="btn botao-detalhar btn-sm">Show</a> </div> </div> {% endif %} {% endfor %} </div> {% endblock content %} function readTempDinamic(rowId) { var endpointTemp = '/api/weatherData/getSensor/1/' + rowId + '/' console.log(endpointTemp); /* ############################################################################# */ $.ajax({ method: "GET", url: endpointTemp, success: function(data){ var row = [] var value = [] var read_data = [] row = data.row value = data.value read_data = data.read_date generateGaugeCharts(row[0], read_data[0], value[0]) }, error: function(error_data){ console.log("error") console.log(error_data) … -
How to render template in Django and redirect to a certain fragment of the template?
A Django newbie question. Let's say I have a template that contains three paragraphs and I render it in views.py. Is there a way to redirect to a certain paragraph of the template using render? and if not what are my options?