Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i know that email is real email or not using django framework
I built an email sender by using the Django framework but the logic that I built it accepted any email whatever is real email or not !! # Sending Email View def send_email(request): if request.method == 'POST': form = SubscribeForm(request.POST or None, request.FILES or None) if form.is_valid(): message = form.cleaned_data['body'] subject = form.cleaned_data['subject'] recipient_list = request.POST['to_email'] email = EmailMessage(subject, message, EMAIL_HOST_USER, [recipient_list]) email.send(fail_silently=False) messages.success(request, f'email sent to {recipient_list} successfully.') return redirect('/') else: form = SubscribeForm() context = { 'form': form, } return render(request, 'index.html', context) **Settings.py** EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #<<===========================================================================>> EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587'enter code here EMAIL_HOST_USER = 'MyAccount@gmail.com' EMAIL_HOST_PASSWORD = 'MyPassword' EMAIL_USE_TLS = True -
Django ckeditor Image compression to Jpeg and image resize
Hi can anyone suggest me a way, I'm trying to do couple of things i'm using RichTextUploadingField in model, can anyone please help me with this: Compress django ckeditor uploaded image to jpeg to save disk space. For this i found CKEDITOR_FORCE_JPEG_COMPRESSION setting on django-ckeditor github page but it is throwing me error: NameError:name 'CKEDITOR_FORCE_JPEG_COMPRESSION' is not defined I want to set default django ckeditor uploaded image size suppose if i wupload 1000px image it should automatically converted into 600 or 500px without impacting the image quality or if possible image resize option like we do in word drag and resize. Ckeditor settings config: Ckeditor config: CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_FORCE_JPEG_COMPRESSION = True CKEDITOR_CONFIGS = { 'default': { 'width': '100%', 'height': 600, 'contentsCss': 'img {max-width: 100%;height: auto! important;}', 'toolbar': 'Custom', 'toolbar_Custom': [ [ 'Bold', 'Italic', 'Underline' ], [ 'Font', 'FontSize', 'TextColor', 'BGColor', 'Find', 'Replace', '-', 'SpellChecker' ], [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'Table', 'TableTools' ], [ 'Link', 'Unlink' ], [ 'RemoveFormat', 'Source', 'Smiley', 'Image', 'Youtube', 'Preview' ] ], }, } -
Django import export, get() returned more than one
Please help me to find a solution to this error, whene using django-import-export here is my code : Models : class ChartOfAccounts(models.Model): code = models.CharField('code plan comptable', max_length=20, unique=True) name = models.CharField('plan comptable', max_length=100) def __str__(self): return self.code class Company(models.Model): code = models.CharField('code société', max_length=20, unique=True) name = models.CharField('société', max_length=100) addr = models.CharField('adresse', max_length=100, blank=True, null=True) chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable') def __str__(self): return self.code class GLAccount(models.Model): class Meta: unique_together = (('code', 'chart_of_accounts'),) code = models.CharField('code compte comptable', max_length=10) chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable') name = models.CharField('compte comptable', max_length=100, help_text='text descriptif du compte comptable') def __str__(self): return f'{self.code}, {self.chart_of_accounts}' class CompanyAccount(models.Model): company = models.ForeignKey(Company, verbose_name='code société', on_delete=models.CASCADE) gl_account = models.ForeignKey(GLAccount, verbose_name='compte comptable', on_delete=models.CASCADE) Resources : class CompanyAccountResource(ModelResource): class Meta: model = models.CompanyAccount fields = ('company', 'gl_account',) exclude = ('id',) import_id_fields = ('company', 'gl_account',) skip_unchanged = False report_skipped = False # fields company = Field( column_name=Meta.model._meta.get_field('company').verbose_name, attribute='company', widget=ForeignKeyWidget(models.Company, field='code') ) gl_account = Field( column_name=Meta.model._meta.get_field('gl_account').verbose_name, attribute='gl_account', widget=ForeignKeyWidget(models.GLAccount, field='code') ) def get_export_order(self): export_fields = ['company', 'gl_account', ] return export_fields My data is : Company model data here ChatOfAccounts model data here GLAccount model data here CompanyAccountResource Excel canvas to import data the problem : a GLAccount code may apear … -
Productpage with Django and bootstrap For loop
I am making a productpage with Django and bootstrap. I am getting stuck when I want to iterate a for loop for multiple items. In my code I begin with {{% for iten in items %}} and end with {{endfor}}, but I need line in between for example elsif or elseend. So: {{% for item in items %}} Item 1 {{some code}} item 2 {{endfor}} <div class="row featured__filter"> {% for item in items %} <div class="col-lg-3 col-md-4 col-sm-6 mix {{ item.get_category_display }}"> <div class="featured__item"> <div class="featured__item__pic set-bg" data-setbg="{% static 'img/featured/dash1.png' %}"> <ul class="featured__item__pic__hover"> <li><a href="#"><i class="fas fa-search"></i></a></li> <li><a href="#"><i class="fa fa-shopping-cart"></i></a></li> </ul> </div> <div class="featured__item__text"> <h6><a href="#">{{item.title}}</a></h6> <h5>${{item.price}}</h5> </div> </div> </div> <div class="col-lg-3 col-md-4 col-sm-6 mix {{ item.get_category_display }}"> <div class="featured__item"> <div class="featured__item__pic set-bg" data-setbg="{% static 'img/featured/dash2.png' %}"> <ul class="featured__item__pic__hover"> <li><a href="#"><i class="fas fa-search"></i></a></li> <li><a href="#"><i class="fa fa-shopping-cart"></i></a></li> </ul> </div> <div class="featured__item__text"> <h6><a href="#">**{{item.title}}**</a></h6> <h5>${{item.price}}</h5> </div> </div> </div>{% endfor %} -
Django csrf_exempt decorator doesn't work
I am using django version 3.1.1 and python 3.8.2 the decorator @csrf_exempt over a view function: #settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #urls.py urlpatterns = [ path('func/', views.func) ] #views.py @csrf_exempt def func(request: HttpRequest) -> JsonResponse: return JsonResponse(dict(success=True)) each time I send a request from javascript to this view: POST func/ I receive Forbidden (CSRF token missing or incorrect.) HTTP/1.1" 403 Thanks -
Get string from TextChoices class in Django
class Foo(models.Model): class Bar(models.TextChoices): CODE_A = 'A', "special code A" CODE_B = 'B', "not so special code B" bar = models.CharField(max_length=1, choices=Bar.choices) The text choices look like tuples but they aren't: print(Foo.Bar.CODE_A[1]) Gives "IndexError: string index out of range". I was expecting to get "special code A". How do I access the code string programmatically from a view, not from within a template and not just the code constant? -
SyntaxError: invalid syntax on lib/python3.8/site-packages/sql_server/pyodbc/base.py django deploy on Linux
** Preface (Testing HyperV Virtual Server with os: Ubuntu Server 20.04.1 on local Windows PC) ** I am having problems deploying my Django app (using Python 3.8.2) on a Ubuntu Server 20.04.1 LTS that uses MS SQL Server as its database. No issues reverting back to 'ENGINE': 'django.db.backends.sqlite3' on Linux but I have to be honest, it is frustrating. I already had to downgrade to Django==3.0 to get my app working on my local windows pc but the 2 migrations I did proves that I am missing something and I hope someone can give me a hand. Any help is appreciated. My PC Working settings.py file (currently running on windows with Sql Server 2019 Express DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'mdm_db', 'USER': 'AAA', 'PASSWORD': 'AAA', 'HOST': 'localhost\\SQLEXPRESS', 'PORT': '', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', # 'driver': 'ODBC Driver 13 for SQL Server ', -> port 1433? }, }, } installed components: pip freeze asgiref==3.2.10 Django==3.0 django-mssql-backend==2.8.1 pyodbc==4.0.30 pytz==2020.1 sql-server.pyodbc==1.0 sqlparse==0.3.1 Ubuntu Server (also tried using ODBC and installing the latest version https://docs.microsoft.com/it-it/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'mdm_db', 'USER': 'mdmuser', 'PASSWORD': 'mdmuser', 'HOST': 'localhost\\SQLEXPRESS', 'PORT': '', 'OPTIONS': { #'driver': 'SQL Server … -
Editing form field __init__
class BotForm(UserForm): def __init__(self, *args, **kwargs): super(BotForm, self).__init__(*args, **kwargs) del self.fields['q2'] Question: How to redefine form fields not by deleting existing ones, but to specify which ones to show only? Any ideas? -
Django filter data of foreign key table and primary key table
I have these two models class Upload(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=50) class Text(models.Model): texts=models.CharField(max_length=500,null=True,blank=True) upload_text=models.ForeignKey(Upload, blank=True, null=True, on_delete = models.CASCADE) What I want is to get texts from Text when I filter name from Upload. So I want name, email and texts displayed. I know this question has been asked previously and I am also doing the same, but getting error. I have tried this data=Text.objects.filter(upload__name__icontains=query) But it give me an error Cannot resolve keyword 'upload' into field. Choices are: id, texts, upload_text, upload_text_id I have also tried this. data=Upload.objects.filter(name__icontains=query) data1=Text.objects.filter(upload_text__in=data) But I am unable to display both at the same time in jinja2 template. {% for q,t in zip(query_key,query_res) %} {{ t.texts }} {{ q.name }} | {{q.email}} -
How Can I render the Hosptal?
How to show the Hospital here? (https://ibb.co/Xkn58yK) blood/models from django.db import models class Patient(models.Model): patient_id = models.CharField(max_length= 1000, null= True) first_name = models.CharField(max_length = 50, null = True) last_name = models.CharField(max_length= 50, null = True) address = models.CharField(max_length=100, null = True, blank=True) phone_number = models.CharField(max_length=50, null= True, blank=True) date_created = models.DateTimeField(auto_now_add = True, null = True, blank=True) hospitals = models.ManyToManyField(Hospital) BLOOD_TYPE = ( ('O+','O+'), ('O-','O-'), ('A+','A+'), ('A-','A-'), ('B+','B+'), ('B-','B-'), ('AB+','AB+'), ('AB-','AB-'), ) patient_blood = models.CharField(max_length=5, null = True , choices=BLOOD_TYPE) def __str__(self): return '{} {} {} {}' .format(self.first_name, self.last_name, "-", self.patient_id) class Hospital(models.Model): hospital = models.CharField(max_length=100, null=True) address = models.CharField(max_length=100, null = True, blank=True) phone_number = models.CharField(max_length=50, null= True, blank=True) def __str__(self): return self.hospital views.py blood/views from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import * def PatientPage(request): patients = Patient.objects.all() hospitals = Hospital.objects.all() context = { 'patients':patients, 'hospitals':hospitals, } return render(request, 'blood/patients.html', context) I can query the rest, only the hospital left {% for id in patients %} <tr> <td>{{id.hospitals}}</td> </tr> {% endfor %} This is the HTML section, I listed the rest, but I can't do the ManyToManyField. The only problem is how can I show the hospital chosen by the patient I am just … -
Multiple blocks in Django
I have a page that shows articles and event dates. I have the code set up for blok content working for the article, but I can't figure out how to make the second block of content appear on the page. These are my models: class NewsLetter(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) class Event(models.Model): name = models.CharField(max_length=100) date = models.CharField(max_length=30) location = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name And this is the code for the second block of content I am trying to show: {% block events %} <div class="w-full bg-white shadow flex flex-col my-4 p-6"> <p class="text-xl font-bold pb-3">Events Calendar</p> <hr> {% for event in object_list %} {{ event.title }} {% endfor %} <a href="#" class="w-full bg-green-600 text-white font-bold text-sm uppercase rounded hover:bg-green-500 flex items-center justify-center px-2 py-3 mt-4"> Sign Up </a> </div> {% endblock %} The solution has to be simple, but I can't see it in the Django docs. Can someone please help. And please remember, the answer to a similar question posted 3 years ago may not work today - so please don't send me to some … -
Django : two users in rating form instance
I got a simple question. I don't understand how I get for rate_form.instance.sugar the sugargroup.seller. As RateSugar is related to Sugargroup I could normally do it. Bu I don't find the answer... Only user (which is consumer) can post the form. That's why I've used self.request.user views.py def form_valide(self, rate_form): if rate_form.is_valid(): rate_form.instance.relationto = self.object ##rate_form.instance.sugar = self.object.seller -> I need to change this to get the SELLER rate_form.instance.user = self.request.user rate_form.save() return super(CheckoutDetail, self).form_valid(rate_form) else: return super(CheckoutDetail, self).form_invalid(rate_form) models.py class Ratesugar(models.Model): relationto = models.OneToOneField(Sugargroup,on_delete=models.CASCADE, blank=True, null=True, related_name="ratesugar_relationto") sugar = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='ratesugar_sugar') user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='ratesugar_cooker') ... class Sugargroup(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_consumer", blank=True, null=True) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_seller") -
Token login Authentication Django REST
I want to be able to login a user using Token Authentication. For some reason my code is not working. I appreciate your help. Here is my code: Serializers.py: #Login class UserLoginSerializer(serializers.ModelSerializer): password = serializers.CharField(style= {'input_type':'password'}, label= ("Password")) def validate(self, attrs): email = attrs.get("email") password = attrs.get("password") if(email and password): user = authenticate(request= self.context.get("request") ,email= email, password= password) if(not user): raise serializers.ValidationError("Unable To Login With Provided Credentials!", code= "Authorization") else: raise serializers.ValidationError("Email and/or Password Fields are Invalid!", code= "Authorization") attrs["user"] = user return attrs class Meta: model = UserModel fields= ('email', 'password',) views.py class UserLoginView(ObtainAuthToken): parser_classes = [JSONParser, MultiPartParser, FormParser,] serializer_class = UserLoginSerializer def post(self, request): serializer = UserLoginSerializer(data= request.data) if(serializer.is_valid()): user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user= user) content = {"token": token.key,} return Response(content) return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) Thanks. -
How to add my own python code in django in views.py index function
I have a code of python in different files: st.py and mydefinations.py, yahoo.py. And These codes are working fine but whenever I integrate this code in django. It shows my error. This is my code of views.py in django. def index(request): latest_stocks_list = Stock.objects.all() template = loader.get_template('stocks/index.html') context = { 'latest_stocks_list': latest_stocks_list, } return HttpResponse(template.render(context, request)) And i want to add following code in the index function from mydefinations import * from yahoo import * headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} tickerslist = ["AAPL"] prntvar = {'prntnum': 0} mydef = mydefinations() for ticker in tickerslist: try: testdic = {'Var1': 0, 'Var2': 0} Ticker_stats = {} Ticker_summary = {} yahoo = my_yahoo(headers, ticker) Ticker_stats = yahoo.yahoo_stats() print(Ticker_stats) except Exception as e: pass Wen I add code in the index and import line in the start and error shows that mydefinations module is not found What should i do. -
Video play on hover in django template
I am displaying the list of videos in Django template by iterating the queryset object. I want to play a specific video on mouse enter. Django Template: {% for video in videos %} <div class="card bg-light pl-3" style="width:310px;height:300px;border:none"> <a href="{% url 'core:videoview' video.id %}"><video class="videocard" src="{{video.video_file.url}}" poster="{{video.thumbnail.url}}" alt="not found" style="height:185px" preload></a> <div class="card-body"> <div class="row" style=""> <div class="fst pt-2 pl-3"> <img src="{{video.video_owner.channel_owner.profile_pic.url}}" class="rounded-circle" style="height:45px" alt=""> </div> <div class="sec pt-2 pl-3"> <tr> <p class="font-weight-bold""><a href="{% url 'core:videoview' video.id %}" style="text-decoration:none;color:black">{{video.video_title|truncatechars:"25"}}</a> <br> <a href="#" style="text-decoration:none;color:black"><span class="font-weight-normal">{{video.video_owner}}</span></a> </p> </tr> </div> </div> </div> </div> {% endfor %} JavaScript: $(".videocard").on('mousenter', function(){ $('.videocard').get(0).play(); $('.videocard').get(0).currentTime = 0; }); $(".videocard").on('mouseout', function(){ $('.videocard').get(0).pause(); $('.videocard').get(0).currentTime = 0; }); but due to get(0), its only working for the first video in the video list. How to make it work for every displayed video? -
Restrict access to a function based view depending on a django variable
I have a Django variable which becomes true after a few conditions. I don't want the user to access the page if the variable is true. The page is a function based view: def complete(request): return render(request, 'users/complete.html') The variable is : complete_task = forms.BooleanField() Is it possible to do this with a function based view just like a custom mixin? -
Django 3.1: Access objects in template of ModelChoiceField
Using Django 3.1 and I'm struggling with a basic tasks. I've got a form with a field like this: forms.ModelChoiceField(queryset=StorageSpace.objects.filter(visible=True), widget=forms.RadioSelect) I would like to do this in my view: {% for space in form.available_spaces %} <input value="{{ space.id }}" data-storage-price={{ space.price }}>{{ space.title }} {% endfor %} But this doesn't work. How can I access the attributes of my objects for each choice? Can't be that difficult, can it? I really need to set the data attribute, otherwise I would just use{{space}}. -
error : Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I defined this class in views.py: class EditOrderStudents(generics.RetrieveUpdateDestroyAPIView): #permission_classes = (permissions.AllowAny,) authentication_classes = (TokenAuthentication , ) serializer_class =newOrdersStudentSerializidGet def get_queryset(self): id = self.request.query_params.get('id') queryset = newOrdersStudent.objects.filter(Groupid=(id)) return queryset and I use the RetrieveUpdateDestroyAPIView generic to put , delete and get methode but I got this error and I dont know what is the problem? AssertionError: Expected view EditOrderStudents to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. -
Django Elastic Beanstalk Cron job
I am trying to create a simple cron to send email. I searched and tried different answers but none of them seem to be working. This is my django.config It is one of the answer i found on net. container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true 02_cronjb: command: "cat .ebextensions/cronjobs.cron > /etc/cron.d/djangocrons && chmod 644 /etc/cron.d/djangocrons" leader_only: true 03_createsu: command: "source /opt/python/run/venv/bin/activate && python manage.py createsu" leader_only: true 04_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: github.settings PYTHONPATH: $PYTHONPATH aws:elasticbeanstalk:container:python: WSGIPath: github.wsgi:application aws:elasticbeanstalk:container:python:staticfiles: /static/: www/static/ packages: yum: postgresql95-devel: [] This is cronjobs.cron * * * * * root source /opt/python/run/venv/bin/activate && /opt/python/run/venv/bin/python /opt/python/current/github/manage.py cronjb >> /var/log/cronjobs.log This is my cronjb.py from django.core.management.base import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): def handle(self, *args, **options): subject = 'Hello' message = 'World' email_from = "abc@gmail.come" recipient_list = ['abc@gmail.com'] send_mail(subject, message, email_from, recipient_list) It all gets deployed without any error but the i am not receiving any emails. Is there something wrong? -
How connect polymer 3 application front-end to Django back-end build with djangorestframework?
I have a polymer 3 application folder and a django app folder. I can run the front-end polymer app on it's the root folder like this:- polymer serve And the back-end Django app providing the rest service like this:- python manage.py runserver These are two in separate folders but I want to connect these two so that in the front-end polymer Js app I can access the Django app API rest service and populate all the relevant data in the front-end. Note I want to deploy the app to heroku too. How do I go about this to make them work as a single app? -
Django Model - Modeling on Django ORM (Postgres-12 Database View)
I'm having a hard time figuring out how to model Postgres database view (I'm using Postgres 12) to Django ORM (Django 3.1 and Python 3.8.5). I tried this answered here in stackoverflow but still I got the same error. To visualized my database schema Database Objects Tables: |_items |_uom |_location | Views: |_vItems the vItems contains the SQL command joining the three tables items, uom, location, when running the SQL command below to the pgAdmin 4. I can fetch all the items data without getting any errors. SELECT * FROM vItems Here is my Django models.py code: class Items(models.Model): id = models.AutoField(primary_key = True) item_code = models.CharField(max_length = 100) sku = models.CharField(max_length = 100) name = models.CharField(max_length = 100) description = models.CharField(max_length = 100) uom_id = models.IntegerField() location_id = models.IntegerField() created_date= models.DateTimeField(default=timezone.now) created_by = models.IntegerField() updated_date= models.DateTimeField(auto_now = True) updated_by = models.IntegerField() class Meta: db_table = "items" def __str__(self): return self.name def get_absolute_url(self): return reverse('item_detail', kwargs = {'pk': self.id}) class UOM(models.Model): id = models.AutoField(primary_key = True) uom = models.CharField(max_length = 50) created_date= models.DateTimeField(default=timezone.now) created_by = models.IntegerField() updated_date= models.DateTimeField(auto_now = True) updated_by = models.IntegerField() class Meta: db_table = "uom" def __str__(self): return self.uom class Location(models.Model): id = models.AutoField(primary_key = True) location … -
Django templates' for loop simply does not show html code
I am trying to create a page that shows all the winnings the user has. The URL is running a function that renders a template. In the template there's a FOR loop that has an empty condition. The HTML doesn't show the empty condition nor the FOR loop itself... Check out the image at the end. Here are the models used: class CreateListing(models.Model): owner = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.CharField(max_length=64) category = models.CharField(max_length=64) price = models.CharField(max_length=64) link = models.CharField(max_length=64, blank=True, null=True, default=None) time = models.CharField(max_length=64) class Watchlist(models.Model): user = models.CharField(max_length=64) listingid = models.IntegerField() class Closedbid(models.Model): owner = models.CharField(max_length=64) winner = models.CharField(max_length=64) listingid = models.IntegerField() winprice = models.IntegerField() The URL: from django.urls import path from . import views urlpatterns = [ path("mywinnings/<str:username>", views.mywinnings, name="mywinnings") ] My function: def mywinnings(request, username): if request.user.username: items = [] wonitems = Closedbid.objects.filter(winner=username).all() for w in wonitems: items.append(CreateListing.objects.filter(id=w.listingid).all()) try: w = Watchlist.objects.filter(user=request.user.username) wcount = len(w) except: wcount = None return render(request, 'auctions/mywinnings.html', { "items": items, "wcount": wcount, "wonitems": wonitems }) else: return HttpResponseRedirect(reverse('index')) My HTML template: {% extends "auctions/layout.html" %} {% block body %} <div class="container"> <h2>Your Winnings</h2> </div> <div class="container" id="listings"> {% for item in items %} {% for i in item %} … -
Django Local module import is not working
I have the following directory structure: . ├── LMS │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── VENV │ ├── bin │ ├── include │ ├── lib │ └── pyvenv.cfg ├── assets │ ├── css │ ├── images │ └── js ├── courses │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── fields.py │ ├── fixtures │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── templatetags │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── media │ ├── course_images │ ├── files │ └── images ├── templates │ └── base.html └── users ├── __init__.py ├── __pycache__ ├── admin.py ├── apps.py ├── forms.py ├── migrations ├── models.py ├── templates ├── tests.py ├── urls.py └── views.py Now I'm trying to import courses.models.Course in my users.models in the following way: from courses.models import Course but its giving an error as: from courses.models import Course ImportError: cannot import name 'Course' from 'courses.models' (/Users/abdul/PycharmProjects/LMS/courses/models.py) -
Passing a form into django's detail view
Im new to django and im trying to pass a form into detail view(which ive done)but i get an error on submitting the form Here's the code below class student_listview(DetailView): model = Post template_name='promise/detail.html' def get_context_data(self, *args, **kwargs): form = Comment_form stud_list = Categories.objects.all() context = super(student_listview, self).get_context_data(*args, **kwargs) context["stud_list"] = stud_list context["form"] = form return context It gives a page does not exist error when i try to submit the form -
How to change the id of any tag wiht javascript?
Html Code:- {% for post in posts %} <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="{% url 'post-detail' post.slug %}">{{ post.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">{{ post.date_posted }}</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="{% static "blog/viewicon.png" %}"> <p style="float: right; display: inline !important;" id="ViewCount"> </p> </img> </div> </div> <p class="article-content">{{ post.content|truncatechars:200|safe }}</p> </div> <script> function changeid () { var e = document.getElementById('post_title'); e.id = 'post_title_1'; var e = document.getElementById('ViewCount'); e.id = 'ViewCount_1'; } </script> </article> {% endfor %} I am trying to change the id of those two tags but, this script doesn't seem to work, or it's been not exected. I want to change that id because I want to insert some data to them from the server. Since we can't have the same id the data which I am trying to embed is embedded by defaut to only the first run of the loop.