Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get users spent time on a task with Djanog?
I have Django project and several views. In one view i want to track users spent time. How can i do that? Maybe some libraries or django built in methods? Little bit more about view: when user open view he can see many photoes, and then he need to choose similar and save. Then page reloads with new photoes and task is similar, find similar photoes and submit. I need to track and store that time what each user spent on this task. If i check users time when he open view i don't know when she close it, and also user can just open view and chill, without doing something. How or with i can realize it? -
How do I include a Django project's README.md in a template?
I want to add the text of the readme to a custom index template in admin. So I have the following relevant paths in the project: ./README.md ./impact_api/templates/admin/index.html And in the project settings I have TEMPLATES = [ { 'DIRS': [BASE_DIR / 'templates'], ...}] So in the index.html file I want to do something like this: {% include "../../README.md" %} But that raises an error: TemplateSyntaxError at /admin/ The relative path '"../../README.md"' points outside the file hierarchy that template 'admin/index.html' is in. The only things I can think of are a) to move the README into the body, which I'm not sure I can do without losing the display on Github and seems like a bad idea even if I can, or to change the templates lookup path to the entire project, which also seems like a terrible idea. Is there a more sensible option? -
IndexError: list index out of range Django and Postgresql DB
I'm getting mad with this issue, so please help hahahahaha. the error i have is IndexError: list index out of range, when i try do an insert to in table of my DB. I'm trying insert a svc document with only 30 rows. any idea? class CamerasBaleares(TimeStampedModel, SoftDeletableModel): title = models.CharField(max_length=50, blank=True) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) url = models.URLField(blank=True) is_removed = models.BooleanField(default=False) def __str__(self): return self.title def load_data(self): import csv self.file = open(r'/home/elsamex/Documentos/CamarasBaleares.csv') self.row = csv.reader(self.file, delimiter='"') self.list = list(self.row) self.tupla = tuple(self.list) def save_data(self): import psycopg2 self.connection = psycopg2.connect("dbname=camarasdgt user=******* password=++++++++") self.cursor = self.connection.cursor() self.cursor.executemany ("INSERT INTO api_camerasbaleares (title, lat, lon, url) VALUES (%s, %s, %s, %s)", self.tupla) self.connection.commit() self.cursor.close() self.connection.close() def select (self): self.load_data() self.save_data() self.cursor = self.connection.cursor() self.cursor.execute("""SELECT * FROM api_camerasbaleares""") self.rows = self.cursor.fetchall() self.cursor.close() self.connection.close() return self.rows ins_db= CamerasBaleares() ins_db.load_data() ins_db.save_data() ins_db.select() -
Django Bootstrap 5 - Custom styling
I am using django-bootstrap5 in a Django project. According to the docs, for customization, I can add the following to settings.py: BOOTSTRAP5 = { "css_url": {}, # I could add a custom URL here "theme_url": "..." # Or I could override the theme here } Which seems overkill for only a few customizations. How can I customize something like the primary colour of Bootstrap? Do I have to use Sass/Scss, and if so, how does one do this in Django? -
django when viewing other users profile i get the logged user's profile
New to Django and i can't figure out why i keep getting the profile view of the user I logged in with when i try to view other user's profile. HTML: {% extends "Portfolio/base.html" %} {% block content %} <body> <a href=""><i class="bi bi-pencil"></i>Send Message</a> {% for message in message_list %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ message.sender_user.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'profile-detail' message.sender_user.id %}">{{message.sender_user.username}}</a><small class="text-muted">&emsp; {{message.date_posted}}</small></p> {# |date:"F d, Y" #} </div> <p class="article-content mb-4">{{message.content|safe}}</p> </div> </article> <p>{{message.seen}}</p> {% endfor %} Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Views: ''' User Profile ''' class ProfileDetailView(DetailView): template_name = 'user/profile_detail.html' # <app>/<model>_<viewtype>.html model = Profile fields=('image') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) URLs path('profile/<int:pk>', user_views.ProfileDetailView.as_view(), name='profile-detail'), -
How to deploy Django Based Server and Laravel Project Simultaneously on a Single Droplet
I am new to Digital Ocean and was wondering on how to deploy Django and Laravel code side-by-side. The code works fine locally but I don't know how to deploy the both sources over Digital Ocean droplet. We bought cloudways server but it doesn't offer anything other than PHP which was the limitation. So, we don't have any experience with deployment on Digital Ocean. Is there anyone who can help me with this? Thank you! -
How to send parameter from Django to JavaScript function
I would like to know how I can send a parameter value from Django (View, Form, etc) to JavaScript function in js file. I have a Contact app: Models.py class Contact(models.Model): firstname = models.CharField(max_length=100, verbose_name='Nombre') lastname = models.CharField(max_length=100, verbose_name='Apellidos') email = models.EmailField(max_length=100, verbose_name='eMail') message = models.TextField(max_length=1000, verbose_name='Mensaje') created = models.DateTimeField(auto_now_add=True, verbose_name='Creado') updated = models.DateTimeField(auto_now=True, verbose_name='Editado') class Meta(): verbose_name = 'Contacta Mensaje' verbose_name_plural = 'Contacta Mensajes' ordering = ['-created'] def __str__(self): return str(self.email) Forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ("firstname", "lastname", "email", "message") widgets = { 'firstname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_firstname'}), 'lastname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_lastname'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'id': 'id_email'}), 'message': forms.Textarea(attrs={'class':'form-control', 'id': 'id_message'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) View.py class ContactView(CreateView): form_class = ContactForm template_name = 'core/contact.html' JS function in theme.js forms: function () { (function() { "use strict"; window.addEventListener("load", function() { var forms = document.querySelectorAll(".needs-validation"); var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener("submit", function(event) { if(form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add("was-validated"); if(form.checkValidity() === true) { event.preventDefault(); form.classList.remove("was-validated"); // Send message only if the form has class .contact-form var isContactForm = form.classList.contains('contact-form'); console.log(isContactForm); if(isContactForm) { var data = new FormData(form); var alertClass = 'alert-danger'; fetch("", { method: "post", body: data }).then((data) => { if(data.ok) { … -
Django Unknown column in field list error
I am unsure why I am getting this error when I load order_processing.html django.db.utils.OperationalError: (1054, "Unknown column 'orchestration_ce_base.model' in 'field list'") In models.py, I have just added the these: model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) I assume they have not been created in the database. I have tried running makemigrations/migrate, but no changes are detected. When the html page is loaded it is throwing an error. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.order_name class Ce_Base(models.Model): ROUTER_MODELS = ( ('CISCO2901', 'CISCO2901'), ('ISR4331', 'ISR4331'), ('CISCO1921', 'CISCO1921'), ('ISR4351', 'ISR4351'), ('ISR4451', 'ISR4451'), ('ISR4231', 'ISR4231'), ('ISR4431', 'ISR4431'), ('ISR4461', 'ISR4461'), ) REGION = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ) ce_hostname = models.CharField(max_length=15) new = models.BooleanField() location = models.TextField(null=True, blank=True) model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Order from .models import Ce_Base from .forms import OrderForm #from .tables import OrderTable #from django_tables2 import … -
Django Detail View on Boostrap Modal?
Am in the process of building an Ecomerce app with django and although am comming along just fine, I can't seem to be able to render the details of a specific object on a bootstrap modal. This is a screenshot of what am trying to get rendered on the modal This is the modal being display but no image or data being passed to it I went around searching and saw that modals can be rendered with Ajax but haven't found any solid article so far. I would appreciate if anyone could provide a source or a quick sample on how to pull this off. NOTE: I am able to render the detail view as a standalone view as you can see in the image that will follow:Detail View My views: def product_list(request, category_slug=None): # category_slug parameter gives us the ability to optionally filter product by a give category category = None categories = Category.objects.all() # Available=True to filter only the available products products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) paginator = Paginator(products, 9) # Show 9 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # -> Adds the "add to cart" form to … -
Deploying Django Web App with Apache2 on Ec2 Instance
I have come back to AWS and now the old methods don't work anymore. I have followed an instruction manual on the internet to deploy my web app but I run into this 403 Forbidden page. The security groups are entered and everything else is also according to the instructions. So what is wrong here. This is my 000-default.conf <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/django/hosp_app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/hosp_app/static <Directory /home/ubuntu/django/hosp_app/static> Require all granted </Directory> <Directory /home/ubuntu/django/hosp_app/hosp_app> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> WSGIDaemonProcess hosp_app python-path=/home/ubuntu/django/hosp_app python-home=/home/ubuntu/django/hosp_app_env WSGIProcessGroup hosp_app WSGIScriptAlias / /home/ubuntu/django/hosp_app/hosp_app/wsgi.py </VirtualHost> I am in a bit of a hurry so please help. Thanks -
How To send live video frame to server(python side) while using webrtc?
I want to make a Video conferencing app like zoom. I decided to use webrtc, django and django-channel. I want to use mahine learning in live stream video using opencv and deep learning models. How can I do such things, I know for that, we need to send video frame to server side but I could not do due to p2p browser connection after initial offer/answer exchange. Plsese any reference can you provide?? I did not find any answer? -
Django. How to show only related choices in a two table relationship?
Why does this work? This is hard coded with contrato_id = 1, but the goal dynamicaly present related choices, not the full table model. class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'].queryset=FaturaBlog.objects.filter(id_contrato=1).all() But none of them works? a) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'].queryset = FaturaBlog.objects.filter(id_contrato=self.object.pk).all() Exception Type: AttributeError Exception Value: 'LancamentoBlogForm' object has no attribute 'object' b) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.id_fatura_choices = [*forms.ModelChoiceField(FaturaBlog.objects.filter(id_contrato=self.object.pk).all().choices)] Exception Type: AttributeError Exception Value: 'LancamentoBlogForm' object has no attribute 'object' c) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = FaturaBlog.objects.filter(id_contrato=contratoblog__id).all() Exception Type: NameError Exception Value: name 'contratoblog__id' is not defined d) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = super(LancamentoFormset, self).get_context_data() Exception Type: AttributeError Exception Value: 'super' object has no attribute 'get_context_data' BUT I do have context, as return self.render(context) returns data for base.html context [{'True': True, 'False': False, 'None': None}, {}, {}, {'object': <ContratoBlog: Terceiro Contrato Blog>, 'contratoblog': <ContratoBlog: Terceiro Contrato Blog>, 'form': <django.forms.formsets.LancamentoBlogFormFormSet object at 0x107cfb0d0>, 'view': <blog.views.ContratoLancamentoEdit object at 0x107cfb0a0>, 'contrato_dados': <ContratoBlog: Terceiro Contrato Blog>, 'fatura_list': <QuerySet [<FaturaBlog: c.3.vct.2022-07-15>, <FaturaBlog: c.3.vct.2022-08-15>, <FaturaBlog: c.3.vct.2022-09-15>]>, 'lancamento_list': <QuerySet [<LancamentoBlog: L7.2022-02-01>, <LancamentoBlog: L8.2022-04-01>, <LancamentoBlog: L9.2022-06-01>]>}] e) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = FaturaBlog.objects.filter(id_contrato = lancamentoblog__id_contrato).all() Exception Type: NameError Exception Value: name … -
SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in Django Model
I have the following Django Model class Tag(models.Model): name = models.CharField(max_length=50, unique=True, editable=False) created_at = models.DateTimeField(default=datetime.now, editable=False) When I try to create an object like below, Tag.objects.create(name='me','created_at'=str(datetime.now())) I get the following error Tag.objects.create(name='me','created_at'=str(datetime.now())) ^^^^^^^^^^^^^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="? What am I doing wrong here? -
python: can't open file 'C:\\usr\\local\\bin\\django-admin.py': [Errno 2] No such file or directory
Whenever I say "python manage.py startproject myproject" while trying to make a website with Django, I get this error. I'm using python 3.10.4. What can i do? -
Django UUID Field does not autocreate with new entry
I just added a new model where I want to use a UUID for the first time. I run django 3.1.3 on python 3.8.10. Found some questions about this and I am quite certain I did it according to those suggestions. However, when I add an entry to that model (in phpmyadmin web-surface) the UUID is not being added, it just stays empty. However when I create an other one I get the error, that the UUID Field is not allowed to be the same as somewhere else (both empty) wich means at least the unique=True does work. Another thing to mention is, when I create the field using VSCode, normally those fieldnames are being auto-completed, however it is not the case with this one. Thought this might give you a hint what is going on. My model looks like this: from django.db import models import uuid class MQTTTable(models.Model): uuid = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False, unique = True) description = models.CharField(max_length= 100, default = None) clientID = models.CharField(max_length = 50, default = None) mastertopic = models.CharField(max_length = 200, default = None) -
Django form fields not rendering when grouping fields
I am using Django 4.0.3 with a bootstrap webinterface. For layout reasons I want my fields in a ModelForm to be grouped and I'm doing it with: class UserForm(ModelForm): template_name = "container/form.html" field_groups = [["email", "company"], ["last_name", "first_name"]] grouped_fields = [] class Meta: model = MyUser fields = ["email", "company", "first_name", "last_name"] __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) def group_fields(self): for group in self._field_groups: group_entry = [] for entry in group: group_entry.append(self.fields[entry]) self.grouped_fields.append(group_entry) in the view I initialize my form and the regroup the fields: def user_form(request): form = UserForm() form.group_fields() render(request, "page.html, {"form", form}) The page.html looks like this: <body> <div id="form-wrapper"> {{ form }} </div> </body> and the form.html looks like this: <form action="" method="POST">{% csrf_token %} {% for field_group in form.grouped_fields %} <div class="row"> {% for field in field_group %} <div class="col"> <label>{{ field.label }}</label> {{ field }} </div> {% endfor %} </div> {% endfor %} However the rendered fields are displayed as string representations of the field objects: Email <django.forms.fields.EmailField object at 0x7f98c00e03a0> Company <django.forms.fields.CharField object at 0x7f98c00e0250> Last name <django.forms.fields.CharField object at 0x7f98c00e0790> First name <django.forms.fields.CharField object at 0x7f98c00e10c0> Whereas a common call renders as expected a form with input fields, but not with the … -
How to filter queryset with mutiple m2m values?
I'm tryna filter Seo model here. I want to get objects that has the brand dependency and the model dependency. Code class SeoListView(generics.ListAPIView): serializer_class = SeoListSerializer def get_queryset(self) -> QuerySet: queryset = Seo.objects.all() dependencies = self.request.query_params.get('dependencies') if dependencies is not None: dependencies = [str(dep).strip() for dep in dependencies.split(',')] print(dependencies) # for dep in dependencies: # query.add(Q(dependencies__dependency__exact=dep), Q.AND) query = reduce(lambda q, dep: q & Q(dependencies__dependency__exact=dep), dependencies, Q()) queryset = queryset.filter(query) return queryset class Dependency(models.Model): dependency = models.SlugField( 'Зависимость', unique=True, help_text='Перечислите зависимости через нижнее подчеркивание. Пример: brand_model' ) def __str__(self) -> str: return f'Зависимость {self.dependency}' class Meta: verbose_name = 'Зависимость' verbose_name_plural = 'Зависимости' class Seo(models.Model): statuses = ( (1, 'Дефолтная'), (2, 'Дополнительная') ) _delimiter = SEOService().delimiter _help_text = ( f'Если вы ввели Купить {_delimiter}, а зависимость - car,' f' то после сохранения получится Купить car машину. ' f'Все {_delimiter} заменяются на соотв. им зависимости.' ) dependencies = models.ManyToManyField( Dependency, verbose_name='Зависимости', blank=True, help_text='Оставьте пустым, если это дефолтный шаблон.' ) h1 = models.CharField( 'Заголовок(h1)', max_length=200, help_text=_help_text ) title = models.CharField( 'Заголовок(title)', max_length=200, help_text=_help_text ) description = models.CharField( 'Описание', max_length=200, help_text=_help_text ) keywords = models.TextField( 'Ключевые слова', help_text=_help_text ) status = models.IntegerField('Статус', choices=statuses, blank=True, help_text='Не трогать руками', null=True) def __str__(self) -> str: return f'Настройка … -
trying to use web scrapper in my application [closed]
DevTools listening on ws://127.0.0.1:1731/devtools/browser/ffe6022f-8d1b-41a0-8ab8-b2bd80fdf8b1 [16224:17484:0517/085953.922:ERROR:device_event_log_impl.cc(214)] [08:59:53.926] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F) Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "C:\Users\Razer\Downloads\WEb scrapper\mysite\polls\views.py", line 245, in start wait.until(EC.presence_of_all_elements_located( File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 89, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: [9564:3800:0517/090149.183:ERROR:gpu_init.cc(481)] Passthrough is not supported, GL is disabled, ANGLE is [16224:17484:0517/085953.922:ERROR:device_event_log_impl.cc(214)] [08:59:53.926] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F) Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "C:\Users\Razer\Downloads\WEb scrapper\mysite\polls\views.py", line 245, in start wait.until(EC.presence_of_all_elements_located( File "C:\Users\Razer\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 89, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: -
EntityChoiceWidget is missing a QuerySet. django-select2
I'm getting this error when using django-select2: EntityChoiceWidget is missing a QuerySet. Define EntityChoiceWidget.model, EntityChoiceWidget.queryset, or override EntityChoiceWidget.get_queryset(). and I don't know what does it mean. {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> {{ field|label_with_class:"col-sm-2 control-label" }} <div class="col-xs-4"> X {{ field|input_with_class:"form-control" }} {% for e in field.errors %}<span class="help-block">{{ e }}</span>{% endfor %} </div> </div> {% endfor %} The whole stacktrace points to the site-packages/ directory, so there might be something wrong with my package. I'm using Django 1.11 and django-select2 5.9.0. I tried upgrading django-select2 to the newest version I could use with Django 1.11 (6.3.1) and I'm still getting this error. Why can this error be happening and how can I fix it? -
How to query User model by 'custom' fields? (django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor)
I extended the User model using my account app. Model Account app: from django.db import models from django.contrib.auth.models import User from departments.models import Department class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) department = models.ForeignKey( Department, on_delete=models.SET_NULL, null=True, related_name='department') def __str__(self): return self.user.username Now I need to send the count of users from the same department to my template... View: from django.contrib.auth.models import User @login_required def home(request): context = { 'title': 'Dashboard', 'department_members': 'department_members': User.objects.filter(department=request.user.account.department).count(), } return render(request, 'app/dashboard.html', context)\ department_members is always 1 even though I have more users on the same department. I figure that the problem is that User don't have department field by default, so I can't say User.account.objects.filter(department=request.user.account.department) I've tried a lot of queries and looked into django docs but I could't find the proper manner on how to retrieve this info. Anyone have the same problem? Any tips on how I can debug/create my query in a better way? Thanks to all in advance! -
Django product update / inline formsets updating a model
I am creating an E-commerce website, I'm having a problem when I'm updating images of the product, I can update the form `but I can't update the images. can you guys tell what am I doing wrong ? this is my code: views.py class ProductEditView(UpdateView): model = Product form = ProductUpdateForm fields='__all__' product_metas = ProductUpdateMetaForm template_name = 'products/update_product.html' product_meta_formset = ProductMetaInlineFormset() meta = product_metas ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5) def form_valid(self, form): response = super(ProductEditView, self).form_valid(form) if self.request.method == 'POST': product_meta_formset = self.ProductMetaInlineFormset(self.request.POST, self.request.FILES, instance=self.object) product_meta_formset.save() return response def get_context_data(self, **kwargs): context = super(ProductEditView, self).get_context_data(**kwargs) context['product_meta_formset'] = self.ProductMetaInlineFormset(instance=self.object) return context forms.py class ProductUpdateMetaForm(forms.ModelForm): class Meta: model = Image fields = ['image', 'is_feature', ] ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5,) update_product.html <div class="container mt-4"> <form enctype="multipart/form-data" action= "." method="POST" class="ui form"> {% csrf_token %} <div class="card"> <div class="card-body"> {{ form.non_form_errors }} {{ form.as_p }} {{ product_meta_formset.non_form_errors }} {{ product_meta_formset.management_form}} {% for form in product_meta_formset %} <div class="d-flex py-1 inline {{ product_meta_formset.prefix }}"> <div>{{form.image.label}}: {{ form.image }}</div> <div class="ml-4">{{form.is_feature.label}}: {{ form.is_feature }}</div> {% if product_meta_formset.can_delete %} <div class="ml-4">{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} </div> {% endfor %} </div> </div> <button type='submit' class = 'ui positive button mtop'>Update product</button> … -
Django convert model objects to dictionary in large volumes results in server timeout
I have been having a problem where a Django server takes forever to return a response. When running with gunicorn in Heroku I get a timeout, so can't receive the response. If I run locally, it takes a while, but after some time it correctly shows the site. Basically I have two models: class Entry(models.Model): #Some stuff charFields, foreignKey, TextField and ManyToMany fields #Eg of m2m field: tags = models.ManyToManyField(Tag, blank=True) def getTags(self): ret = [] for tag in self.tags.all(): ret.append(getattr(tag, "name")) return ret def convertToDict(self): #for the many to many field I run the getter return {'id': self.id, 'tags' : self.getTags(), ... all the other fields ... } class EntryState(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE) def convertToDict(self): temp = self.entry.convertToDict() temp['field1'] = self.field1 temp['field2'] = self.field1 + self.field3 return temp Then I have a view: def myView(request): entries = list(EntryState.objects.filter(field1 < 10)) dictData = {'entries' : []} for entry in entries: dictData['entries'].append(entry.convertToDict()) context = {'dictData': dictData} return render(request, 'my_template.html', context) The way it was done, the dictData contains the information for all the entries that must be shown in the site. Then, this variable gets loaded into a javascript that will decide how to display the information. The view gets … -
What is the proper documentation for using django channels on azure app services?
I am trying to deploy a web app on azure app service All the http request work just fine as one would expect there just one problem none of the websockets work I am using in memory channels version 2.4.0 and django version 2.2.15 The problem is azure just can not show me proper logs that django shows when running on local server -
django: Query regarding radio buttons
The requirement is that I have a set of questions, and I want the responses to be provided by selecting a value which is rendered using radio buttons. The issue here is, say, we have: Question 1: o option 1 x option 2 o option 3 Question 2: o option 1 o option 2 o option 3 where 'o' represents un-selected options and 'x' - represents an option that has been selected. Now, when trying to check option3 under question 2 it unselects the response to the previous question i.e., Question1. Question 1: o option 1 o option 2 o option 3 Question 2: o option 1 o option 2 x option 3 How do we decouple the radio button responses for each field?? Any help would be appreciated. Thanks!! -
How to force insert custom value in datetimefield(auto_now_add=True) while object creation in Django?
I have a model Test in service A class Test(models.Model): some_field = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I am migrating data from a different service B's model to this model (using APIs). Exposed an API in service A which reads from POST data sent from the B, and saves the data in this Test model. Sample data coming from service B data = { 'some_field': 5, 'created_at': '2013-06-26 00:14:27.260524', } Now when I save this data in the db using: obj = Test( some_field=request.POST.get('some_field'), created_at=request.POST.get('created_at'), ) obj.save() The created_at values of saved object is the current time. Not the created_at coming from the API. How to bypass this current time saving in this scenario and save the timestamp coming from the API while creating the object?