Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
automatic Image resizing for every uploaded images by users
I have a web application that allows user to upload tons of images, My goal is to reduce the hosting fees AWS are going to charge me by shrink the image size users uploaded, Currently i set the limit to 1MB using simple Js, I am not really a frontend developer, So How hard it is to create a javascript solution that automatically shrinks the image size? Is this can be done easily? If not, then my other two options are Django and AWS UI, the backend is Django, But Django can only process the image once it reaches the backend, So if this happens, Would my aws cost increase? Finally it's the AWS solution, I don't know how to do it yet, Maybe using something called lambda? Is it completely free? If it keeps my cost down and easy to set up then this is it? Or would it be wise just to use simple javascript? is this can be easily implemented? like copy and paste code less than 50lines of code then it's automatically solved? -
Djnago reads images without defining MEDIA_URL
I'm new to Django, I know that to display an image I should define MEDIA_URL in the settings but when I tried to remove it and use the {{ img.url }} and still the images are readable and the browser can see it and display it, the question is does this mean that the MEDIA_URL does not import in displaying images -
Django Models: Setting up daily time slots
I’ve been thinking about this for a while, and not getting anywhere. Using Django, I’m trying to set up a time slot reservation web app, but I’m getting hung up on how to set up the models. Essentially, every day of the week would have time slots offered like: 09:00, 09:10, 09:20, 09:30, 09:40, etc. And each of those time slots would include the specified time, date, and count of people. My first try... I was initially thinking I’d make records for every time slot, for every day of the week; then I could query that to display available time slots on the website. That seems really inefficient though, because I’d have to create around 70 entries for each day of the week. My Second Try... Then I was thinking I’d just lay out all of the time slots on the website itself, then when someone reserves one of the slots, save that to the database. However, doing that, I’m not sure how I would then NOT display that time slot on the site. I included a rough mockup below to describe what I'm trying to accomplish. Any ideas that would lead me the right direction would be great. Thanks! … -
When i try to iterate over a RawQuerySet object in django i get "django.db.utils.ProgrammingError: can't adapt type 'dict'"
for example lets say books.objects.raw(....) the (...) are a representation of the sql parameters for example as seen in the django docs https://docs.djangoproject.com/en/3.2/topics/db/sql/#:~:text=Django%20gives%20you%20two%20ways,ORM%20before%20using%20raw%20SQL! when i try to iterate through the above oject like so [print(x) for x in books.ojects.raw(...)] I get this from my logs below django.db.utils.ProgrammingError: can't adapt type 'dict' -
can I use the value of the arguments more than once
My problem is in python/django I want to use the value of my argument entry before passing it on to my function util.get_entry Below is my original code: def display_entry(request, entry): entry = util.get_entry(entry) markdowner = Markdown() context = {'entry': markdowner.convert(entry)} return render(request, "my_app/entry.html", context) I have tried to do: def display_entry(request, entry): title = entry entry = util.get_entry(entry) markdowner = Markdown() context = {'entry': markdowner.convert(entry)} return render(request, "my_app/entry.html", context, title) The goal is to be able to render the title of my page dynamically but it produces unexpected results. I am sure it is something very simple but currently I am not seeing it. Thank you for looking into it. -
Change save method at Admin panel Django
This is my models.py from django.db import models class Post(models.Model): html = models.TextField(editable=False) thumbnail = models.TextField(editable=False) url = models.TextField() This is admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print("Not working") othermethod() obj.html = "html" obj.save() super().save_model(request, obj, form, change) def othermethod(): print("Not working") admin.site.register(Post) How can I call a function that do something before I save a Post through Django admin panel, this is what I've been trying so far, but doesn't work at all, Post object is saving at the database without 'html' field and "othermethod() function isn't been called". -
How to have pre/post populated id field in django form submissiob
What I am trying to achieve is to have my "student_id" auto-generated field to be part of the form submission in the sense that the "student_id" field does not have to be manually input in form submission: The "student_id" field needs to be either pre-generated upon displaying the form or to be generated upon form submission. I have tried and currently facing error when submitting form as bellow: KeyError at 'student_id' Exception Value: 'student_id' Removing the "student_id = form.cleaned_data['student_id']" syntax in views.py does not help either. I have the following model, which generates an auto "student_id" field class Student(models.Model): student_id = models.AutoField(primary_key=True,unique=True, max_length=10, blank=False) name = models.CharField(max_length=200, blank=False) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) def __str__(self): return self.name and my forms.py look as bellow: Class StudentForm(forms.ModelForm): class Meta: model = Student fields = [ 'student_id','name', 'first_name', 'last_name' ] And my views.py look as bellow def index(request): if request.method == 'POST': form = StudentForm(request.POST, or None) if form.is_valid(): student_id = form.cleaned_data['student_id'] form.save() else: FormError = StudentForm.errors return redirect(f'/card/{student_id}') else: form = StudentForm() template_name = 'index.html' context = { 'form' : form, } return render(request, template_name, context) {% csrf_token %} <div class="form-group"> {{ form | crispy }} </div> <input type="submit" … -
Mantener un input en todos los Templates
Estoy haciendo la parte de búsqueda para una venta de repuestos. El problema es que no sé como pasar el input entre las direcciones. En views.py tengo ésto: dev home(request): formulario_busqueda=Formulario() // Creo un formulario de 1 sólo input valor=request.GET.get("search") // obtengo el valor que se ingresó al formulario if valor: comp=spare.objects.filter(engine_info__engine_ide__icontains=valor) // Creo un query con todos los repuestos que tengan ese código return(request,"Repuestosapp/home.html",{"form":formulario_busqueda,"spare":comp}) def brand(request,val): test=val brand_id=spare.objects.filter(spare_brand__icontains=test) return render(request,"Repuestosapp/brand.html",{"brand_id":brand_id}) En base.html simplemente tengo: <div class="contform"> <h1>Buscador de repuestos</h1> <form action="" method="GET"> <!-- {% csrf_token %} --> <div class="maintable">{{formulariop.as_table}}</div> <button type="submit" value="enviar">Buscar</button> </form> </div> En home.html tengo un link para redirigir a la marca si deseo clickearla, así: <table> <tr> <th>Code</th> <th>Brand</th> <th>Type</th> <th>Car</th> </tr> {% for spares in spare %} <tr> <th><a href="">{{spares.spare_code}}</a></th> <th><a href="{% url 'brand' spares.spare_brand %}">{{spares.spare_brand}}</a></th> <!-- <th><a name="brand_id" href="brand?brand_id">{{spares.spare_brand}}</a></th> --> <th><a href="">{{spares.spare_name}}</a></th> <th><a href="">{{spares.car_info.car_manufacturer}}</a></th> </tr> {% endfor %} </table> El problema, es que cuando renderiza brand.html, el formulario se pierde, porque en la función en views.py no estoy pasando el formulario. En realidad tengo 2 formularios, pero sólo estoy preguntando por ése. También debo crearle un hyperlink a tipo de repuesto y para eso debo crear otro html. Pero no sé como pasar esos … -
Models are'nt loaded yet error when trying to get object of a model by it's ForeignKey
i have two models like this : class Author(models.Model): name = models.CharField(max_length=100,) code = models.IntegerField(unique = True) class Book(models.Model): title = models.CharField(max_length=100,) author = models.ForeignKey(Author, on_delete=models.PROTECT) And i want to list some Book with specific author and use them in another model like below: class SomeBook(models.Model): books = Book.objects.all().values('title').filter(author__code=20) text = models.TextField(default=books) But i receive the "Models aren't loaded yet" Error. i also tried to use the serializers to get the object in josn format But still the same error appears. I also look at the similar question in here but nothings helped How i can fix this error. -
Send form informations between pages in DJANGO
I have a problem with my Django application. What I want to do, in theory, is simple, but I'm not getting it. I am working with "CLASS BASED VIEWS". What I want to do is the following, I intend to have a page with my form, so when the user clicks on the button to submit the information Django has to perform some mathematical calculations with the information that was on the form and, after calculating everything, should redirect the user to a new page with the result of the calculations. Would someone give me a light on how to do this? Below is a graphic example of the process. CLICK TO SEE THE PROCESS Algorithm: Capture information using form - VIEW 01 / TEMPLATE 01 Perform some mathematical calculations with submitted information Show results on another page - VIEW 02 / TEMPLATE 02 -
google cloud build error: --substitutions flag not found
I am trying to follow the tutorial from google to run a django project on Cloud Run (https://cloud.google.com/python/django/run). I've worked my way down to actually building my container by running: gcloud builds submit --config cloudmigrate.yaml --substitutions _INSTANCE_NAME=INSTANCE_NAME,_REGION=REGION However, it continues to fail with a mysterious error: ERROR: (gcloud.builds.submit) build b1cc40a4-93e5-4935-8838-0ec2f4f9a764 completed with status "FAILURE" zsh: command not found: --substitutions As far as I can tell, the syntax is exactly as specified in the documentation. I've also run the command in bash with the same result. Is there maybe something wrong with my gcloud SDK install? Many thanks in advance for help. -
django-bootstrap-v5 DecimalField Throwing Errors in ModelForm Class
Using the django-bootstrap-v5 module, I get the error: "init() got an unexpected keyword argument 'attrs'" on a DecimalField Widget in the definition of a ModelForm class for a simple Model. The Model is defined as follows: class MenuItem(models.Model): menuname=models.CharField(max_length=20,primary_key=True) description=models.TextField() price=models.DecimalField(max_digits = 5, decimal_places = 2) And the Model Form is defined as follows: class MenuItemForm(forms.ModelForm): class Meta: model=MenuItem fields='__all__' widgets = {'menuname': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'price': forms.DecimalField(attrs={'class': 'form-control'}), } The error is thrown on the Line: 'price': forms.DecimalField(attrs={'class': 'form-control'}), If I change that line to: 'price': forms.TextInput(attrs={'class': 'form-control'}), Then no error it thrown. But of course I would rather use a DecimalField widget rather than a TextInput to render the underlying DecimalField in the model. Once again this is using the django-bootstrap-v5 module. Any Ideas? -
Title being displayed both in browser's bar and in body in Django
I am following the book "Django By Example" and I tried to implement tags. I expect the title to be shown only on the browser's title bar. However, the text inside is being displayed both on the browser's title bar but also on the webpage content. If I look at the page source, of that screenshot, it looks like this: </nav> Title goes here <div class="container"> And here is how the first lines of my base.html look like: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> And here is the template of the page shown in the screenshot: {% extends 'base.html' %} {% block content %} {% block title %} Title goes here {% endblock %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-2 left top"> <div class="card-body"> <div class=""> Here is some content. </div> </div> </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> {% endblock content %} Do you know how to get rid of the tile being displayed on the page body? -
Pass cropperjs output to OCR in Django
In my Django App someone uploads an image, makes a box selection, clicks the button crop and the image inside the box is cropped using fengyuachen Cropperjs. I want to pass the cropped image to an OCR (in my case I use Pytesseract. I had two independent apps (one for cropping and one for OCR and both works. Now, I want to join them). So, my questions is : How can I pass the cropped Image to the form input that is used by pytesseract to extract the information? I'm new to Javascript so I've been struggling with it. I think this images could help. Someone uploads and image, selects the cropping box and then select the button crop. The image is displayed "Someone" would click on the button Send to OCR and then Django Views recieves the input HTML and JS code <html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.11/cropper.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.11/cropper.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <h1>Upload Image to Crop</h1> <input type="file" name="image" id="image" enctype="multipart/form-data" multiple="true" onchange="readURL(this);" /> <div class="image_container"> <img id="blah" src="#" alt="your image" height="600px" width="600px" /> </div> <!--<div id="cropped_result" ></div>--> <button id="crop_button">Crop</button> {% if ....%} <!-- I am getting multivalue key error, there has to be and if statement here … -
Django complex query from relational model
Using django-rest-framework, I have simple model There is a Book which is getting translated, This book has chapters (each chapter has a name), each chapter has paragraphs. The Translation table contains foreign key to the Chapter(for chapter name) and paragraph range (from-to) because each translator can translate set of paragraphs in one translation, and the translation set can be out of order, but no overlap, for example a Translator1 can translate Chapter 3 paragraph 4 to 10, Translator2 can translate Chapter3 paragraph 20 to 30 but Translator3 cannot translate Chapter3 paragraph 9 to 20 because it leads to duplicate translation. for now this is done manually, I don't know how to set a constraint to prevent it. class Chapters(models.Model): id = models.PositiveIntegerField(primary_key=True) name_fr = models.CharField(max_length=45, db_collation='utf8_unicode_ci') name_en = models.CharField(max_length=50, db_collation='utf8_unicode_ci', blank=True, null=True) def __str__(self): return self.name_fr class TheBook(models.Model): id = models.AutoField(primary_key=True) # Field name made lowercase. chapterid = models.OneToOneField(Chapters,on_delete=models.PROTECT) # Field name made lowercase. paragraphID = models.IntegerField() # Field name made lowercase. paragraphText = models.TextField(db_collation='utf8_unicode_ci') # Field name made lowercase. def __str__(self): return self.paragraphText class Translate(models.Model): id = models.AutoField(primary_key=True) chapterid = models.ForeignKey(Chapters, to_field='id',on_delete=models.SET_NULL,null=True) parag_from = models.IntegerField(blank=True, null=True) parag_to = models.IntegerField(blank=True, null=True) translate = models.TextField(db_collation='utf8_unicode_ci', blank=True, null=True) def __str__(self): return ("{}: … -
xhtml2pdf django-cms 'sekizai.context_processors.sekizai' or use 'sekizai.context.SekizaiContext'
I am using Django-CMS, but when I try to use the xhtml2pdf example in the views.py I get this error: TemplateSyntaxError You must enable the 'sekizai.context_processors.sekizai' template context processor or use 'sekizai.context.SekizaiContext' to render your templates. If I use the example in a Django project without Sekizai no problem, any suggestions? Thanks. settings.py THIRD_PARTY_APPS = ( ... 'sekizai', ... ) base.html {% load cms_tags menu_tags sekizai_tags static i18n %} ... applications/htmltopdf_app views.py from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa # Create your views here. def render_pdf_view(request): template_path = 'htmltopdf_app/cv_to_pdf.html' context = {'myvar': 'this is your template context'} # Create a Django response object, and specify content_type as pdf response = HttpResponse( content_type='application/pdf' ) response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response ) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
Why Django app doesn't work on production server?
I'm trying to get django up and running on my production server but it's not working. Btw, the OS is ubuntu. I will describe everything that i did step by step, so no details are lost. So, I installed mod_wsgi: apt-get install libapache2-mod-wsgi-py3 Installed venv: apt-get install python3-venv Created venv in my django directory: sudo python3 -m venv venv Installed Django: pip install Django Then i created copy of 000-default.conf named dj.conf and populated it with the following code: <VirtualHost *:80> WSGIScriptAlias / /home/path/mysite/mysite/wsgi.py WSGIPythonHome /home/path/mysite/venv WSGIPythonPath /home/path/mysite <Directory /home/path/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Then I enabled new config and disabled old and restared server: sudo a2ensite dj sudo a2dissite 000-default.conf systemctl reload apache2 sudo service apache2 restart Then I typed ip of my server in browser address bar and I saw the default page! The same that i saw when just bought a VPS, it says "Your new web server is ready to use.". This is not even a default apache page. I also typed netstat -tulpen |grep 80 in console and it gave me this: tcp 0 0 VPS_IP:8080 0.0.0.0:* LISTEN 0 164979 88786/apache2 tcp 0 0 VPS_IP:80 0.0.0.0:* LISTEN 0 22066 773/nginx: master … -
Setting relationship with chosen model class in Django Admin interface
Problem: How to add relationship from chosen model instance to any other Django model dynamically via Django Admin interface? Description: I want to create Categories via Django Admin interface. Each Category has multiple Choices assigned to it. Choice(s) from given Category may be assigned only to objects of another specific Django class (model). Let's present a pseudocode example: class Category: category_name = models.CharField() class Choice: category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="choices") choice_name = models.CharField() class ModelWithChoosableFields: possible_categories = ... # objects of class Category selected_choices = ... # objects of class Choice class Meta: abstract = True class Book(ModelWithChoosableFields): ... class Animal(ModelWithChoosableFields): ... Category with category_name = 'Genre' has three possible Choices: choice_name = 'biography', choice_name = 'thriller' and choice_name = 'poetry'. Category with category_name = 'Animal type' has two possible Choices: choice_name = 'mammal' and choice_name = 'reptile'. Class Book may have one of the Choices from Category category_name = 'Genre' assigned. However, Choices related to category_name = 'Animal type' cannot be assigned to class Book. Analogically, class Animal can only have Choices related to category_name = 'Animal type' assigned to it. In other words, in Admin panel for instance of class Book I want to have a way of … -
Django forms is_valid() for registration, always false
I'm still learning django and I'm trying to create a register and login page. I beleive i created the form right, and the .is_valid() looks good to me also, I have no idea what i did wrong. every time I submit the register form, it fails and renders the else condition, same with the login function, even thought I went into admin to add a user manually. my user model is called 'Users' Forms: class reg_form(forms.Form): username = forms.CharField(label='username', max_length=64) password = forms.CharField(widget=forms.PasswordInput) email = forms.EmailField(label="email", max_length=64) phone = forms.CharField(label='Phone', max_length=64) first_name = forms.CharField(label='First Name', max_length=64) last_name = forms.CharField(label='Last Name', max_length=64) class log_form(forms.Form): username = forms.CharField(label='username', max_length=64) password = forms.CharField(widget=forms.PasswordInput) Register: def register(request): if request.method == 'POST': form = reg_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] user = Users.objects.Create(username=username, email=email, password=password, phone=phone, first_name=first_name, last_name=last_name) Users.save(user) login(request, user) return render(request, 'profile.html') else: return render(request, 'register.html', { 'form': reg_form }) else: return render(request, 'register.html', { 'form': reg_form }) login: def log_in(request): if request.method == 'POST': form = log_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) … -
Pagination of search results only in Django not working
I have implemented a search bar and function into a django web app in the following view: def search_products(request): search_query = request.GET.get('search', '') products = Product.objects.filter(Q(name__icontains=search_query) | Q(brand__icontains=search_query)) paginator = Paginator(products, 40) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) if page.has_next(): next_url = f'?page={page.next_page_number()}' else: next_url = '' if page.has_previous(): prev_url = f'?page={page.previous_page_number()}' else: prev_url = '' return render(request, 'store/search_products.html', context={'products': page.object_list, 'page': page, 'next_page_url': next_url, 'prev_page_url': prev_url}) The URLs are setup as follows: urlpatterns = [ path('', views.store_view, name='store'), path('wishlist/', views.wishlist_view, name='wishlist'), path('update_item/', views.updateItem, name='update_item'), path('search_products/', views.search_products, name='search_products'), ] And the HTML for the search results is as follows: <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item {% if not prev_page_url %} disabled {% endif %}"> <a class="page-link" href="{{ prev_page_url }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active" aria-current="page"> <a class="page-link" href="?page={{ n }}">{{ n }} <span class="sr-only"></span> </a></li> {% elif n > page.number|add:-4 and n < page.number|add:4 %} <li class="page-item"> <a class="page-link" href="?page={{ n }}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %} disabled {% endif %}"> <a class="page-link" href="{{ next_page_url }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> … -
Django Annotate ExpressionWrapper Does not Return Expected Type
I have the following models: class Creditor(models.Model): terms_of_payment = models.IntegerField( blank=False, null=False ) class Invoice(models.Model): creditor = models.ForeignKey( Creditor, blank=False, null=False, on_delete=models.CASCADE ) reception_date = models.DateField( blank=True, null=True ) I am getting type int for due_on from the following queryset, instead of datetime.date and can't figure out why. invoices = Invoice.objects.annotate( due_on=ExpressionWrapper( F('reception_date') + F('creditor__terms_of_payment'), output_field=DateField() ) ) The database I'm using is MySQL. So basically if reception_date=datetime.date(2021, 5, 13) and terms_of_payment=2, I expect to get datetime.date(2021, 5, 15) but I'm getting 2021515 which is <class 'int'>. -
Including fields from a OneToOneField in Django Admin
I am attempting to add the fields from a OneToOneField into my admin view. Here is an example of how my models look. class Customer(BaseUser): name = CharField() address = CharField() secondary_information = OneToOneField("SecondaryCustomerInfo", on_delete=SET_NULL, null=True) class SecondaryCustomerInfo(models.Model): email = EmailField() And I tried adding in the fields as an inline like this. class SecondaryCustomerInfoInline(admin.StackedInline): model = SecondaryCustomerInfo class CustomerAdmin(admin.ModelAdmin): inlines = [SecondaryCustomerInfoInline] But I get the error <class 'user.admin.SecondaryCustomerInfoInline'>: (admin.E202) 'user.SecondaryCustomerInfo' has no ForeignKey to 'user.Customer'. I'm used to putting the OneToOneField on the secondary model but my coworker asked that I put it on the main Customer model since we will be accessing that information more often. I think switching things around is what is tripping me up. How would I include the fields from SecondaryCustomerInfo on the admin view for Customer? -
When i update my models.py file in Django i get an error :- AttributeError: 'tuple' object has no attribute 'rsplit'
updated models.py file in users directory from django.db import models from django.contrib.auth.models import User 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' when i run command in terminal python manage.py makemigrations i get this: PS C:\Django\django_project> python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\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 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Django\django_project\users\models.py", line 5, in <module> class Profile(models.Model): File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 320, in __new__ new_class._prepare() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 333, in _prepare opts._prepare(cls) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 285, in _prepare pk_class = self._get_default_pk_class() File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\options.py", line 238, in _get_default_pk_class pk_class = import_string(pk_class_path) File "C:\Users\rsk\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 13, in import_string … -
Data in Django for loop {% for %} not loading for Modal
I am trying to display information from a django for loop in the HTML. The HTML is as follows: <div class="row"> {% for product in page.object_list %} <div class="col-lg-3"> <img class="thumbnail update-wishlist " style="height: auto" src="{{product.finalimagelink}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <a id="mySizeChart" class="button" style="vertical-align:middle"><span>Prices</span></a> <div id="mySizeChartModal" class="ebcf_modal"> <div class="ebcf_modal-content"> <span class="ebcf_close">&times;</span> <p>{{product.name}} FROM {{product.store}} £{{product.price}}</p> </div> </div> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-wishlist" style="width:50px;"><img class="button-image" src="{% static 'images/add.png' %}"></button> <h4 style="display: inline-block; float: right"><strong>£{{product.price}}</strong></h4> </div> </div> {% endfor %} </div> This works for loading the products in a grid but when clicking on <a id="mySizeChart" class="button" style="vertical-align:middle"><span>Prices</span></a> only the data for the first product is displayed. I am not sure why this is. In addtition to this, I have used JavaScript to display the Modal as a popup: $(".button").click(function() { $("#mySizeChartModal").show(); }); $("#mySizeChartModal .ebcf_close").click(function() { $("#mySizeChartModal").hide(); }); Any ideas on how I can get the data to load for each product when I click on the Modal pop up? -
Django Translation Files - Alternative to .po files
I have a legacy/non-django application where I have translation files that are in a different format from Django/gettext .po files. I would like to use all the strings in my Django application, but I would also like to continue using them in the existing application. The format of the current system is: Every language has it's own file. (ie. en.txt, de.txt, fr.txt) Each line has a string translated in to it's own language When a string is used in application, the line number that matches that string is first found in en.txt and the same line is returned from the target language. So if the string was "hello world" and on line 5 of en.txt, the function would return line 5 of de.txt which would be "hallo welt". What is the best way to use the old translation files within Django? Here are a few ideas I've thought of Create a script to create .po files from the .txt files Create my own template tags to handle translation Override the gettext system in Django to return my own translations