Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web3py Interacting with smart contract
Hey I'm working on a project and want to know if I can use python/django to make a frontend dapp where people can mint a token while connected to metamask ? Like signing their account and interact with the smart contract ? I really don't get it why I need to use javascript in order to make a minting process. Can some ligten me so I can continue to focus on python/django to AUTH, INTERACT with the blockchain. -
Django Ajax Not Found "url"
i am trying to use ajax with django: $('.btnMyc').click(function() { $.ajax({ type: "GET", url: "/getpic", data: { username: document.getElementById("usernameid").value }, urls.py: urlpatterns = [ path('', views.vscomain, name="vscomain"), path('getpic',views.send_pic,name="getpic"), ] and there is a function names send_pic in views.py but when i type username and click it i get this error: Not Found: /getpic [21/Sep/2021 14:00:59] "GET /getpic?username=sfdgl HTTP/1.1" 404 2400 -
Error while loading static files in Django
Trying to load static files but it is showing following error. ERROR GET http://127.0.0.1:8000/static/css/user/style.css net::ERR_ABORTED 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/css/user/style.css 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:149 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:1 Click here to see error image. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Dirs Structure Click here to Project Directory Structure Image CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading But some media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. Also in dir structure, we can see img and css folder at same place in static folder and images from image folder are loaded but css from css folder does not. -
Using saved database settings to generate code (if-statements) [closed]
I currently have an app that generates financial documents based on user-set settings These settings look something like this: Trial Balance ☐ Use main accounts ☐ Include Opening Balances ☐ Print Null Values ☐ Print Account Number All these settings are boolean variables and can easily be checked with if UseMainAccount == True : However, this would obviously take quite a few if statements to complete and can become very tedious. Is there a way to shorten this process (I know in Delphi and some other codes there are "case" statements for this. But would a case statement be possible in Django/Python -
Token generated by django-restframework-simplejwt not valid
This was working just fine before I tried to add social authentication to the project, and now when I send the verification email with the token, the token verifier says that the token is not valid! class ResendVerifyEmail(APIView): serializer_class = RegisterSerialzer def post(self, request): data = request.data # email = data.get('email') email = data['email'] print(email) try: user = User.objects.get(email=email) # print('hello') if user.is_verified: return Response({'msg':'User is already verified','status':'status.HTTP_400_BAD_REQUEST'}) print (user.username) token = RefreshToken.for_user(user).access_token current_site= get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + ' this is the resent link to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) return Response({'msg':'The verification email has been sent','status':'status.HTTP_201_CREATED'}, status=status.HTTP_201_CREATED) except User.DoesNotExist: return Response({'msg':'No such user, register first','status':'status.HTTP_400_BAD_REQUEST'}) class VerifyEmail(APIView): serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) # print('decoded') user = User.objects.filter(id=payload['user_id']).first() # print(user) if user.is_verified: return Response({'msg':'User already verified!'}, status=status.HTTP_400_BAD_REQUEST) else: user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated','status':'status.HTTP_200_OK'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) also, I have added these … -
Regex Error Finding Details from a bank statement
I am working with Regex and currently I am trying to extract the Name, IFSC and Account No. from the PDF. I am using following code to extract the details. acc_name= " ", '\n'.join([re.sub(r'^[\d \t]+|[\d \t]+:$', '', line) for line in data.splitlines() if 'Mr. ' in line]) acc_no= " ", '\n'.join([re.sub(r'Account Number\s+:', '', line) for line in data.splitlines() if 'Account Number' in line]) acc_code = " ", '\n'.join([re.sub(r'IFSC Code\s+:', '', line) for line in data.splitlines() if 'IFSC Code' in line]) But the data which I am getting back is following: (' ', ' 50439602642') (' ', 'Mr. MOHD AZFAR ALAM LARI') (' ', ' ALLA0211993') I want to remove the commas, brackets and quotes. I am new with regex so any help would be appreciated. -
Upload an csv file then, store data in MCQs format in the model
I'm creating an quiz app in django.The model is like this, class Question(models.Model): questions = models.CharField(max_length=50, unique=True) choice1 = models.CharField(max_length=50, unique=True) choice2 = models.CharField(max_length=50, unique=True) choice3 = models.CharField(max_length=50, unique=True) choice4 = models.CharField(max_length=50, unique=True) correct_answer = models.CharField(max_length=50, unique=True) I want to upload an MCQ-contained file and the model automatically stores the MCQs according to entries. e.g, if the file contains 20 MCQs then all MCQs store in the model according to the pattern given above. -
Django: How to delete Media Files on Digitalocean Spaces/ Amazon S3 automatically when Model instance is deleted
I have the following model defined in my Django-App def directory_path(instance, filename): return 'attachments/{0}_{1}/{2}'.format(instance.date, instance.title, filename) class Note(models.Model): title = models.CharField(max_length=200) date = models.DateField(default=datetime.date.today) # File will be saved to MEDIA_ROOT/attachments attachment = models.FileField(upload_to=directory_path) def __str__(self): return self.title I successfully set up AWS S3/ Digitalocean Spaces to store the media file uploaded via the attachment field. However, when I delete an instance of the model, the file remains in my bucket. What do I have to do, in order to delete the file automatically in my s3 bucket, if the corresponding model intance is deleted? -
How can I change template of account activation Email of django
I created class based view to access uid and token . Here I create one web page which have one button of activate user. I am sending one uid and token to user email. I created class based view to get uid and token. I am sending email on user gmail account. where user get link for activate his account. Email looks like this : You're receiving this email because you need to finish activation process on 127.0.0.1:8000. Please go to the following page to activate account: http://127.0.0.1:8000/activate/Mg/ata7ek-01e823899301fe357286112596a25655 Thanks for using our site! The 127.0.0.1:8000 team .... But now I wish to change this content/template of email for activate account . How can I change this template in django Here is my djoser setting DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'user_profile.serializer.UserSerializer', 'user': 'user_profile.serializer.UserSerializer', } } How can I change it ? -
How to resolve missing dependencies in Docker Alpine
I have Django application that works just fine when I build my docker image using python:3.10.0rc2-buster or python:3.10.0rc2-slim-buster without any problem. In order to decrease the image size, I switched to python:3.10-rc-alpine, however, I am facing dozens of missing dependencies. I found this post very helpful Docker Alpine Linux python (missing) It allowed me to resolve some of the missing dependencies. Appreciate your support to guide me on what can I do to resolve this ? These are the missing dependencies errors I am receiving: #6 9.141 ERROR: unable to select packages: #6 9.173 libcairo2 (no such package): #6 9.173 required by: world[libcairo2] #6 9.173 libgdk-pixbuf2.0-0 (no such package): #6 9.173 required by: world[libgdk-pixbuf2.0-0] #6 9.173 libldap2-dev (no such package): #6 9.173 required by: world[libldap2-dev] #6 9.173 libpango-1.0-0 (no such package): #6 9.173 required by: world[libpango-1.0-0] #6 9.173 libpangocairo-1.0-0 (no such package): #6 9.173 required by: world[libpangocairo-1.0-0] #6 9.173 libsasl2-dev (no such package): #6 9.173 required by: world[libsasl2-dev] #6 9.173 libsnmp-dev (no such package): #6 9.173 required by: world[libsnmp-dev] #6 9.173 libssl-dev (no such package): #6 9.173 required by: world[libssl-dev] #6 9.173 pdftk (no such package): #6 9.173 required by: world[pdftk] #6 9.173 python-dev (no such package): #6 9.173 required … -
How do i query all the fields in a django Many to Many
Trying to loop over a many to many relationship where I want all the fields. My Models: class Recipe(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from="title") category = models.ForeignKey(RecipeTopic, on_delete=models.CASCADE) image = models.ImageField() description = models.TextField() ingredients = models.ManyToManyField(Ingredient, through="IngredientList") directions = models.TextField() servings = models.IntegerField() time = models.IntegerField() cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) def __str__(self): return self.title class IngredientList(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) Recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) amount = models.FloatField(default=1) unit = models.ForeignKey(Units, on_delete=models.CASCADE) My Views: from .models import Recipe def home(request): recipe = Recipe.objects.all() context = { "title": "Home Page", "recipe": recipe } return render(request, "home.html", context) and my template: {%for r in recipe %} <h2>{{r.title}}</h2> <h4>Ingredients:</h4> {%for i in r.ingredients.all %} <p>---{{i.amount}}{{i.unit}} {{i.ingredient}}</p> {%endfor%} {%endfor%} Want to showcase the ingredients, their amount, and the units that goes along with them. Except that I am only getting the "ingredient" title -
setting new file storage path in django model
I am trying to change the file storage path in model instance via view.py (instance.model.path = new_path) and I get can't set attribute. Not sure why as I can change the file name. view.py def SaveFile(request): if request.method == 'POST': model, created = MyModel.objects.get_or_create(record_id=request.POST['record_id']) file=request.FILES['report'] model.report = file.name call_id = model.record.call_ID date = datetime.now() date = str(date.strftime("%d.%m.%Y-%H:%M:%S")) file_storage = FileSystemStorage(location=os.path.join(MEDIA_ROOT, 'Reports', call_id)) file_name = file_storage.save(str(date + '-' + file.name),file) model.report.path = file_storage.location model.report = file_name model.save() return JsonResponse(file_name, safe=False) -
Errors don't show in Templates after custom validation
I'm working on a form where few field inputs depend on each other. I implemented custom validation and added error messages to it but, although custom validation works, error messages don't get shown in templates. form.py class NewCalculationForm(forms.ModelForm): def clean(self): cleaned_data = super(NewCalculationForm, self).clean() if self.cleaned_data.get('Tsrcin') <= self.cleaned_data.get('Tsrcout'): raise forms.ValidationError({"Tsrcout": "Source outlet temperature has to be lower than inlet temperature."}) # msg = "Source outlet temperature has to be lower than inlet temperature." # self.errors["Tsrcout"] = self.error_class([msg]) if self.cleaned_data.get('Tsinkin') >= self.cleaned_data.get('Tsinkout'): raise forms.ValidationError({"Tsinkout": "Sink outlet temperature has to be higher than inlet temperature."}) # msg = "Sink outlet temperature has to be higher than inlet temperature." # self.errors["Tsinkout"] = self.error_class([msg]) return cleaned_data class Meta: model = Calculation fields = ['Tsrcin', 'Tsrcout', 'Qsrc','Tsinkin','Tsinkout',] view.py def index(request): if request.method == 'POST': form = NewCalculationForm(request.POST or None) if form.is_valid(): Tsrcin = form.cleaned_data.get("Tsrcin") Tsrcout = form.cleaned_data.get("Tsrcout") Qsrc = form.cleaned_data.get("Qsrc") Tsinkin = form.cleaned_data.get("Tsinkin") Tsinkout = form.cleaned_data.get("Tsinkout") [Pnet, Pel, thermaleff, savepath] = cycle_simulation(Tsrcin, Tsrcout, Qsrc, Tsinkin, Tsinkout) file1 = DjangoFile(open(os.path.join(savepath, "TSDiagrammORCCycle.png"), mode='rb'),name='PNG') file2 = DjangoFile(open(os.path.join(savepath, "TQDiagrammORCCycle.png"), mode='rb'),name='PNG') instance = Calculation.objects.create(userid = request.user,Tsrcin = Tsrcin, Tsrcout = Tsrcout,\ Qsrc = Qsrc, Tsinkin = Tsinkin, Tsinkout = Tsinkout, Pel = Pel,\ time_calculated = datetime.today(), result = Pnet,\ thermaleff … -
How to perform a __all_in query with Django?
I have three models class Pizza(models.Model): toppings = models.ManyToManyField(Topping) class Topping(models.Model): name = models.CharField(max_length=50) class Order(models.Model): must_have_toppings = models.ManyToManyField(Topping) I want to find all Orders that match a certain Pizza. For this, I would like to do something like orders = Order.objects.filter(must_have_toppings__all_in=my_pizza.toppings) What I tried: orders = Order.objects.filter(must_have_toppings__in=my_pizza.toppings) doesn't work, because Orders with just one of the Pizza's toppings in their must_have will be returned. And: orders = Orders.objects for topping in my_pizza.toppings.all(): orders = orders.filter(must_have_toppings=topping) doesn't work, because it will return orders that have all the toppings from the pizza, even if some of the must_have_toppings are missing. For example, a Pizza with Tomatoes and Mushrooms will return an Order that needs Tomato, Pepper, and Mushroom. How can I look for Orders where the must_have_toppings are ALL in the Pizza object? (I am using MySql) -
How to pass value to django admin change list template?
I am linking my django admin to a custom change list template as shown in the images below, but how can I pass on a variable to this template from my admin page? -
How to create relation on in django User model and other model if other model have two fields to make relation
I am working on an application where I have two types of users Patients and Doctors, where patients can book appointments with doctors. I am using Django's built-in User model to register users. I have an appointment model but I am unable to make the relation between the appointment model and the user model as I want to reference the patient and doctor in the appointment model. when I tried with Foreign Key Appointment Model class Appointment(models.Model): patient = models.ForeignKey(UsersInfo,on_delete=models.CASCADE,default="None") doctor = models.ForeignKey(DoctorInfo,on_delete=models.CASCADE,default="None") doctor = models.CharField(max_length=20,blank=False) patient = models.CharField(max_length=20,blank=False) date = models.DateField(blank=False) time = models.TimeField(blank=False) status = models.CharField(default="pending",blank=True, max_length=20) during migrate python manage.py migrate Error (venv) D:\Python\Django\FYP\HeatlhCare>py manage.py migrate Operations to perform: Apply all migrations: Users, admin, auth, contenttypes, sessions Running migrations: Applying Users.0002_auto_20210921_1250...Traceback (most recent call last): File "D:\Python\Django\FYP\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'None' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Python\Django\FYP\HeatlhCare\manage.py", line 22, in <module> main() File "D:\Python\Django\FYP\HeatlhCare\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python\Django\FYP\venv\lib\site-packages\django\core\management\base.py", line … -
Django Excel Export (using xlwt)
I'm trying to export data tied to an id from a view, to an excel file, this is the code: from django.shortcuts import render from clientesapp.models import Cliente, Orden from django.http import HttpResponse import xlwt def excel_create(request, id): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="recibo.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('recibo') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold=True columns = ['Orden', 'Cliente', 'Entrada', 'Instrumento', 'Marca',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Orden.objects.get(id=id) rows.values_list('num_orden', 'client', 'fechain', 'instrumento', 'marca') for row in rows: row_num +=1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response I want to export to excel this table, that also shows the id i need to get the data: Table with id But this code shows me the error "Orden object have no attribute values_list". How can i solve this problem? -
Redirection failure in django
I'm trying to create a dashboard on Django It consists of 7 pages and every third page is giving error PYCHARM, django module Localhost Python 3,7 Django Latest version I have written all the URLs properly And it comes like that Localhost/maps this one is fine but the next click is Localhost/maps/reports now this is error I want that every time a link is clicked it goes back to localhost and then take the new link.The codes urls are like this from django.urls import path from . import views urlpatterns = [ path('', views.index), path('login/', views.login), path('maps/', views.maps), path('profile/', views.profile), path('preferences/', views.preferences), path('register/', views.register), path('reports/', views.reports), path('weather/', views.weather), path('help/', views.help), ] -
How to display PDF files in the same html page in file history in Django?
I have a web application created with Django in which a user can upload a pdf file. There is a view called 'file history' which displays the 'ID', 'Docfile', 'Source', 'Date'. And when a user clicks on a file name I'd like to display it in the same html page. I have read a lot of similar question on stackoverlflow and other sites on the internet but I did not find a useful guide except the one below: A similar solution can be found here: ChillarAnand's answer The html page looks like this: The code which produces this is: class Version(models.Model): docfile = models.FileField(upload_to = history_directory_path, db_column = 'docfile',max_length=500) source = models.CharField(max_length=50,default='') date = models.DateTimeField(auto_now_add=True, db_column='date') def doc_url(self): if self.docfile and hasattr(self.docfile, 'url'): return self.docfile.url How can I use this code snippet in my model? def embed_pdf(self, obj): # check for valid URL and return if no valid URL url = obj.pdf_file.url html = '<embed src="{url}" type="application/pdf">' formatted_html = format_html(html.format(url=obj.cover.url)) return formatted_html -
Django Rest Framework partial=True not working
I am a beginner in Django & DRF and I have a very dumb problem with my project, in which it doesn't allow me to do partial update. I am using generic views (UpdateAPIView) and I have been stuck with it for 2 weeks now. It allows me to update, however I have to fill every field but what I want to do is to pop email & mobile number if they are the same as the stored value in the database. Hoping someone might help and thank you in advance. Model: class BusinessPartner(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) mobile_number = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=150, unique=True) business_name = models.CharField(max_length=255, blank=True) type_of_business = models.CharField(max_length=150, blank=True) street_address = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=150, blank=True) state_province = models.CharField(max_length=150, blank=True) postal_zip = models.IntegerField(null=True, blank=True) services_offered = models.TextField(null=True, blank=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) class Meta: ordering = ["-account"] def __str__(self): return self.first_name + " " + self.last_name Serializer: class BusinessPartnerSerializer(serializers.ModelSerializer): class Meta: model = BusinessPartner fields = [ "id", "first_name", "last_name", "mobile_number", "email", "business_name", "type_of_business", "street_address", "city", "state_province", "postal_zip", "services_offered", "account", ] extra_kwargs = {"id": {"read_only": True}} def update(self, instance, validated_data): partner = BusinessPartner.objects.get(account=instance) print("Previous mobile number: ", getattr(partner, "mobile_number")) print("New mobile number: … -
how can i resolve this 'Push rejected, failed to compile Python app. ! Push failed' error in heroku
i am getting this build error while deploying on heroku can anyone tell why is this error happened ? Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting pyttsx3==2.90 Downloading pyttsx3-2.90-py3-none-any.whl (39 kB) Collecting pytz==2021.1 Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) ERROR: Could not find a version that satisfies the requirement pywin32==300 (from -r /tmp/build_7bcad96a/requirements.txt (line 99)) (from versions: none) ERROR: No matching distribution found for pywin32==300 (from -r /tmp/build_7bcad96a/requirements.txt (line 99)) ! Push rejected, failed to compile Python app. ! Push failed my requirements.txt has asgiref==3.4.1 beautifulsoup4==4.10.0 bs4==0.0.1 certifi==2021.5.30 charset-normalizer==2.0.4 Django==3.2.7 django-phone-field==1.8.1 djangorestframework==3.12.4 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.8.0 docutils==0.17.1 gunicorn==20.1.0o idna==3.2 Kivy==2.0.0 kivy-deps.angle==0.3.0 kivy-deps.glew==0.3.0 kivy-deps.sdl2==0.3.1 Kivy-Garden==0.1.4 Pygments==2.10.0 PyJWT==2.1.0 pypiwin32==223 pytz==2021.1 pywin32==301 requests==2.26.0 soupsieve==2.2.1 sqlparse==0.4.1 termcolor==1.1.0 urllib3==1.26.6 whitenoise==5.3.0 setuptools==0.7.3 is it just because of python or something else..? any solutions pls.. -
Django form is always returning false:
I am trying to update an entry. But form.save() is returning false. And I am unable to get the situation. Views.py def update(request, id): customer = Customer.objects.get(id=id) if request.method == "POST": form = customerForm(request.POST, instance=customer) if form.is_valid(): form.save() return redirect("/") else: return render(request, 'index.html') else: form = customerForm() return render(request, 'edit.html', {'customer': customer}) models.py from django.db import models from django.db import connections # Create your models here. class Customer(models.Model): # id = models.CharField(max_length=100) customer_name = models.CharField(max_length=256) phone = models.CharField(max_length=256) address = models.CharField(max_length=256) city = models.CharField(max_length=256) email = models.EmailField() product_company = models.CharField(max_length=256) product_brand = models.CharField(max_length=256) product_model = models.CharField(max_length=256) imei = models.CharField(max_length=20) reported_issue = models.CharField(max_length=256) possible_solution = models.CharField(max_length=256) actual_solution = models.CharField(max_length=256) estimated_time = models.CharField(max_length=256) actual_time = models.CharField(max_length=256) current_status = models.CharField(max_length=256) additional_notes = models.CharField(max_length=256) date_created = models.CharField(max_length=256) date_updated = models.CharField(max_length=256) class Meta: db_table = "datagrid" forms.py from django import forms from django.forms import fields, widgets from customerDetails.models import Customer class customerForm(forms.ModelForm): class Meta: model = Customer fields = ['id', 'customer_name', 'phone', 'address', 'city', 'email', 'product_company', 'product_brand', 'product_model', 'imei', 'reported_issue', 'possible_solution', 'actual_solution', 'estimated_time', 'actual_time', 'current_status', 'additional_notes', 'date_created', 'date_updated'] widgets = {'customer_name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'city': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'product_company': forms.TextInput(attrs={'class': 'form-control'}), 'product_brand': forms.TextInput(attrs={'class': 'form-control'}), 'product_model': forms.TextInput(attrs={'class': 'form-control'}), … -
'Tag' object has no attribute 'count' in for loop
I am building a BlogApp and I am trying to create a notification when a particular tag is used 10 times. So i am using if statement in for loop so if any tag used 10 times then create notification But when i try to count then it is showing 'Tag' object has no attribute 'count' models.py class Post(models.Model): post_user = models.ForeignKey(User, on_delete=models.CASCADE) psot_title = models.CharField(max_length=30) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(Post, on_delete=models.CASCADE) views.py def page(request): subquery = Tag.objects.filter(post__post_user=request.user).annotate( num_name=Count('name') for que in subquery: if que.count() > 10: Notification.objects.create(user=request.user) context = {'subquery':subquery} return render(request, 'page.html', context} What have i tried :- I also tried len like :- for que in subquery: if len(que) > 10: Notification.objects.create(user=request.user) But it showed object of type 'Tag' has no len() I have tried many times by removing count() and len() but it showed 'int' object has no attribute 'name' Any help would be much Appreciated. Thank You -
Django: How to pass js variable to html template as tag
My task is to send the result of the test, created using javascript, to the html-template to use it in the {% if mark> = 4%} tag, in order to write to the database that the test is passed. I tried composing an ajax request but not sure if it is correct. views.py def practice(request, lesson_id): form = LessonDone() posts = get_object_or_404(Lessons, pk=lesson_id) lessonid = Lessons.objects.get(pk=lesson_id) mark = request.POST.get('url') if request.method == 'POST': p, created = DoneLessonsModel.objects.get_or_create( user=request.user, lessons=lessonid, defaults={'done': True}, ) form = LessonDone(request.POST, instance=p) if form.is_valid(): try: form.save() return redirect('practice') except: form.add_error(None, 'Ошибка') context = {'posts': posts, 'form': form, 'mark': mark} return render(request, 'landing/../static/practice.html', context) urls.py ... path(r'lesson/<int:lesson_id>/practice/', views.practice, name='practice'), ... practice.html ... <div class="buttons "> <button class="restart btn-dark">Перепройти тест{{ mark }}</button> {% if mark >= 4 %} <form action="" method="POST"> {% csrf_token %} {{ form }} {% endif %} <button class="quit btn-dark" type="submit" value="Submit" id="send-my-url-to-django-button">Выйти</button> {% if mark >= 4 %} </form> {% endif %} </div> ... </script> <script type="text/javascript"> $(document).ready(function() { var url = userScore; $("#send-my-url-to-django-button").click(function() { $.ajax({ url: {% url 'practice' posts.pk %}, type: "POST", dataType: "json", data: { url: url, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the URL to … -
How to restrict staff unauthorize access to admin page django?
I have created my admin page, so when the admin login it will redirect them to this url http://127.0.0.1:8000/home/, but the admin can change the url to http://127.0.0.1:8000/logistic/ after they login, how to prevent this from happen? Any help would be appreciated