Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting to mongo atlas gives me pymongo.errors.ServerSelectionTimeoutError: localhost:27017
I am trying to connect to mongoDB Atlas from my Django application using models. I have changed the database configuration in settings as below DATABASES = { 'default': { 'ENGINE': "djongo", 'NAME': "test", 'HOST': "mongodb+srv://admin:<mypassword>@cluster0-9jtq2.mongodb.net/test?retryWrites=true&w=majority", 'USER': "admin", 'PASSWORD': "<mypassword>", } } Now when i execute migrate # python3.7 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/usr/local/lib/python3.7/dist-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/usr/local/lib/python3.7/dist-packages/pymongo/database.py", line 856, in list_collection_names … -
how to fix mysqlclient issue
I create a new e-commerce project and want to use a MySQL database. after installation of MySQL when i try to install mysqlclient, I'm facing the following problem. D:\---\--->pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\zalmi\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\zalmi\\AppData\\Local\\Temp\\pip-install-booy0vp7\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\zalmi\\AppData\\Local\\Temp\\pip-install-booy0vp7\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\zalmi\AppData\Local\Temp\pip-record-md7380nv\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\zalmi\AppData\Local\Temp\pip-install-booy0vp7\mysqlclient\ Complete output (30 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" -Ic:\users\zalmi\appdata\local\programs\python\python37-32\include -Ic:\users\zalmi\appdata\local\programs\python\python37-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program … -
I get a duplicate key error when i try to insert a second entry in mongodb
Im trying to pass some entries in my mongoDB and im using django framework. Everything was working okay but when i changed the model name and some things in my forms.py file and run migrations i came up with this problem. 'errmsg': 'E11000 duplicate key error .My first entry goes up into the database as expected but when i try to add another entry this error fires. Can anyone please help? -
Django Ajax request needs refresh to load
I am creating a CRUD system using Ajax, however, I have a remove button for the user to delete the posts that they created. But I need to refresh the page after creating a new post else it would not appear, how can I send the user to the page so I would not need to refresh? This is my post_create view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) My javascript code for handling Ajax: $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; } //create $('.create-post-btn').click(ShowForm); $('#modal-post').on("submit",".post-create-form",SaveForm) //update $('#post-list').on("click",".show-form-update",ShowForm); $('#modal-post').on("submit",".update-form",SaveForm) //delete $('#post-list').on("click",".show-form-delete",ShowForm); $('#modal-post').on("submit",".delete-form",SaveForm) }); And my post list template: {% load static %} {% … -
Posting data to a model with foreign key in django rest framework
I have 2 models like this: class Address(models.Model): line1 = models.CharField(max_length=264) line2 = models.CharField(max_length=264) line3 = models.CharField(max_length=264) city = models.CharField(max_length=264) state_province = models.CharField(max_length=264) zip_pincode = models.CharField(max_length=264) country = models.CharField(max_length=264) other_details = models.TextField() def __str__(self): return self.id class Doctor(models.Model): doctor_name = models.CharField(max_length=264, unique=True) # on_delete argument needs to be researched more deeply. address = models.ForeignKey(Address, on_delete=models.CASCADE) contact_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") contact = models.CharField(validators=[contact_regex], max_length=15, blank=True) # validators should be a list qualifications = models.CharField(max_length=264) license = models.CharField(max_length=264) note = models.TextField() def __str__(self): return self.doctor_name I want to create an api where doctor details include address. so address should be created and it's id should be in doctor model as foreign key in single api call. class DoctorSerializer(serializers.ModelSerializer): address = AddressSerializer() class Meta: model = Doctor fields = '__all__' def create(self, validated_data): address = validated_data.pop('address') doctor = Doctor.objects.create(**validated_data) Doctor.objects.create(doctor=doctor, **address) return doctor This gives Integrity Error as it takes address_id as null. Can someone help me with this? -
Unable to assign Groups to Users in Django
I have created a custom Users model and to use the default Auth of Django I have also inherited class AbstractBaseUser and PermissionsMixin. models.py class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = managers.UserManager() USERNAME_FIELD = 'email' After running the migrations for this Django app I have got following tables - In table auth_group I have created two user groups lets say ABC and PQR. While creating a user I want to assign user to a group which could be achieved by adding a record in table users_and_auth_users_groups. This table is created by the inherited classes of User model. The table is described below - I don't know what exact model I will have to import to have access to this particular. I know that add() method is used to insert data into Relationfields but again I am not able to find how exactly that could be achieved. -
is their any other method for defining on django
I am facing a problem in creating a django web application ![whereasindex is already defined in views.py and from which we are importing to urls.py ]2 -
legacy mysql data to django model using inspectDB
I have legacy database in mysql. I would like to use this in my django project. I used 'inspectDB' to generate django Model. However, this model does not have foreign key relationship. for example, I expect, person = models.ForeignKey('Person', on_delete=models.CASCADE) but it shows, person = models.IntegerField(db_column='Person') # Field name made lowercase. how can I make it correctly? Thank you in advance -
Django: form not displaying in browser
The form doesn't display in the browser. The navbar and submit button show up but no form in between. The problem must be straightforward but I haven't been able to find the issue. Thank you for your help. views.py def ProductCreateView(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('set_app/product_list.html')) else: product_form = ProductForm() return render(request, 'set_app/product_form.html', {'product_form':product_form}) forms.py class ProductForm(forms.Form): class Meta(): model = models.Product fields = ('code', 'barcode', 'name', 'description', 'brand', 'status') product_form.html {% extends "set_app/basic_app_base.html" %} {% block body_block %} <h1> {% if not form.instance.pk %} Create Product {% else %} Update Product {% endif %} </h1> <form method="post"> {% csrf_token %} {{ product_form.as_p }} <input type="submit" class="btn btn-primary" value="Submit"> </form> {% endblock %} -
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'image'
I have spent a LOT of time trying to resolve this- Read Django docs, consulted forms but not got anything satisfactory. So please be patient here with me. I am trying to do an upload of an Image file here from my html template The file upload happens properly an d I am able to see the uploaded image file in the HTML. In my views.py, views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE from django.core.files.storage import FileSystemStorage def button(request): return render(request,'home.html') def output(request): data=requests.get("https://www.google.com/") print(data.text) data=data.text return render(request,'home.html',{'data':data}) def external(request): inp= request.POST.get('param') image=request.FILES['image'] print("image is ",image) fs=FileSystemStorage() filename=fs.save(image.name,image) fileurl=fs.open(filename) templateurl=fs.url(filename) print("file raw url",filename) print("file full url", fileurl) print("template url",templateurl) out= run([sys.executable,'D:/corona/Image Edit Html Button Run Python Script/Image Edit Html Button Run Python Script/test.py',inp],shell=False,stdout=PIPE) image= run([sys.executable,'D:/corona/Image Edit Html Button Run Python Script/Image Edit Html Button Run Python Script/image.py',str(fileurl),str(filename)],shell=False,stdout=PIPE) print(out) print(image.stdout) return render(request,'home.html',{'data':out.stdout,'raw_url':templateurl,'edit_url':image.stdout}) In my home.html home.html <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button onclick="location.href='{% url 'script' %}'">Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} <br><br> {% if raw_url or edit_url %} <span> RAW IMAGE: <img src={{raw_url}} height=500 width=500> PROCESSED IMAGE: <img src={{edit_url}} height=500 width=500> </span> … -
Error: Requested setting INSTALLED_APPS, but settings are not configured..?
I have just started django and I have stuck in an error that I can't find the solution. As my first project in django is: To Do list web app. from django.db import models # Create your models here. class ToDo(models.Model): added_date = models.DateTimeField() text = models.CharField(max_length=200) When I run this code it show me these error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django user change Password
So we're working on a django project where users are supposed to change their passwords. I enabled a view for edit profile fields like name, last name or email but password has to have its own form. First of it all, id like to know how can i put this two forms in the same template but in two differents distributions and how to put the change password in work. and if doing this, the "No password set" advice will dissapear. template <div class="tab-pane container p-0 active" id="home1"> <form method="POST" action="#" id="datosForm"> {% csrf_token %} <p>Por favor, no dejes ningún campo en blanco. {{ form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="datosForm"> Save </button> </p> </form> </div> <div class="tab-pane container p-0 fade" id="home2"> <form method="POST" action="#" id="contraForm"> {% csrf_token %} <p>Por favor, llena los siguientes campos para cambiar tu contraseña. {{form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" name="contraForm" > Save </button> </p> </form> </div> views.py def profileedit_view(request): form= PerfilEditadoForm(request.POST or None) if request.method== 'POST'and 'datosform' in request.POST: form.instance = request.user if form.is_valid(): form.save() return redirect('profileedit') else: form= PerfilEditadoForm(instance=request.user) args= {'form': form} return render(request, 'profileedit.html', args) context = { 'form': form } return render(request, "profileedit.html", context) def change_password(request): if … -
Why is Django not publishing a valid form?
I am creating a website using Django. I'd like to give users the chance to comment on pictures they have posted. I have created a comment model and a comment form, and put the following code into the HTML document for the photo gallery: <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form However, the form is not displaying - there is nothing between 'Leave a comment' and the submit button on the page. I don't understand this as my form in forms.py appears to be configured correctly: class CommentForm(forms.ModelForm): body = forms.CharField(help_text="What is your comment?", widget=forms.TextInput(attrs={'size': '1000'}), required=True) class Meta: model = Comment fields = ('body',) def as_p(self): # Returns this form rendered as HTML <p>s. return self._html_output( normal_row='<p%(help_text)s<p></p>%(field)s</p>', error_row='%s', row_ender='</p>', help_text_html=' <span class="helptext">%s</span>', errors_on_separate_row=True)` So does my model in models.py: class Comment(models.Model): COMMENT_MAX_LENGTH = 1000 image = models.ForeignKey(Picture, on_delete=models.CASCADE, related_name="comments") user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField(max_length=COMMENT_MAX_LENGTH) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) I'd really appreciate any suggestions anyone could please offer. Thanks Jeff -
Django model with User, Profile and company
I am trying to build an app but have a hard time to figure out my model. I have already setup the User authentication. Next: Each User needs to be member of a Company (company has address info etc) Each User should have a Profile Invoices should be presented based on Company membership so every member gets the same page of invoices. So the tables (models) are: Profile Invoice Company User (this already exists and is the default django User) What would be the appropiate model relationships between those models. I would really appreciate the written model relationships like ForeignKey and ManyToMany e.d. -
django-keycloak | Set username as Keycloak Username (instead of Keycloak ID)
I am integrating Keycloak with Djnago https://github.com/Peter-Slump/django-keycloak/issues Keycloak Server This is what my keycloak User Screen looks like BUT when I log within django, user.email is proper (whats present in keycloak) user.username is getting set as ID from keycloak. Is there a way to retain djnago username as keycloak username? https://github.com/Peter-Slump/django-keycloak/issues/39 -
Loop through queryset and a dictionary with similar keys in order
I have a django queryset containing information about network things. Primary key is IP. Then, I have a dictionary with IPs as keys containing some data. I would like to display all IPs from either of the two sources in order, together with some info. For example, given: <Queryset[{'ip':'10.2.2.2', 'type':'laptop', ...}, {'ip':'10.4.4.4', 'type':'camera', ...}, {'ip':'10.5.5.5', 'type':'iot', ...}, {'ip':'10.8.8.8', 'type':'switch', ...}]> and: {'10.1.1.1': 'foo', '10.6.6.6': 'bar', '10.9.9.9': 'baz'} I want the following output: 10.1.1.1 foo 10.2.2.2 type: laptop ... 10.4.4.4 type: camera ... 10.5.5.5 type: iot ... 10.6.6.6 bar 10.8.8.8 type: switch ... 10.9.9.9 baz I could do nested loops, but is there a neat pythonic way? -
Django's Wagtail images have faulty S3 URL
I'm trying to upload images to my Django site's S3 storage using Wagtail. The images upload properly, but Wagtail appends ?AWSAccessKeyId= followed by a bunch of gibberish to the image URL. This causes the image to fail to load in both Wagtail's admin as well as the actual site. If I remove the appended text then the URL works properly. The problem is, I don't know how to stop Wagtail from appending the text in the first place. -
Error during template rendering - Required parameter name not set
I am a new developer that is stuck on this problem. The issue seems to be with the bootstrap code that I copied from their site, which is confusing. My site was working fine until I deployed it to Heroku. When I add a new post to my site I am presented with the following error: ERROR MESSAGE - ValueError - Required parameter name not set Thank you for your help! -
How to filter a Django model based on requirement from another model?
I'd like to retrieve all my contacts from my Contact model excluding those listed on my DoNotContact model. Is the following the most efficient way to do that: contacts = Contact.objects.filter(dont_contact=False) Wondering if this is going to take long to process, is there a more efficient way? class Contact(models.Model): email = models.CharField(max_length=12) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) def dont_contact(self): try: get_object_or_404(DoNotContact, email=self.email) return True except: return False def __str__(self): return self.email class DoNotContact(models.Model): email = models.CharField(max_length=12) #views.py def send_email(request): if request.method == "POST": contacts = Contact.objects.filter(dont_contact=False) -
How to redirect API call to another API which will return the response to the requester directly
CLIENT Side: UserA requests GET /file/from/some/location SERVER Side: UserA request will hit the API1 which will generate a URL and redirect the user to API2 the API will take the generated URL and return the file to the user directly without sending a response to the API1. -
Django: How to add model class inside class or refer?
I have a class called artist which is a profil for an artist class Artist_object(models.Model): surname = models.CharField(max_length=120) name = models.CharField(max_length=120) Biography = models.TextField(default='Bitte Biography eingfügen', null=False) now I want that this artist can have multiple paintings with a desrciption. class Artist_painting(models.Model): painting1 = models.ImageField() painting1_desc = models.CharField(max_length=120, default=None) painting2 = models.ImageField() painting2_desc = models.CharField(max_length=120, default=None) How can I put class Artist_painting inside the Artist_object that for every artist I view (i got def get_absolute_url(self): return f'/artist/{self.id}' ) it have an description for every image ? -
How to create a new record using a django form
I want to create a new record by using django form but I am stuck on it and i get this kind of error IntegrityError at /academy/add_academy/3/ null value in column "Student_name_id" violates not-null constraint DETAIL: Failing row contains (39, da10, 2020-03-06, A, 11, 11, null). Here is my view.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.filter(Student_name=child) form=AcademicForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) Also this is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my template file <div class="card"> <div class="card-header bg-primary text-white"> <h4> <i class="fas fa-user-plus"></i> Enter {{child.Firstname}} {{child.Lastname}} details </h4> </div> <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> Thanks for your help -
Docker-compose can't import Django (ModuleNotFoundError)
I'm very new to Docker and I've been trying to get a very simple 'Hello World' program to run on docker. No matter what I do I always get "ModuleNotFoundError: No module named 'Django'" I've been stuck with this for two days now. Still no luck. Could you please point me in the right direction? What am I doing wrong? Here's the terminal output. C:\path\to\app\root>docker-compose up Creating network "hello-world_default" with the default driver Creating hello-world_web_1 ... done Attaching to hello-world_web_1 web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 10, in main web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 21, in <module> web_1 | main() web_1 | File "/code/manage.py", line 16, in main web_1 | ) from exc web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? hello-world_web_1 exited with code 1 Here's the dockerfile # Pull base image FROM python:3.7 # Set environmental variables … -
Trying to display multiple image for my product
I'm trying to display multiple images for one product but the images won't display and i don't know why can anyone help. My Models. I have to image field one is used to display and product and if the user wants more detail the other is used to show more images of the product. class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def get_absolute_url(self): return reverse('single',args=[self.id,self.slug]) class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return self.product.image Views def single(request, id, slug): try: # products = Product.objects.get(slug=slug) product = get_object_or_404(Product, id=id, slug=slug) images = ProductImage.objects.filter(product=product) return render(request, "single.html", {'product': product}, {'images':images}) except: raise Http404 How I tried to display the images on the Html page. {% for img in images %} {% if item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% if not item.featured %} <img class="img-responsive"src="{{ MEDIA_URL }}{{ img.image.url }}" height="px" width="px" class="pr-5 mr-5"> {% endif %} {% endfor %} -
Cannot run Django with active venv in zsh
I've got a properly activated venv in zsh, because I can see (venv) at the beginning of the prompt, but when I try to run Django with the command python manage.py runserver I've the error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? If I run which which python I can see python: aliased to /usr/local/bin/python3.7 that it seems wrong, because I expect something like /Users/myuser/Python-Projects/test/venv/bin/python. In fact if I disable the venv the result of which python is the same. I tried to the same steps with bash and everything works fine, so I guess I've got something wrong with zsh, but I don't know what. …