Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User Session Tracking Middleware in Django
I'm trying to set up a basic session counter for users who log into the site, so I can know how active they are. I want it to run not just when they fill out the login form, but if they come back already logged in. I'm separating session saves by 1 hour, counting sessions that happen within the same hour as the same session. The middleware: (1) Saves a new session to the UserSession object and (2) increments total_visits by 1 on the UserProfile object. My issue is that it's saving 2 sessions per visit, and increasing the count by two. So basically it's running twice before setting the cache. in settings.py MIDDLEWARE = ( ... 'my_app.middleware.LastUserActivityMiddleware', ) which points to this middleware def LastUserActivityMiddleware(get_response): def middleware(request): """ Save the time of last user visit """ response = get_response(request) if request.session.session_key: key = "recently-seen-{}".format(request.session.session_key) recently_seen = cache.get(key) # is_authenticated hits db as it selects user row # so we will hit it only if user is not recently seen if not recently_seen and request.user.is_authenticated: try: user_profile = UserProfile.objects.get(user=request.user) user_profile.total_visits= F('total_visits') + 1 user_profile.save() except: UserProfile.objects.create(user=request.user, total_visits=1) UserSession.objects.get_or_create(user=request.user, session_key=request.session.session_key) visit_time = 60 * 60 # wait one hour before logging … -
Using '_id' in Django
I am a bit confused how Django handles '_id' property when we use ORM with some models that use foreign key. For example: class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) And when I use ORM with 'filter' I can easily use something like: CartItem.objects.filter(user=1, product=1, quantity=1) And Django kind of 'see' that I refer to 'id', but when I use exacly the same line of code, but with 'create' instead of 'filter': CartItem.objects.create(user=1, product=1, quantity=1) Then it throws an error saying: Cannot assign "1": "CartItem.user" must be a "CustomUser" instance. And to create it I need to use: CartItem.objects.create(user_id=1, product_id=1, quantity=1) Why is that? Is there some rule here that I don't understand? -
How to create multiple models from the same form in Django
I have a create view used to make a quiz that has the title, author, etc but my quizzes are made up of answer models that are linked to question models that are then linked to this quiz. How do I make a form for creating a whole quiz, including the questions and correct answers, from this? class QuizCreateView(LoginRequiredMixin, CreateView): model = Quiz fields = ['title', 'video_link', 'question_amount'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I use crispy forms in the template {% extends "quiz_app/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Quiz</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-blue" type="submit">Submit</button> </div> </form> </div> {% endblock content %} TIA -
Queryset object in Django form not iterable
I'm trying to get the form to create the fields based on what exam page the user is on. In the error page all local variables have the correct value for form and view, but i keep getting "ExamQuestion" object not iterable and an error at line 0 of template. It also highlights the render() at line 44 in the view as the source of the problem. If I change line 28 from "exam__name=exam_name" to "exam__name="exam_name"", basicly turning the variable into a str, the page runs but no data is passed. In the error console choice_list shows querysets as individual list items as it should for forms.py How do I make the object ExamQuestion iterable? Ive been stumped for a week now. I've written a hundred ways at this point. I know it's listing questions instead of answers for the questions, I'm just trying to get it to load ANY queryset and freaking run at this point. view def exampage(request, exam_name): exams = Exam.objects.all() questionlist = ExamQuestion.objects.filter(exam__name=exam_name) choicelist = ExamChoice.objects.filter(question__exam__name=exam_name) form = ExamTest(request.POST, exam_name=exam_name) if request.method == "POST": if form.is_valid(): #form.save() #choice = form.cleaned_data.get('choice') return redirect('exampage.html') return render(request, 'exams/exampage.html', {'exams': exams,'questionlist': questionlist, 'exam_name': exam_name, 'choicelist': choicelist, 'form': form, 'choice': choice}) … -
Django app doesn't recognize .env file, I tried to set it up through the os, Django-environ, and dotenv but nothing worked
I set up a new django app in a virtual environment and tried to use a .env file with it for the secret key and the database url, however I can't manage to make the django app read the .env file. I've tried first with os.environ, tried to set a direct path, tried with dotenv (both python-dotnev and django-dotnev, seperately) and last with Django-environ. I tried putting the .env file is in the same folder, the parent folder, the venv folder, but nothing worked. In myapp/settings.py I have: import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env() environ.Env.read_env() SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ALLOWED_HOSTS = [] And then in the same folder I have ".env" file: Debug=True SECRET_KEY='some-secret-key' I tried adding "export" before Debug and SECRET_KEY but it didn't make any difference. I constantly get this error when I run python manage.py runserver: raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable What am I missing? What step did I not do? Does it not work because the app runs in a virtual envirnoment? -
Comparing strings in SQL, where the same two records are never compared again
I am currently working on a capstone project for an IT degree and could use some guidance. My stack for this project is windows>python>django>MySQL I have an article table and news source table. I am comparing the string content of each article against each article in the database. My problem is that I only want to compare Article "A" to Article "B" once no matter how many times the comparison script is run. I am assuming that I would populate the relationship table with foreign keys from each of the articles and then cross-check the relationship table for that exact article FK combination? Not needing exact coding examples but the logic in how to tackle this problem. Thanks, Stackoverflow community. Django SQL Models -
I get a ' no module named django ' error on heroku only when i try to submit an email form yet locally it works just fine
When I pip freeze on heroku console i find that django has been installed. When i try to submit the form locally on my computer the submission is successful with no errors. Views.py ''' @login_required(login_url='/accounts/login/') def b_contact(request): c_form = ContactForm if request.method == 'POST': c_form = ContactForm(data=request.POST) if c_form.is_valid(): email = c_form.cleaned_data['email'] subject = c_form.cleaned_data['subject'] message = c_form.cleaned_data['message'] send_mail(email, message, subject, ['be.rightmuk@gmail.com'], fail_silently=False) messages.success(request, f'Your message has been sent!') return redirect('buyer_home') else: email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') context = { 'c_form': c_form } return render(request, 'buyer/contact.html', context) ''' forms.py class ContactForm(forms.Form): email = forms.EmailField(label='Your Email') subject = forms.CharField(required=True, max_length=150) message = forms.CharField(widget=forms.Textarea, required=True) tepmplate <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ c_form|crispy }} </fieldset> <button class="btn btn-default" type="submit">Send </button> </form> requirements.txt dj-database-url==0.5.0 Django==2.0 django-bootstrap3==11.0.0 django-bootstrap4==1.0.1 django-braces==1.13.0 django-crispy-forms==1.7.2 django-heroku==0.3.1 django-model-utils==3.2.0 django-progressive-web-app==0.1.1 django-registration==2.4.1 django-tinymce==2.8.0 djangorestframework==3.9.4 gunicorn==19.9.0 This is the error ModuleNotFoundError at /seller/contact/ No module named "'django" Request Method: POST Request URL: https://sakka.herokuapp.com/seller/contact/ Django Version: 2.0 Exception Type: ModuleNotFoundError Exception Value: No module named "'django" Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 953 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', ' /app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 24 Oct 2019 15:06:42 +0300 This … -
Django Receiving Message from SQS
I have a Django application that runs a process once a day using Celery and SQS and saves the files to S3. I used this tutorial to setup Django, Celery and SQS. That works out well when the flow is Django --> SQS --> Celery --> S3 However, in addition to saving files to S3, I need to be able to run a process when the S3 Bucket receives files from another application (it's a shared S3 Bucket). In that case the flow is S3 --> SQS --> Celery --> Django From what I read in the documentation it is possible to send a notification when a new document is created in S3 using SQS. So if I set that up it takes care of the S3-->SQS portion. What I'm not clear on is how this message gets passed from SQS to Celery and then to Django to perform what I need to do with the new object: This would be the final process: 1- A new File gets saved to S3 2- A notification saying a new file was saved in S3 with the name of the file gets sent using SQS 3- SQS notifies the Celery worker a … -
display a list of items in a select box in my html template in django 2.2
I have a list of departments i want to be shown in a select drop-down but its not shown? Its a duty-log App and want the user to be able to select the department from the drop-down. here's my views.py def index(request): # the index view logs = Dutylog.objects.all() # quering all logs with the object manager departments = Department.objects.all() # getting all departments with object manager if request.method == "POST": # checking if the request method is a POST if "taskAdd" in request.POST: # checking if there is a request to add a logo title = request.POST["description"] # title date = str(request.POST["date"]) # date department = request.POST["department_select"] # department content = title + " -- " + date + " " + department # content Log = Dutylog(title=title, content=content, due_date=date, department=Department.objects.get(name=department)) Log.save() # saving the log return redirect("/") # reloading the page if "taskDelete" in request.POST: # checking if there is a request to delete a log checkedlist = request.POST["checkedbox"] # checked logs to be deleted for log_id in checkedlist: Log = Dutylog.objects.get(id=int(log_id)) # getting log id Log.delete() # deleting logo return render(request, "index.html", {"logs": logs, "department": departments}) here''s my models.py class Department(models.Model): # The Category table name that … -
Django return result set from postgreSQL function
I have a postgreSQL function (named changed_permissions_for_role) that returns a TABLE. When I query the function in DataGrip, it works perfectly (i.e. I get all rows that I am expecting). In DataGrip, I am doing this: SELECT * FROM changed_permissions_for_role(6, 7) When I try to do the same thing in my Django project, I get nothing!?!? This is what I am doing in the Django project: with connection.cursor() as cursor: permissions = cursor.execute("SELECT * FROM changed_permissions_for_role(%s, %s)", [role.base, pk]) return render(request, 'roles/edit.html', {'permissions': permissions}) What am I doing wrong? I am unable to debug the project to try to see if I can figure it out myself but my PyCharm debugger suddenly doesn't work anymore :( (Thanks for your time) -
Order choices by user
I'd like to order a choicefield on a form in alphabetically order by user models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) busname = models.CharField(max_length=60) forms.py self.fields['user'].choices = tuple([(t.user.id, t) for t in UserProfile.objects.all().order_by('user')]) Unfortunately, this isn't working. The order is coming out by user.id Thanks! -
Django ternary models relationship with constraints
As part of a Django online platform that offers online courses, course authors are free to include exercises from a public exercise repository. Each course has its own chapters and is free with how to organize the exercises in chapters. An exercise in a course can be part of zero or one chapter. When a chapter in a course is deleted, the exercises in it just go back to the status of no chapter assigned. What I have so far : class Exercise(models.Model): title = models.CharField(max_length=30) class Course(models.Model): title = models.CharField(max_length=30) exercises = models.ManyToManyField(Exercise) class Chapter(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) title = models.CharField(max_length=30) The problem: There is no link between exercises and course chapters so far, it isn't clear to me how to do it in a proper way taking into consideration the constraint that an exercise in a chapter should be in the course as well. -
How to use pendulum as a base datetime library with Django?
I would like to use pendulum as a base datetime library with Django. So, a DateTimeField should work with pendulum objects, not datetime objects. I have followed an example on pendulum's docs page and created a special field: import pendulum from django.db.models import DateTimeField as BaseDateTimeField class DateTimeField(BaseDateTimeField): def value_to_string(self, obj): val = self.value_from_object(obj) if isinstance(value, pendulum.DateTime): return value.format('YYYY-MM-DD HH:mm:ss') return '' if val is None else val.isoformat() ...and used that in my models.py: class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() done = models.BooleanField() due_date = BaseDateTimeField() def is_today(self): return self.due_date.in_timezone('utc').date() == pendulum.today('utc').date() ...however I'm getting an error: 'datetime.datetime' object has no attribute 'in_timezone' ...which obviously means that Django treats due_date still as a datetime object, not a pendulum object. Is there a possibility of switching to using pendulum as a base datetime library with Django? P.S. I think something is wrong with that docs snippet, value appears out of the blue, but I don't think that this is the cause of the problem. -
Using postgis and mongodb django
I use django (2, 1, 5, 'final', 0). My problem, i try to store an address model in postgresql, all the others models (auth, products...) in mongodb engine with the djongo package. the models stored in app => geolocalise : class Address(models.Model): line1 = models.CharField(max_length=150) line2 = models.CharField(max_length=150, blank=True) postalcode = models.CharField(max_length=10) city = models.CharField(max_length=150) country = models.CharField(max_length=150, default="France") #the postgis entry location = models.PointField(null=True) latitude = models.FloatField( default=0) longitude = models.FloatField( default=0) description = models.TextField(max_length=1024,blank=True) #user = models.ForeignKey('User', related_name='user', on_delete=models.CASCADE) def __str__(self): return "{0} - {1} - {2}".format(self.line1, self.postalcode, self.city) here my settings py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'DBNAME', 'USER': 'USER', 'PASSWORD': 'PASSWORD'}, 'postgresql': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'DBNAME', 'USER': 'USER', 'PASSWORD': 'PASSWORD'}} But when i do my migrations i don't know why the database is store in mongodb. I've try a configuration in a router.py which i found on stackoverflow but it's isn't working: class GeolocaliseRouter(object): def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'geolocalise': return 'postgresql' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'geolocalise': return 'postgresql' return None def allow_relation(self, obj1, obj2, … -
How to add a domain to your localhosting web server
I made a web server with django that i'm hosting on my PC. I have port forwarded my web server to my routers port 80 and can access it just fine from the outside using the Wan address+:80. My question is how i can access my web server through a domain and not my Wan address? For example how can i use http://www.123examplesite.com to access my web server instead of http://123.123.1.123:80? I already have a domain name registered (i used freenom.com for that) -
Django Rest Framework - How to set the current_user when POST
I have just followed a small tutorial using DRF, but I can't figure how to like my model to his user when POSTing a new object this is my model : # Create your models here. class Project(models.Model): # project title title = models.CharField(max_length=255, null=False) # subtitle subtitle = models.CharField(max_length=255, null=False) ####### user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) and so my serializer class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ("id", "title", "subtitle", "user_id") so, now in the view I have access to the current_user with this : request.user class ListProjectsView(generics.ListCreateAPIView): authentication_classes = [authentication.TokenAuthentication] queryset = Project.objects.all() serializer_class = ProjectSerializer def list(self, request): queryset = Project.objects.filter(user_id=request.user.id) serializer = ProjectSerializer(queryset, many=True) return Response(serializer.data) [...] def create(self, request, pk = None): return super(ListProjectsView, self).create(request, pk = None) I suppose there is a way to passe the request.user is the create in order to allow my Project.user_id to be filled ? Whatever I'm doing, I can't manage to set the user, and i get the django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint error Any idea? Thanks! -
how to save this form?
I tried how to save this code. it shows the form in the template but when the form filled and submit the data isn't saving to the database here is my views.py def create_tables(request): restaurant = Restaurant.objects.get(user=request.user) print(restaurant) form = TablesForm(request.POST or None, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() user.restaurant = restaurant user.name = form.cleaned_data.get('name') user.time = form.cleaned_data.get('time') user.save() return redirect('/') args = { 'table': restaurant, 'form': form } return render(request, 'main/tt.html', args) and also here is my forms.py class TablesForm(forms.ModelForm): name = forms.CharField(max_length=250, label="Table Name") time = forms.ModelChoiceField(queryset=Time.objects.all()) class Meta: model = Table fields = [ 'name', 'time', ] so help me please. -
What to write in application root when deploying django app in cpanel
Am deploying my first django app in cpanel, when filling details am stack in the category called application root, which is the physical address of where I will deploy. I have tried to write many words as I have seen by searching through google like django,app, and others nothing has worked. Also I went through my file structure in cpanel account to look which location am going to deploy my site, tried several of them but none of them has worked. Below are the links for more details file structure in my cpanel account and place to input application root -
Django request into forms.py
In a view, I define the user database from request.user: def delete(request, pk): electricity_supply = get_object_or_404( ElectricitySupply.objects.using( request.user.accounts_database_id.database_name ), pk=pk, ) electricity_supply.delete() How to use request in forms.py? class ClientGroupForm(forms.ModelForm): group_name = forms.ModelChoiceField( queryset=ClientGroup.objects.all() ) subgroup_name = forms.ModelChoiceField( queryset=ClientSubGroup.objects.all() ) class Meta: model = ClientSubGroup fields = ["group_name", "subgroup_name"] -
How to write equivalent filter in django for the below query
Below is a query which i am using for a search screen. Mobile1, sponsor1 and status1 are the field inputs from the user. If these fields will not be entered then all the values should be returned as output. Query ----- Select * from customer where mobile = nvl(mobile1,mobile) and sponsor = nvl(sponsor1,sponsor) and status = nvl(status1,status); Models.py --------- class customer(models.Model): company = models.CharField(max_length=3) mobile = models.CharField(max_length=10) name = models.CharField(max_length=100) sponsor = models.CharField(max_length=10) address1 = models.CharField(max_length=200) country = models.CharField(max_length=101) state = models.CharField(max_length=100) city = models.CharField(max_length=100) zip = models.CharField(max_length=6) email = models.EmailField(max_length=100) status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True ) -
Django - Problem with Implementing Models and Views in My PhoneReview Application
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for: Brand – details on brand, such as, name, origin, manufacturing since, etc Model – details on model, such as, model name, launch date, platform, etc Review – review article on the mobile phone and date published, etc Many-to-many relationship between Review and Model. Now, I have to create views for the following: a. An index page that display all Brands available for mobile phone in the database b. A phone model page that display model when a brand is selected. c. A detail page when a model is selected that contain reviews and newslink I have managed to create view for "a. An index page that display all Brands available for mobile phone in the database." However, I am stuck with "b. A phone model page that display model when a brand is selected." I have managed to display the phone model page. However, the name of the phone model is not being displayed. So, I feel that … -
how to add another table in django-admin site?
I have this table inside of students enrollment record(adminsite) how do i add this table under the table students enrollment record when the admin filter/or click the monthly? this is my code in model.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) this is my code in admin.py admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') def lrn(self, obj): return obj.Student_Users.lrn @admin.register(ScheduleOfPayment) class ScheduleOfPayment(admin.ModelAdmin): list_display = ('Education_Levels','Payment_Type','Display_Sequence','Date','Amount','Remark','Status') ordering = ('Education_Levels','Payment_Type','Display_Sequence') list_filter = ('Education_Levels','Payment_Type') -
Docker compyling python file in Dockerfile
I would to create a docker image from my django app but i don't whant pull my .py file. For doint this i need a way to compile my python file in docker then remove all *.py and left only *.pyc file. If i simply in .dokerignore file whrite **/*.py i get the error ImportError: bad magic number in 'ajaxfuncs': b'\x03\xf3\r\n' because my original *.py file was compiled with a different python version (local python3.6.0 docker python3.6 for alpine) So as workaround i would build my python file in dockerfile and then remove all py first in my .dockerignorefile i put: **/*.pyc then in my Dockerfile think to use python -m py_compile for generate my new *.pyc files: FROM python:3.6-alpine EXPOSE 8000 RUN apk update RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ RUN python -m py_compile /Code/ajaxfuncs/ajax.py /Code/ajaxfuncs/asktempl.py /Code/ajaxfuncs/group.py /Code/ajaxfuncs/history.py /Code/ajaxfuncs/template_import.py RUN rm -rf /Code/ajaxfuncs/*.py ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 but when i run my application seem that compiler does not compile my files, because no pyc … -
setting a gallery in a amp lightbox with django
thanks for your time. i've been working on a project with django on the back end and amp on the frontend although im having some troubles to link both tags like the lightbox one. i'd like to get a list of first images on my product page(i've done it) and by clicking on a image it displays me the other images of that object on a lightbox without going to the detail template. the whole project its just updated on github at: https://github.com/lucasrf27/dealership thats the amp code that i'm trying to. i'm trying this one on test.amp.html besides put on my category (product template) <div> {% for v in veiculos %} <amp-img src="{{ v.first_image.imagem.url }}" on="tap:cars" width="200" height="100"></amp-img> <amp-carousel id="cars" lightbox="{{v.modelo}}" width="1600" height="900" layout="responsive" type="slides"> {% for i in veiculos.images.all %} <amp-img lightbox src="{{ i.imagem.url }}" width="30" height="30" alt="apples"></amp-img> {% endfor %} </amp-carousel> {% endfor %} </div>´ i'm not shure if i'm passing the variables wrong on my views.py i'd like to get a list of first images as i did and by clicking in one of them open a lightbox with the other images of that product -
My contact page displays an error "No module named "'django"" on heroku but it works fine on my local machine
I can send a message from my local computer to my email just fine but when i deploy my app on heroku i get an error message 'No module named "'django"'. What might be the problem? Views.py @login_required(login_url='/accounts/login/') def s_contact(request): c_form = ContactForm if request.method == 'POST': c_form = ContactForm(data=request.POST) if c_form.is_valid(): email = c_form.cleaned_data['email'] subject = c_form.cleaned_data['subject'] message = c_form.cleaned_data['message'] send_email(email, subject,message, ['myemail@gmail.com']) messages.success(request, f'Your message has been sent!') return redirect(seller_home) else: email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') context = { 'c_form': c_form } return render(request, 'seller/contact.html', context) Forms.py class ContactForm(forms.Form): email = forms.EmailField(label='Your Email') subject = forms.CharField(required=True, max_length=150) message = forms.CharField(widget=forms.Textarea, required=True) Kindly assist guys.