Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update model field using django signals when updating object in m2m field?
I'm trying to update the order total on updating quantity on OrderItem. For that i'm using django signal m2m change with post_add or post_remove action. Here's my model: class Item(models.Model): name = models.CharField(max_length=20, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) class Order(models.Model): order_item = models.ManyToManyField('OrderItem') total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) m2m changes signal def m2m_changed_order_item_receiver(sender, instance, action, *args, **kwargs): """Receiver for updating total of Order through OrderItem""" if action in ["post_add", "post_remove"]: order_items = instance.order_item.all() total = 0 for order_item in order_items: total += order_item.item.price * order_item.quantity instance.total = total instance.save() m2m_changed.connect(m2m_changed_order_item_receiver, sender=Order.order_item.through) Testcase: def test_updating_order_item_quantity_in_order(self): order_item1, order_item1_data = create_sample_order_item( item=self.item1, quantity=2, data_only=False ) order_item2, order_item2_data = create_sample_order_item( item=self.item2, quantity=2, data_only=False ) order, _ = create_sample_order( order_items=[order_item1_data, order_item2_data], data_only=False ) order_items = order.order_item.all() for order_item in order_items: if order_item == order_item2: order_item2.quantity = 10 order_item2.save() order.save() # update order_item2_total = order_item2.item.price * 10 # works completly fine but i'm searching for alternative method using signal # order.order_item.remove(order_item2) # order.order_item.add(order_item2) order.refresh_from_db() order_item1.refresh_from_db() order_item2.refresh_from_db() # check weather OrderItem total is updated or not self.assertEqual(order_item2.total, order_item2_total) # fails here self.assertEqual(order.total, order_item1.total + order_item2.total) It works completly fine when i first remove … -
How do you save a foreikey in the django of an n: m relationship?
views.py `@login_required def add_arquivo(request, id): if str(request.user) != 'AnonymousUser': if str(request.method) == "POST": form_arq = ArquivoForm(request.POST, request.FILES) if form_arq.is_valid(): form_arq.save() arquivo = Arquivo.objects.create(arq_pro_id = id, arq_usu_id = request.user, arq_desc = form_arq.arq_desc, arq_nome = form_arq.arq_nome, arq_imagem = form_arq.arq_imagem, arq_localizacao_documento = form_arq.arq_localizacao_documento) return redirect('/inicio_projeto/')# rediredionando para lista else: form_arq = ArquivoForm() return render(request, 'arquivos/add_arquivo.html', {'form_arq' : form_arq }) else: return redirect('/')` I don't know how I can save this data arq_pro_id and arq_usu_id together with the others. class Arquivo(models.Model): arq_pro_id = models.ForeignKey(Projetos, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Projetos arq_usu_id = models.ForeignKey(Pessoa, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Usuarios arq_desc = models.TextField('Descrição:') arq_nome = models.CharField('Nome:', max_length=100, null=True) arq_imagem = StdImageField('Imagem:', upload_to='imagem_projeto_arq', null=True) arq_localizacao_documento = models.FileField(upload_to='arquivos_projeto', null=True, max_length=1000) this Arquivos table can have several arquivos linked to a project. class Projetos(models.Model): FINANCIAMENTO_CHOICES = ( ("S", "Sim"), ("N", "Não") ) # pro_titulo = models.CharField('Título do projeto:', max_length=100) pro_imagem = StdImageField('Imagem:', upload_to='imagem_projeto', null=True) # pro_autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) pro_desc = models.TextField('Descrição:') pro_financiamento = models.CharField('Financiamento:', max_length=1, choices=FINANCIAMENTO_CHOICES, blank=False, null=False) pro_financiadora = models.CharField('Instituição financiadora:', max_length=100) pro_datetime = models.DateTimeField('Data de publicação:', blank=True, null=True) pro_inst = models.ForeignKey(Instituicao, on_delete=models.CASCADE, null=True) pro_usuarios = models.ManyToManyField( Pessoa, through='ProjetosDosUsuarios', through_fields=('pdu_projetos', 'pdu_usuarios'), # ) def publicar(self): self.pro_datetime = timezone.now() self.save() … -
Django - Signals are not getting called from User model while creating a new user
I am working on simple hands-on project, and using signals to save the Profile which is part of User model. Seems the signals are not getting called. Though i did not encounter any errors so could not trace what is the issue or what config i am missing. I tried using print statement, and got to know that the signals is not even called. Any pointer how i can check what is causing the issue. Please help... Below is the code i am using. #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'images/default.jpg', upload_to = 'images/profile_pic') def __str__(self): return f'{self.user.username} Profile' #signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print('inside signals') if created: print('inside signals ------------------------> create method is called') Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() # modified the app.py to include the method ready(). from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals -
How can i include a foreign key field in the "fields" tuple to make it appear on detail view page in Django Admin
Models: I have a model like this class TestModel1(models.Model): bookingid = models.ForeignKey(paymenttable) // foreign key name = models.CharField(max_length=100, null=False, db_index=True) // I want this to be displayed in both the list view and detail view @property def custom_field(self): return self.bookingid.username Admin.py class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin): // this works and i get custom_field in list view list_display = ('custom_field', 'name') readonly = ('custom_field', 'name') // this dosent work and gives error fields = ('custom_field', 'name') Error: Unknown field(s) custom_field. Check fields/fieldsets/exclude attributes of MyAdmin class -
Convert a Pillow image to a Django Imagefield
I have an imagefield called thumbnail and another called thumbnail_low which is a 320 * 200 version of thumbnail. when the user uploads an image from the thumbnail imagefield I internally create a 320 * 200 version that is assigned to thumbnail_low. that's the way I do it (see the code below). the problem is that the image is correctly assigned to thumbnail_low except that the browser indicates waiting for localhost until my machine crashes which is weird is that after restarting I find that the post has been created correctly. class Post(models.Model): thumbnail = models.ImageField(upload_to=post_directory_path) thumbnail_low = models.ImageField(upload_to=post_directory_path, null=True, blank=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): obj = super(Post, self).save(force_insert, force_update, using, update_fields) if self.thumbnail: img = Image.open(self.thumbnail.path) img = img.convert("RGB") img.save(self.thumbnail.path, format="JPEG", optimized=True) stream = BytesIO() copy = img.copy() copy.thumbnail((320, 200), Image.ANTIALIAS) copy.save(fp=stream, format="JPEG") thumbnail_name = "low" + get_random_string(length=4) + str(self.id) + ".jpeg" content = stream.getvalue() self.thumbnail_low.save(thumbnail_name, ContentFile(content)) return obj -
URL safety in Django E-commerce
I'm working with my own e-commerce in Django and the payments are handled like this: I have a checkout view with a slug (since I'm working with only two products) where the user sumbits their shipping data. Then they are redirected to the payment URL, that is guided by a Primary Key. It looks like this: http://....../payment/24 The problem that worries me is the simplicity of the id, it's just a number that anyone can access with the URL. Is there any way to make this safer? I was thinking about hashing the URL, but didn't find any tool for that. note: It's a guest checkout, so I'm not dealing with registered users. Thanks in advance! -
Alternative Windows/bash command 'workon [insert virtualenv name]' for Mac Terminal
I've seen you can activate virtualenv on Windows bash by typing 'workon [virtualenv name]' is there a similar command for the Mac Terminal which does the same thing? I want to avoid the long way of activating the virtualenv, which is by going into the sub folder that contains 'bin' and then using 'source bin/activate'. -
How can execute two functions respectively in Django?
I have used the code prepared in https://www.pythoncircle.com/ to import and export an excel file using Django. This code is provided below: from Django.shortcuts import render import openpyxl views.py file: def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) worksheet = wb["Sheet1"] print(worksheet) excel_data = list() for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) import xlwt from django.http import HttpResponse def download_excel_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet("sheet1") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Column 1', 'Column 2', 'Column 3', 'Column 4', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() wb.save(response) return response urls.py file: from django.urls import path from django.http import HttpResponse from . import views app_name = "myapp" urlpatterns = [ path('', views.index, name='index'), path('', views.download_excel_data, name='download_excel_data'), ] When I run the described code, only the index function is executed. while when I change the urlpatterns to: urlpatterns = [ path('', views.download_excel_data, name='download_excel_data'), path('', views.index, name='index'), ] the download_excel_data function is executed. How can I execute both functions respectively? Thanks … -
django admin view image file not found
i am new here in django, I have uploaded image file, i can see file is uploaded under my app myapp/mysite/uploads/testimonial/image.jpg file is there, so it is correct, but now when i open that testimonial module in admin, and when i edit that testimonial and click on that view image link it is showing that as this link http://127.0.0.1:8000/uploads/uploads/testimonial/image.jpg, but that is not visible, can anyone please help me why that image is not showing, i am using python version 3.6, here i have mention whole my code, can anyone please look into it and help me to resolve this issue ? models.py class Testimonial(models.Model): def __str__(self): return self.title TESTIMONIAL_STATUS = ((1, 'Active'), (0, 'Inactive')) title = models.CharField(max_length=255) description = HTMLField() image = models.ImageField(upload_to='uploads/testimonial') status = models.PositiveSmallIntegerField(choices=TESTIMONIAL_STATUS, default=1) published_date = models.DateTimeField(auto_now_add=True, blank=True) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/') MEDIA_URL = '/uploads/' urls.py urlpatterns = [ path('', views.index, name='index'), ] -
Filtering with django model object list using dynamic path
I want to do something like this. path = "pk__in" resources = resource_model.objects.filter(path=resource_ids) I would want resources to be a list of objects from resource_model. How can I achieve filtering with dynamic path? -
django registeration verification of email not working
I followed blog https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef for email verification but it adding a user before verification of link. -
Why doesn't my toggle work correctly when I use staticflies?
I am studying Django and found the following problem when using staticsfiles, the toggler that appears when the screen is reduced does not extend my bootstrap navbar, I did not find the error. NOTE: the rest works, dropdown, navbar (css / js) NOTE1: when I use CDN everything works, including the toggler here are the excerpts that I call staticsfiles and the link to the complete project on github settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) scripts.html {% load static %} <script src="{% static 'jquery/dist/jquery.js' %}"></script> <script src="{% static 'popper.js/dist/umd/popper.js'%}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> Projeto no Github -
Which is better - django login or jQuery AJAX?
Django's indigenous login system is a lot confusing, I really don't know whether its even an AJAX call or simple form registration plus the security concerns with it is not really specified anywhere on the internet. I used jQuery AJAX for all form submissions till yesterday and now that this Django feature of login is an integrated Django feature I'm using it. Is this login methodology better over the AJAX calls? -
Django - How do I had a "points" field to my User model
I'm making an online quizz but when I add a "points" field to my User model, I have an error (I added the app in INSTALLED_APPS). So, I created a UserPoints model in my models.py : from django.db import models from django.contrib.auth.models import User class UserPoints(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) def AddPoints(self, amount): self.amount = amount self.points += amount self.save() Then I resgistered it in admin.py : from django.contrib import admin from .models import UserPoints admin.site.register(UserPoints) But when I type python manage.py makemigrations I have this error : You are trying to add a non-nullable field 'id' to pointsutilisateur without a default; we can't do that (the database needs something to populate existing rows) -
Python multiprocessing fails silently while generate cache with many keys
I want to populate cache (memcached) for a Django apps with Python Multiprocessing. The function create_cache(keys) create cache for memcached. About 5 Millions Keys. Factor from slowest to speadest create cache is about 10. I use BaseCommand of Django to launch following python script : #python imports import multiprocessing as mp # django imports from django.core.management.base import BaseCommand from .../apps import create_cache class Command(BaseCommand): def handle(self, *args, **options): keys =[....] core_number = mp.cpu_count() len_keys = len(keys) chunk_size = int(len_keys / core_number / 10) print ("total len",len_keys, "chunk_size",chunk_size) pool = mp.Pool(core_number) try: pool.imap_unordered(create_cache, keys, chunk_size) except Exception as e: print("a worker failed, aborting...",e) pool.close() pool.terminate() else: print("before close") pool.close() pool.join() print("after join") This code works for some thousands of keys, but after 10 000 keys, It fails after "before close", and process stay iddle, and not all the keys are created (I check with stats in memcached). In addition I can't CTR+C this process, I have to kill it in a terminal. I fix this issue with adding a sleep(0.0001) in create_cache before cache.set(key,result), but it slow down the script. I'am woundering why Multiprocessing lost memcached when too many keys ? Ubuntu 16.04, Python 2.7, Django 1.4 -
I cant able to add the product images , it is showing the attribute error,
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Product(models.Model): CONDITION_TYPE = ( ("New", "New"), ("Used", "Used"), ) name = models.CharField(max_length=50) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, null=True) brand = models.ForeignKey( 'Brand', on_delete=models.SET_NULL, blank=True, null=True) description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) condition = models.CharField(max_length=50, choices=CONDITION_TYPE) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Category(models.Model): category_name = models.CharField(max_length=50) image = models.ImageField(upload_to='product/', blank=True, null=True) def __str__(self): return self.category_name class Meta: verbose_name = 'category' verbose_name_plural = 'categories' class Brand(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Meta: verbose_name = 'brand' verbose_name_plural = 'brands' class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_image = models.ImageField( upload_to='categories/', null=True, blank=True) def __str__(self): return self.Product class Meta: verbose_name = 'product images' verbose_name_plural = 'product images' When I am adding the product images in the admin panel section, It is showing the attribute error.. AttributeError at /admin/product/productimages/add/ 'ProductImages' object has no attribute 'Product' Request Method: POST Request URL: http://127.0.0.1:8000/admin/product/productimages/add/ Django Version: 3.0.5 Exception Type: AttributeError Exception Value: 'ProductImages' object has no attribute 'Product' Exception Location: /home/durga/Desktop/django_projects/olx_clone/src/product/models.py in str, line 59 Python Executable: /home/durga/Desktop/django_projects/olx_clone/bin/python Python Version: 3.7.5 Python Path: ['/home/durga/Desktop/django_projects/olx_clone/src', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/durga/Desktop/django_projects/olx_clone/lib/python3.7/site-packages'] Server time: Wed, … -
Configurate MSSQL Server with Django
I have installed **appdirs==1.4.3 asgiref==3.2.7 distlib==0.3.0 Django==2.1.15 django-mssql==1.8 django-mssql-backend==2.8.1 django-pyodbc-azure==2.1.0.0 filelock==3.0.12 pyodbc==4.0.30 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 virtualenv==20.0.18 virtualenvwrapper-win==1.2.6** My settings.py file in the database section looks like this DATABASES = { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'localhost', 'HOST': 'localhost', 'USER': 'dbo', 'PASSWORD': '', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } I got the following error after run py manage.py migrate File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 167, in ensure_defaults conn = self.databases[alias] File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 37, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 154, in databases if self._databases[DEFAULT_DB_ALIAS] == {}: KeyError: 'default' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen … -
Django reverse , reverse lazy and resolve
Hello i am new in django and the words resolve, reverse and reverse lazy are too much confusing i didn't get all these words in django please help me to understand these words Answer will be appreciated -
How do I get a files absolute path after being uploaded pdf files and converted it into csv in Django?
What I have done: 1.User uploads a pdf file 2.coverted into text and extract values and store in DB 3.pdf table extracted by Camelot and then convert it into CSV and store it in a different folder 4.return the path to a function so as to iterate the CSV file and store it into DB. But the problem I faced: the table data convert into CSV and store it into its folder but I cannot return the path with the file(.csv) extension. ''' def upload(request): if request.method == 'POST': pos = Model.objects.all() form = ModelForm(request.POST, request.FILES) if form.is_valid(): form.save() file_name = form.cleaned_data['pdf'].name file_name1 = form.cleaned_data['choose'] get_file = Model.objects.last() print(file_name1) print(form.cleaned_data['pdf'].name) text=convert_pdf_to_txt(file_name) #In there converts the pdf file and returns text file in #this finction. print(text) path = '/pos/pdfs/{}'.format(file_name) if file_name1 == "x": #here check for which pdf text and its own regex. #different pdf different regex. regex_Q ='len:\s?([0-9]+)' regex_no ='patch\s\s\s\s?([0-9]+)' Q_No=get_info_from_text(text,regex_Q ) s_No=get_info_from_text(text,regex_no ) elif file_name1 == "y": regex_Q = 'Un\s?([0-9\,]+)' regex_no = 'Nu\s?([0-9]+)' Q_No = get_info_from_text(text, regex_Q ) s_No = get_info_from_text(text, regex_no) data = tables_extract(path) #in here csv directory path will return and i want to iterate it #with csv reader #and put it into my Model or ORM … -
Django Url in JQuery
I am using jquery's autocomplete with ajax and django. The search feature exists on the navigation bar so it can be used from any url within the site. The issue I am running into is the link to be selected from the autocomplete dropdown. I have attempted passing in a django url like shown below in main.js but this leads to the url containing the characters '{% show_person %}' appended onto the end of the current url which obviously isn't the desire. main.js: the success parameter within the ajax call. ... success: function(a) { //console.log(a) $("#autocomplete").autocomplete({ source: a, select: function(event, ui) { event.preventDefault(); window.location.href = '{% url show_person %}'; }, minLength: 1, }) } Additionally, instead of the django url used above I have also tried window.location.href = "person/"+ui.item.value;. This ends up just appending person/<personid> onto whatever the current url is. What I would like to happen is for the url to be mapped directly to the corresponding person's page, but this only works now if I am on the index page because there the url is empty and the appendage works. -
How to get the server name in Python Django?
How to get the server name in Python Django? we hosted Django application in AWS - Apache machine which have more than 1 server and increased based on load. Now i need to find from which server the particular request is made and from which server we got the response. I am using Python 3.6, Django,Django restframework, Apache server on AWS machine. -
Authenticating using mysql in django
I am new to Django and noob in that concepts. According to my knowledge i am trying to connect the django page to the mysql database. The insertion to the database using form is done correctly, but when i am trying to login with credentials it throws an error. This was very important for my college graduation. It shows an error called 'NoneType' object is not subscriptable'. Tq for ur suggestions def login(request): email= request.POST['email'] password=request.POST['password'] con = mysql.connector.connect(user='root', password='', host='localhost', database='company') cur = con.cursor() cur.execute("SELECT email,password from buyerregister where 'email' = '"+email+"' and 'password' = '"+password+"' ") data=cur.fetchone() con.commit() cur.close() con.close() if data[2] == email and data[3] == password: return render(request, "purchase.html") else: return render(request, "order.html") -
Static File Issue with DJango and Heroku
This is a well-known issue and I have gone through a lot of such posts and applied different possibilities. But neither the problem is clear to me nor any solution worked. Let me give you the best possible problem description. I have a Django application. The folder structure is as follows, C:. ├───myproject │ └───__pycache__ └───main ├───migrations │ └───__pycache__ ├───static │ ├───css │ └───js ├───templates │ ├───main │ └───registration └───__pycache As you can see, the css and jss files are inside a folder named static In the HTMLs I access the static files as follows, {% load static %} <link href="{% static "/css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "/css/mystyle.css" %}" rel="stylesheet"> When I run the Django's built in server locally the files are accessed like, http://127.0.0.1:8000/static/css/mystyle.css in the browser and it works flawlessly. Now, comes to the Heroku deployment part. I have gone through the official page, https://devcenter.heroku.com/articles/django-assets I modified my settings.py file as, BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' MIDDLEWARE_CLASSES = ( 'whitenoise.middleware.WhiteNoiseMiddleware', ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) Now, after performing the builds I saw in the build log (Heroku cloud) the following line, python manage.py collectstatic --noinput So, it collects all the static files … -
Django import-export - Problem with ForeignKeyWidget
i am trying to insert bulk data into database i am using Django import_export option for importing data i need only import button. i added a foreign key widget for getting the corresponding data. but i got an issue please check the details model.py class Clip(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) dialogflow_intent_name = models.CharField(max_length=128) start_timestamp = models.CharField(max_length=32) end_timestamp = models.CharField(max_length=32) forms.py from django import forms from import_export.forms import ImportForm, ConfirmImportForm from .models import Subject class CustomImportForm(ImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) class CustomConfirmImportForm(ConfirmImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) resource.py from import_export import resources,fields from .models import Clip,Subject from import_export.widgets import ForeignKeyWidget class ClipResource(resources.ModelResource): subject = fields.Field( column_name='subject', attribute='subject', widget=ForeignKeyWidget(Subject)) class Meta: model = Clip fields = ('dialogflow_intent_name','start_timestamp','end_timestamp','subject') export_order = ('dialogflow_intent_name','start_timestamp','end_timestamp','subject') skip_unchanged = True report_skipped = True use_transactions = True admin.py class CustomClipAdmin(ImportMixin, ClipAdmin): resource_class = ClipResource formats = (base_formats.XLS, base_formats.CSV) def get_import_form(self): return CustomImportForm def get_confirm_import_form(self): return CustomConfirmImportForm def get_form_kwargs(self, form, *args, **kwargs): if isinstance(form, CustomImportForm): if form.is_valid(): subject = form.cleaned_data['subject'] kwargs.update({'subject': subject.id}) return kwargs Corresponing table contain 5 files - id(primary key),dialogflow_intent_name,start_timestamp,end_timestamp,subject_id(ForeignKey) Bt i found an error and i cant import the data : issue is attached, here id is my primary key and xls file contain 3 field dialogflow_intent_name,start_timestamp,end_timestamp,and … -
m learning..how to check in html file with jinja format ? it gives me error Could not parse the remainder: '>4000' from 'x.price>4000'
{%for x in dest%} <div class="destination item"> <div class="destination_image"> <img src="{{baseurl}}/{{x.image}}" alt=""> {% if x.price > 4000%} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {%endif%} </div> <div class="destination_content"> <div class="destination_title"><a href="{% static 'destinations.html'%}">{{x.name}}</a></div> <div class="destination_subtitle"><p>{{x.desc}}</p></div> <div class="destination_price">{{x.price}}</div> </div> </div> {% endfor %} What is the problem at if statement above?? i tried to access the line special offer but error says couldnot parse the remainder.