Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to CreateAPIView using the request.user
Hi I'm wondering what the best practice is for creating a new model entry with a user based off the request in Django Rest Framework? Models: class Asset(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="assets") name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=10, decimal_places=2) Serializers: class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = '__all__' Views class CreateAssetView(generics.CreateAPIView): serializer_class = AssetSerializer <Doesn't seem to work, possibly since user isn't in the json> def perform_create(self, serializer): serializer.save(user=self.request.user) Basically I want to be able to send a POST request {name: 'myasset', amount: '50'} to this endpoint and have a new Asset saved with the User field obtain from the request. What is the best way to do this? Thanks -
Django new line in output
i try to print model object in new line but my code don't work. Here is my code and I want to know how can I fix this problem? def list_create_tasks(request): if request.method == 'GET': all_tasks=Task.objects.all() return HttpResponse('\n'.join(map(str, all_tasks))) -
! [rejected] master -> master (fetch first) when pushing to git
Since the major change in policy- I used SSH key. All went well until changes were made. Now when I'm trying to push my changes this error pops :( ! [rejected] master -> master (fetch first) error: failed to push some refs to 'github.com:kohenm63/phone_book.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. -
Passing a Django database pk id to Dash app
I have successfully embedded a Dash application into my Django app. I can display simple plots. But what I want to do, and have been unable to do by following documentation, is pass a pk id variable into the Dash app, pull relevant DB information according to that pk, and then plot it. my urls.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^model/(?P<pk>\d+)/$', views.model, name='model'), views.py: def home(request): return render(request, 'home.html') def model(request, pk): context = {'data' : {'pk': pk}} return render(request, 'model_results.html', context) models.html template: {%load plotly_dash%} <body> <div class="container"> <!--Row with two equal columns--> <div class="row"> <div class="col-lg-1 col-md-1 col-xl-1 col-sm-1"> <div class = "card"> <div class = "card-body"> {%plotly_app name="tutorial_1" initial_arguments=data%} </div> </div> </div> </div> </div> </body> and lastly, my dash app: app = DjangoDash('tutorial_1') app.layout = html.Div(children=[ html.H1(children='Dash Tutorials'), dcc.Graph( id='example', figure={ 'data': [ {'x': [1, 2, 3, 4, 5], 'y': [9, 6, 2, 1, 5], 'type': 'line', 'name': 'Boats'}, {'x': [1, 2, 3, 4, 5], 'y': [8, 7, 2, 7, 3], 'type': 'bar', 'name': 'Cars'}, ], 'layout': { 'title': 'Basic Dash Example' } } ) ]) if __name__ == '__main__': app.run_server(debug=True) It is unclear to me from other examples how I can use the Django ORM … -
heroku git:remote -a command is not working
heroku git:remote -a mymailapp-live » Warning: heroku update available from 7.53.0 to 7.59.0. Error: Command failed: git remote fatal: not a git repository (or any of the parent directories): .git it is showing me above error. please help me. i am hosting this using heroku-cli. -
Multiple django forms with diferent placeholders, do i use form factory?
I have a main model Questionare, A list of ExtraQuestion's and a model to store the answers in... Questionare(model.Model): first_name = ... last_name = ... ExtraQuestion(model.Model): question = ... Answer(model.Model) questionare = models.ForeignKey(Questionare...) extra_qestion = models.ForignKey(ExtraQuestion...) answer = ... How do i create a bunch of ModelForms for each of the ExtraQuestions with the question as a placeholder to the input field and update the Answer model with the relevant foreign keys. I was looking at FormFactory but I think every form needs to be exactly the same and I cant differ the placeholder. Any advice is appreciated. -
Setting up create-react-app in docker shell only
I'm curious if anyone knows why it's not common practice to run create-react-app from within the shell. The goal here is to attempt to avoid having to install packages on my local machine per create-react-app since I'll never run 'npm start' on my local machine but rather from within the shell. The reason I ask is that I know this can be done in Django. Django can be done either way, where you can either create 'startproject' on your local machine, then create Dockerfile and docker-compose.yml file OR you can create an empty 'app' folder within the root folder, start with Dockerfile and docker-compose file, go into the shell and do startproject from within the shell with no problems as long as you have your volumes setup correctly. This might just be my lack of understanding of how Django dev projects are built vs React dev projects. Or could be just how python image works vs node image from dockerhub. I was able to create a simple Dockerfile (below). Then run 'docker-compose build' then run 'docker-compose run react_app sh -c "npx create-react-app ." ' and this worked, but this still copies over all the node_modules anyhow. The part that interests … -
I am getting No reverse match error in django but it is used urls.py
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] View.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect ,get_object_or_404 from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context) def add_post(request): pass def post_detail(request,slug): indentified_post = get_object_or_404(Post,slug=slug) return render(request,"blog/post-detail.html",{'post':indentified_post}) i am iterating through posts and using the post-detail.html page all-post.html. {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <br> <h1 style="text-align:center;">All Tractors</h1> <ul> {% for post in posts %} <br> {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %}``` -
How to implement refresh token in react js
The response from the server set the access and refresh token to the client(reactjs) as an httponly cookie. How can I use the refresh token to generate another access token, because when I try to use document.cookie or cookie.get('refresh') it returned undefined. axios.post('http://localhost:8000/api/token/refresh/', { refresh: cookie.get('refresh') // Cookie here is undefined }).then(response => { // new access token }) -
Async run script from "python manage.py shell"?
As far as I can tell, running a script from python manage.py shell like python manage.py shell < import.py is done synchronously: # models.py class PersonManager(models.Manager): def generate_num_children(self, persons): for person in persons: person.generate_num_children() class ParentManager(models.Manager): def generate_num_grandchildren(self, parents): for parent in parents: parent.generate_num_grandchildren() class Person(models.Model): objects = PersonManager() num_children = models.IntegerField(default=0) parent = models.ForeignKey(related_name="children") def generate_num_children(self): self.num_children = 1 self.save() class Parent(models.Model): objects = ParentManager() num_grandchildren = models.IntegerField() def generate_num_grandchildren(self): num = 0 for child in self.children.all(): num += child.num_children self.num_grandchildren = num self.save() # import.py parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) parent.generate_num_grandchildren() # python manage.py shell Parent.objects.get(id=1).num_grandchildren # Returns 0 When I enter each line individually in python manage.py shell or in a test file however, the code runs asynchronously and gives me the correct result: parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) parent.generate_num_grandchildren() Parent.objects.get(id=1).num_grandchildren # Returns 3 So how can I make my import.py file async? # import.py # Run first parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) # Run … -
Django: AttributeError 'WSGIRequest' object has no attribute 'get'
I am trying to add a set of inline forms, but when I try to save the information of the forms it throws me this error views.py The intention is to create more orders for a particular client, for that reason I focus on the "createOrder" function to achieve it. from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.forms import inlineformset_factory from .forms import OrderForm, CustomerForm # Create your views here. def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status')) customer = Customer.objects.get(id=pk) form_set_value= OrderFormSet(instance=customer) if request.method == 'POST': form_set_value= OrderFormSet(request, instance=customer) if form_set_value.is_valid: form_set_value.save() return redirect('/') context = {'form_set_key':form_set_value} return render(request, 'accounts/order_form.html', context) order_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{ … -
How do I resovle django saml2 authentication type errors in saml.py
I am attempting to integrate django-saml2-auth into legacy code running django1.11.29 with python2.7. From the IDP side I am completing authentication but when I then get the following error from my website. ValueError at /saml2_auth/acs/ Type and value do not match: string:<type 'unicode'>:19055 Request Method: POST Request URL: https://mysite/saml2_auth/acs/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: Type and value do not match: string:<type 'unicode'>:19055 Exception Location: /abc/abc/abc/Django_Env/lib/python2.7/site-packages/saml2/saml.py in _wrong_type_value, line 171 Python Executable: /usr/bin/python Python Version: 2.7.5 This is the function that it fails at in saml.py, line 171 is raise ValueError(msg) def _wrong_type_value(xsd, value): msg = 'Type and value do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) and here is my saml config in settings. SAML2_AUTH={ 'METADATA_LOCAL_FILE_PATH': '/abc/xyz/django-saml2/metadata_170CB91D5E5.xml', 'ASSERTION_URL': 'https://mysite', 'CREATE_USER': 'TRUE', 'ATTRIBUTES_MAP': { 'username': 'urn:mace:dir:attribute-def:UserNumber', 'ENTITY_ID': 'https://mysite/saml2_auth/acs', 'DEFAULT_NEXT_URL': '/site/' } I have been at this for a week now and have not found another package that works better than this package with in the constraints of my environment. And ideas on how to get past this. Thanks -
Django-admin can't run after fresh install
(I'm new to SO also so I'm happy to change anything wrong with my post) But I just installed Ubuntu LTS 16 and tried to get Django working. I ran these commands, and then got the error below. Commands: $ sudo apt-get install python3 $ sudo apt-get install python3-pip $ pip3 install Django $ sudo apt-get install python3-django $ sudo django-admin startproject yourprojectnamehere Error that I keep having, even after 2 OS reinstalls: File "/home/boo/.local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line File "/home/boo/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/home/boo/.local/lib/python3.5/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/home/boo/.local/lib/python3.5/site-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/home/boo/.local/lib/python3.5/site-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/home/boo/.local/lib/python3.5/site-packages/asgiref/sync.py", line 115 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax anyone have any idea? Is it not connecting to python3 or something? My computer even says "System error, do you want to report?" and last time my whole Terminator terminal crashed and wouldn't restart so IDK if I'm messing up some system files or something too. -
Django model_formset not able to edit, save or delete information
I'm trying to create a simple modelformset to show multiple copies of the same form. My models.py table is called Driver and it has only one field, driver: class Driver(models.Model): driver = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.driver if self.driver else '' My urls.py: urlpatterns = [ path('driver/', DriverCreateView.as_view(), name = "driver-create"), ] My forms.py: class DriverForm(forms.ModelForm): class Meta: model = Driver fields = ['driver'] # exclude = ("id",) DriverFormSet = modelformset_factory(Driver, form = DriverForm, fields = ['driver'], extra = 1, max_num=20, can_delete=True) I'm fairly sure the issue is in views.py: class DriverCreateView(LoginRequiredMixin, CreateView): model = Driver form_class = DriverForm template_name = 'trucking/driver_form.html' def get_context_data(self, **kwargs): context = super(DriverCreateView, self).get_context_data(**kwargs) context['formset'] = DriverFormSet() return context def post(self, request, *args, **kwargs): formset = DriverFormSet(request.POST) form= DriverForm(request.POST) if formset.is_valid(): formset.save() if self.request.POST.get('Save_Exit'): return HttpResponseRedirect('/database/') if self.request.POST.get('Save'): return HttpResponseRedirect('/driver/') return render(request, self.template_name, {'formset': formset}) Finally my template driver_form.html: <form method = "POST"> <fieldset class = "form-group"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <table cellpadding="6" cellspacing="1" border="0"> <tbody> {% for form in formset %} {% for field in form.visible_fields %} <tr> <td class="column_name">{{field.label_tag}}{{field.auto_id}}</td> <td class="column_data">{{field}}</td> <td class="column_errors">{{field.errors|striptags}}</td> </tr> … -
What is the correct LANGUAGE_CODE for the UK?
Is the correct LANGUAGE_CODE for British English 'en-GB' or 'en-gb' when using I18N? Does it make a difference? -
Bootstrap and Django: Popper.js is not load after i rendering HTML with AJAX
I want to duplicate a tr that contains some buttons, one of them is a dropdown that works until I copy that line. This error happens even when the dropdown works, so I'm still not sure if that's what's causing this error. I've already made the imports, I've already placed them in the right order. image of error <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/popper.js' %}"></script> <script src="{% static 'js/bootstrap4.0.0.min.js' %}"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.min.js'%}"></script> <script src="{% static 'js/select2.min.js' %}"></script> [.... code here....] <td align="center"> <div class="btn-toolbar" role="toolbar" style="justify-content: center;"> <div class="dropdown d-inline-block"> <button type="button" id="botao-mudar-status-{{tarefa.id}}" class="border-0 ml-2 btn-icon btn-icon-only btn-pill btn btn-outline-primary btn-sm" aria-expanded="false" data-toggle="dropdown"> <i data-toggle="tooltip" data-placement="bottom" data-original-title="Alterar status" class="pe-7s-repeat" style=" transform: rotate(90deg); font-weight: bold; font-size: initial;"></i> </button> <div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu-rounded dropdown-menu" x-placement="bottom-end" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-174px, 33px, 0px);"> <form id="tarefa-mudar-status-{{tarefa.id}}"> {% csrf_token %} <button type="button" tabindex="0" id="a-fazer-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">A Fazer</button> <button type="button" tabindex="0" id="em-andamento-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Em andamento</button> <button type="button" tabindex="0" id="feito-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Feito</button> <button type="button" tabindex="0" id="remover-status-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Remover status</button> </form> </div> </div> <button data-toggle="tooltip" data-placement="bottom" id="editar-tarefa-{{tarefa.id}}" data-original-title="Editar tarefa" class="border-0 ml-2 btn-icon btn-icon-only btn-pill btn btn-outline-focus btn-sm" data-form-url="{% url 'tasks:editar-tarefa' tarefa.id %}"> <i class="fa fa-edit" aria-hidden="true"></i> </button> … -
django_extensions runserver_plus returns NET::ERR_CERT_AUTHORITY_INVALID
I am following a tutorial (building a social website ~ Django 3 By Example by Antonio Mele) and attempting to implement social auth such as facebook/google by using social_django and django_extensions to provide an SSL. My installed apps are INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django_extensions', ] with allowed hosts ALLOWED_HOSTS = [ 'mysite.com', 'localhost', '127.0.0.1' ] and have the following packages installed asgiref==3.4.1 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.6 cryptography==35.0.0 defusedxml==0.7.1 Django==3.2.6 django-extensions==3.1.3 idna==3.2 oauthlib==3.1.1 Pillow==8.3.2 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==21.0.0 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 sqlparse==0.4.1 toml==0.10.2 urllib3==1.26.7 Werkzeug==2.0.1 and my hosts file located at C:\Windows\System32\drivers\etc also contains the string 127.0.0.1 mysite.com However, whenever I run the command python manage.py runserver_plus --cert-file cert.crt, which does generate the crt and key files, and load the browser, it tells me Your connection is not private with error NET::ERR_CERT_AUTHORITY_INVALID. I have also tried django-sslserver and runsslserver however the same error results, and no resource I have found has helped. Thanks in advance for any ideas! -
Django setting a ManyToMany field to the current value of another ManyToMany field
I'm trying to set the value of my StudentMeeting model's current_courses ManyToManyField field to the value of my Student.course ManyToManyField so each meeting keeps a record of what courses the student was enrolled in at the time of the meeting. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save from django.dispatch import receiver # Unrelated models omitted... class Student(models.Model): """Model representing a student""" first_name = models.CharField(max_length=50, help_text="Student first name.") last_name = models.CharField(max_length=50, help_text="Student last name.") course = models.ManyToManyField(Course, help_text="Select courses student is enrolled in.", blank=True, default='') def __str__(self): """String representing the Model object""" return self.last_name + ", " + self.first_name def get_absolute_url(self): """Returns the url to access a detailed record for this student""" return reverse("checkin-student-detail", args=[str(self.id)]) class StudentMeeting(models.Model): """Model representing a check-in appointment""" instructor = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True, default='') student = models.ForeignKey(Student, help_text="Student Name.", on_delete=models.CASCADE, null=True) appointment_date = models.DateField("Date", default=timezone.now) attended_meeting = models.BooleanField() missing_work_amount = models.IntegerField(default=0) narrative = models.TextField(blank=True, default='') current_courses = models.ManyToManyField(Course, blank=True, default='') def __str__(self): """String representing the Model object""" return str(self.appointment_date) + ": " + self.student.last_name + ", " + self.student.first_name @receiver(post_save, sender=StudentMeeting) def set_current_courses(sender, instance, created, **kwargs): if created: instance.current_courses.set(instance.student.course.all()) The vary last line … -
Django query parameter
I try to get a value as query parameter and I want to how can I optimize this code and don't use "" when user don't want to enter anything. author = request.GET.get('author','') name = request.GET.get('name','') -
DRF Get Request is always an empty object
I have a Django REST Framework setup, and I am only getting blank values. My serializer: class SettingsSerializer(serializers.Serializer): class Meta: model = Settings fields = fields = ["user_id","traditional","audio_download","show_read","show_pinyin","char_size","pinyin_size","start_date","end_date","speed","volume", "char_colors", "pinyin_colors", "global_dash"] My model: class Settings(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE) traditional = models.BooleanField() audio_download = models.BooleanField() show_read = models.BooleanField() show_pinyin = models.BooleanField() char_size = models.IntegerField() pinyin_size = models.IntegerField() start_date = models.DateField(null=True) end_date = models.DateField(null=True) speed = models.IntegerField() volume = models.IntegerField() char_colors = models.BooleanField() pinyin_colors = models.BooleanField() global_dash = models.BooleanField() class Meta: db_table = 'settings' My view: class SettingsRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView): queryset = Settings.objects.all() serializer_class = SettingsSerializer lookup_field = 'user_id' My url pattern: urlpatterns = [ path('settings/<int:user_id>/', SettingsRetrieveUpdateDestroyView.as_view()), ] My url: http://127.0.0.1:8000/api/v1/settings/87/ My response: {} And I can definitely confirm that there is a record for user_id = 87: Why is my response empty? -
django group by date without computing any metric
I have these two models and I am trying to build a django query such that given a Jobproject, I can get all the dates with events and which events they are...grouped by date. So basically, given a project having in return a dictionary that would look like this: { <10/10/21>:[Party,Meeting,DoctorAppointment]; <10/10/21>:[Game,Work]; <10/10/21>:[Dinner]; <10/10/21>:[Gym]; } Considering the below models, I though about building a query such as instance.jobproject_events.order_by('date') and then manipulate the result in python. But I was hoping Django had a way of doing it through a query using some sort of groupby. class EventName(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30, null=True) def __str__(self): return self.name class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField(blank=True, null=True) event_name = models.ForeignKey(EventName, blank=True, on_delete=models.CASCADE, related_name='events', null=True) project = models.ForeignKey(JobProject, blank=True, on_delete=models.CASCADE, related_name='jobproject_events', null=True) def __str__(self): return self.project.title + ": "+ str(self.date.strftime("%m/%d/%Y")) + " - "+ str(self.event_name.name) #+ ": from " + str(self.date) #+ " to " + str(self.date_end) -
Guarantee that the results of a QuerySet are not all loaded in-memory
I have a query which will return a massive set of objects, but I just need to iterate over them once. Is calling .iterator() on the queryset enough to guarantee that they won't all be loaded into memory? -
DJango - handle form_invalid errors with ajax-submitted data
I'm looking for a way to keep all of django's builtin stuff for form errors with an ajax submission that returns a django form_invalid() "standard" response. For instance, with a non-ajax request: class SomeCreateView(LoginRequiredMixin, SideBarMixin, CreateView): def form_invalid(self): return self.render_to_response(self.get_context_data()) And then in the template: <div class="container-fluid"> <form action="" method="post" enctype='multipart/form-data'> {{ form.non_field_errors }} ... <div class="wide_items"> {{form.no_form.errors}} {{form.no_form.label_tag}} {{form.no_form}} </div> ... </form> ... I then get all the nice errors messages displayed in the relevent fields/or top of form for non_field_errors etc. However, using the following jquery ajax request: some_handler: function (e, clickedBtn) { // .... some logic to check what to do etc. .... $.ajax({ url: url, type: "POST", data: data, success: function (response) { if (response.status==1) { // form_valid() - reload current page, load some other alert(response.message); location.reload(true); if (response.next_url) { mainjs.open_new_window(response.next_url); } } else if (response.status==0) { // form_invalid - how to manage this? alert(response.message); } }, error: function (xhr, errmsg, err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg + " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom } }); }, In that second case, I'd like some way to directly the response from the regular … -
Django / Python Media rendering not working
Can anyone explain to me what is happening here? I am able to upload images from the admin panel, and the frontend to the 'media/company/logo1.png' folders. its working, and when I delete the folder it re-creates it, no issue. In development I am unable to render the image from the django admin panel, as clicking the image link to view returns "Not Found The requested resource was not found on this server." with the URL "http://13.59.234.9/media/company/mnmade-logo.png" # Settings.py import os STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' # Models.py class Company(models.Model): name=models.CharField(max_length=100, null=False, unique=True) image=models.ImageField(null=True, upload_to="company/") created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) objects = CompanyManager() # add for manager validator class Meta: ordering = ( 'id', 'name', 'image', 'created_at', 'updated_at' ) def __str__(self): return self.name # projects URLS.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('frontend.urls')), path('reports/', include('reports.urls')), path('users/', include('users.urls')), path('company/', include('company.urls')), path('employees/', include('employees.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Views def manage_admin(request): if 'admin_id' not in request.session: return redirect('/signin-company-admin') company = Company.objects.get(admins=request.session['admin_id']) context = { 'admin': Admin.objects.get(id=request.session['admin_id']), 'all_admins': Admin.objects.filter(company=request.session['company_id']), 'company': company, 'locations': Location.objects.filter(company=company.id) } return render(request, … -
Django M2M / Many To Many Relationship to SELF with through table not adding symmetrical reverse
I'm trying to set a Many To Many relationship on a model to itself. I have read up on the whole Symmetrical=True/False settings. I do want the symmetry between the self related models, aka, if the locale1 of model Locale is related to another Locale, locale2, then locale2 should have a reference to get locale1. Below is how I have the models set up Locale and the Many To Many Model/Table RelatedLocale. When I set locale1.related_locales.set([locale2]) only 1 record is created and locale2 can not use 'related_locales' to access locale1. What am missing on the models? shell >>> locale1.related_locales.set([locale2]) >>> locale1.related_locales.all() <QuerySet [<Locale: Locale object (<locale2>)>]> >>> locale2.related_locales.all() <QuerySet []> Models: class Locale(models.Model): """Locale to be used for everything on the Aspiria Campus""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... related_locales = models.ManyToManyField( "Locale", through='RelatedLocale') class Meta: db_table = 'locale' class RelatedLocale(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) locale = models.ForeignKey( Locale, on_delete=models.CASCADE, db_column='locale_id') related_locale = models.ForeignKey( Locale, related_name="related_locale", on_delete=models.CASCADE, db_column='related_locale_id') is_parent = models.BooleanField(default=False) class Meta: db_table = "related_locale" def __str__(self): return "%s related" % self.locale.name