Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access request object of django in react?
I have multiple apps in my Django project but for One app I would like to use react, so I have create two apps one for apis and other for frontend. I used webpack to merge django and react. Now I want to access request.user and user.is_authenticated in my components. How can I access those without calling apis as I am not using token-based authentication so I can not call APIs. views.py def index(request): return render(request,'index.html') urls.py urlpatterns = [ re_path(r'^(?:.*)/?$',index), ] I would like to use is_authenticated in my sidebar everywhere. -
DRF, get foreignkey objects using option
i'm trying to make backend using DRF, and i just faced a problem This is models class SchoolYear(models.Model): title = models.CharField(max_length=255, unique=True) class Student(models.Model): name = models.CharField(max_length=10) school_year = models.ForeignKey( "students.SchoolYear", related_name="school_year", on_delete=models.CASCADE, ) class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' Result from POSTMAN when using the option. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": { "type": "field", "required": true, "read_only": false, } } } } But I want to get a result like this. Because I have to deliver this to the front-end developer to make select form I'd like to use this method, so I'd appreciate it if you could let me know if there's any other good method. Thanks. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": [ { "id" : 1, "title": "title1", }, { "id" : 2, "title": "title2", }, { "id" : 3, "title": "title3", }, { "id" : 4, "title": "title4", } ] … -
change color of button after click
I have a question with four answers and I want the button to flash green when the correct answer is selected and red when the wrong answer is selected. How can I do that? i want to solve this problem with django and not with javascript. html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next" value="{{q.question}}" class="nächstefrage_btn">Nächste Frage!</button></div> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{erste_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{erste_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" [ngClass] = value="{{zweite_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{zweite_frage}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{dritte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{dritte_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{vierte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{vierte_frage}}</span></button></p> </div> </div> </div> <div class="menü"> <button class="menü_button" formaction="{% url 'Example_dashboard' %}" ><i class="fa fa-bars" aria-hidden="true"></i><b> Menü</b></button> <div class="items"> <a href="{% url 'Example_dashboard' %}"> <i class="fa-solid fa-house"></i> Startseite </a> <a href="{% url 'Example_fragenkatalog' %}"> <i class="fa-solid fa-pen"></i> Fragenkatalog </a> <a href="{% url 'statistics' … -
Django cannot display a PDF inline on a web page using <embed> or <object> or <iframe> tags
I am trying to embed a PDF into a web page in Django. This is the message I see in the console: Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. Here is the function definition in my python file: from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt from django.template.loader import render_to_string ... @login_required @xframe_options_exempt def resource_entity_screen(request,pk): ... rendered = render_to_string('classroom/resourcecenter/resource_entity_display.html', \ {'src' : url_src, \ 'embed_pdf' : embed_pdf, \ 'embed_video' : embed_video, \ 'embed_audio' : embed_audio, \ 'embed_image' : embed_image, \ 'obj_type' : obj_type, \ 'image_info' : image_info}) return HttpResponse(rendered) I ncluded this code instead of a straight render because I read in another post that the decorator only works with HttpResponse. However even with this code I am still getting the message shown above (in the console). I did clear my cache and do a reload, and also tried Ctrl-Shift R as well. No change. Can anyone tell me what I am missing? Is there something additional needed in settings.py? I have not tried deploying this to a testing server on the web to see if it just my local testing environment. -
Django media image not showing up in template but can acces it via .../media/thumbnail/image.png
Altough context does render in html, i can use other variables but cant accsess the image. My code is: html: {% for a in Manga %} <div class="manga_container"> <div class="manga_image"> <p>{{a.manga_image}}</p> <img src="{{ x.manga_image.url }}" alt=""> </div> </div> {%endfor%} model: class Manga(models.Model): manga_name = models.CharField(max_length= 255, default="null") manga_image = models.ImageField(upload_to="thumbnail", default="thumbnail/noimage.png") def __str__(self): return f"{self.id}, {self.manga_name}" and lastly view: def Index(request): manga = Manga.objects.all().values() chapter = Chapter.objects.all().values() fansub = Fansub.objects.all().values() context= { "Manga": manga, "Chapter": chapter, "Fansub": fansub, } template = loader.get_template("Index.html") return HttpResponse(template.render(context, request)) ı have used function based views since ı have to deal with multiple models at once. my media and url is as following: import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urlpatterns = [ ... ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have put that p tag for me to see its url and as you can see it was in the right place, when i go to 127.0.0.1:8000/media/thumbnail/noimage.png i can see it and it does come up to my screen. i have tried most of the ways i could have think of. I want to see the image on my html and i didnt touch anything so it is basicly default image as i have … -
Image not getting uploaded in Django
I tried to save a record using two different methods but both are not working. Django Form Models (create method) 1 I have created a ModelForm class ProductForm(ModelForm): class Meta: model= ProductDetails fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3") labels={ "name":"Product Name", "product_details":"Description", "category":"Category", "subcategory":"Sub-Category", "price":"Price", "mrp":"MRP", "main_img":"Main Image", "img1":"Image 1", "img2":"Image 2", "img3":"Image 3", } widgets = { 'name':forms.TextInput(attrs={'class':'form-control validate',}), 'product_details':forms.TextInput(attrs={'class':'form-control validate',}), 'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'price':forms.TextInput(attrs={'class':'form-control validate',}), 'mrp':forms.TextInput(attrs={'class':'form-control validate',}), 'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), } Models File # For Product details class ProductDetails(models.Model): name= models.CharField(max_length=100) price= models.FloatField() mrp= models.FloatField() main_img = models.ImageField(upload_to='product_img') img1 = models.ImageField(upload_to='product_img') img2 = models.ImageField(upload_to='product_img') img3 = models.ImageField(upload_to='product_img') category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE) product_details = RichTextField(blank=True, null=True) trending = models.BooleanField(default=False) def __str__(self): return self.name Method 1 Save record using form.save() getting Form validation error I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully. The validation error is just because of some issue with the image uploading print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul> def add_product(request): if request.method … -
Django context pass only None value
I have a view where I want to pass a variable to my template, however the value is always passed as None, as shown in numerals 1 , 2 and 3. What am I doing wrong please your help, I know it's a newbie question, actually I'm very newbie. views.py def create_address(request, dni): person = None addresses = None if request.method == 'POST': form = CreateAddressForm(request.POST) if form.is_valid(): try: person = Persona.objects.get(numero_documento=dni) addresses = Direccion.objects.filter(numero_documento=dni) print(f'Persona: {person}') # (1) print person ID. f = form.save(commit=False) f.numero_documento = person f.save() messages.success(request, 'Dirección registrada con éxito.' ) if 'save' in request.POST: return HttpResponseRedirect(reverse('persons:list')) if 'add_data' in request.POST: return HttpResponseRedirect(reverse('persons:create_address', kwargs={'dni': dni})) except Persona.DoesNotExist: person = None messages.error( request, 'El número de DNI no existe en la base de datos.' ) except Direccion.DoesNotExist: addresses = None messages.error( request, 'No se ha registrado ninguna dirección.' ) else: person = None messages.error( request, 'No se pudo registrar la dirección.' ) else: form = CreateAddressForm() template = 'persons/addresses/create_address.html' context = { 'pre_title': 'Direcciones domiciliarias', 'person': person, # (2) The value of "person" is "None". 'form': form, 'addresses': addresses, } return render(request, template, context) template.html (3) Value of "person" is "None". <div class="tab-pane active show" id="tabs-address-data"> Number … -
DRF Response VS Django - JSONResponse
from rest_framework.response import Response from django.http import JsonResponse What is the difference between these two? how can I decide which one should I use? -
How to get IP address of all devices connected on WLAN
Am working on a Django website. Basically, I want to block and IP once it perform an operation, when that Particular IP comes to perform that same operation then the system will not allow it. Now my problem is if a set of devices are connected on the same network and an operation is performed on the site, another person on that same network cannot perform that operation again because the IP has already been used, so how do I get all IP address connected through WLAN. This the code am using import ipaddress import socket import re def is_valid_ip(ip_address): """ Check Validity of an IP address """ try: ip = ipaddress.ip_address(u'' + ip_address) return True except ValueError as e: return False def is_local_ip(ip_address): """ Check if IP is local """ try: ip = ipaddress.ip_address(u'' + ip_address) return ip.is_loopback except ValueError as e: return None def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') ip_address = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') if x_forwarded_for and ',' not in x_forwarded_for: if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for): ip_address = x_forwarded_for.strip() else: ips = [ip.strip() for ip in x_forwarded_for.split(',')] for … -
Python weasyprint unable to find 'gobject-2.0-0' library
While following the installation process for Saleor headless e-commerce, the Python Weasyprint package fails to load the gobject-2.0.0 dependency which I have already installed on my machine using Macport. Below is the source code showing where the error is emitting from after starting the Django server. The file holds utility functions for generating invoices for the plugin file. utils.py import os import re from datetime import datetime from decimal import Decimal import pytz from django.conf import settings from django.template.loader import get_template from prices import Money from weasyprint import HTML # <----------- This what is emitting the error because the # package can't find the needed dependency. from ...giftcard import GiftCardEvents from ...giftcard.models import GiftCardEvent from ...invoice.models import Invoice MAX_PRODUCTS_WITH_TABLE = 3 MAX_PRODUCTS_WITHOUT_TABLE = 4 MAX_PRODUCTS_PER_PAGE = 13 def make_full_invoice_number(number=None, month=None, year=None): now = datetime.now() current_month = int(now.strftime("%m")) current_year = int(now.strftime("%Y")) month_and_year = now.strftime("%m/%Y") if month == current_month and year == current_year: new_number = (number or 0) + 1 return f"{new_number}/{month_and_year}" return f"1/{month_and_year}" def parse_invoice_dates(number: str): match = re.match(r"^(\d+)\/(\d+)\/(\d+)", number) if not match: raise ValueError("Unrecognized invoice number format") return int(match.group(1)), int(match.group(2)), int(match.group(3)) def generate_invoice_number(): last_invoice = Invoice.objects.filter(number__isnull=False).last() if not last_invoice or not last_invoice.number: return make_full_invoice_number() try: number, month, year = parse_invoice_dates(last_invoice.number) … -
I get a form object when I need want to get a form:
Views.py: from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserPostForm from django.contrib.auth.models import User def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def profile(request, username): post_form = UserPostForm() context = { 'username': username, 'post_form': post_form, } return render(request, 'users/profile.html', context) urls.py: from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path("admin/", admin.site.urls), path("", include("photoblog.urls")), path("register/", user_views.register, name="register"), path("profile/<str:username>", user_views.profile, name="profile") profile.html: {% extends 'photoblog/base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Welcome to the {{ username }} profile page</h1> <form method="POST"> {{post_form}} </form> {% endblock %} forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from photoblog.models import Post class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserPostForm(): class Meta: model = Post fields = ['title', 'author', 'content', 'date_posted'] Whenever I load up the page, I get an <users.forms.UserPostForm object at 0x7ff183aea670> when I want the actual form to show up on the page. How do I get that to work? I tried uploading UserPostForm() as a variable in the view … -
(Django CBV) Need object be attached to a user with CBV
I implemented this functionality with using FBV, but when I'm trying to use CBV, Objects were created with empty user field. views.py class BlockCreate(CreateView): model = TrainingBlock template_name = 'training_room/create_block.html' form_class = BlockForm success_url = reverse_lazy('gym') def set_user(self, form): form.instance.user = self.request.user return super(BlockCreate, self).set_user(form) models.py class TrainingBlock(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) duration = models.IntegerField(default=10) if_ended = models.BooleanField(default=False) def __str__(self): return self.name forms.py class BlockForm(forms.ModelForm): class Meta: model = TrainingBlock fields = '__all__' exclude = ['user'] -
django sql .raw filtering on a string not working
I am trying to filter on a foreign key but getting an error. Current code is: Views.py def kingmailboxcodesshow(request): lname = "King" lockbox_list = MailBoxCodes.objects.raw('SELECT * FROM mailboxcodes WHERE Address_id__contains %s',[lname]) return render(request,"users/mailboxcodesshow.html",{'MailBoxCodes':lockbox_list}) receiving this error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''King'' at line 1") I am still really new to django and python, looking at the error I am thinking i need a few less ' around the King, but I am not sure how to make that happen. I have a bunch of addresses in the Address_id and I just want to retrieve all the address with the work King in their street address. I would greatly appreciate any and all assistance. Thank you in advance. -
ImportError: cannot import name 'Random' from 'django.db.models.functions'
Well, I am trying to run my django project in new environment, I installed all of my requirements although every package is installed but it is still giving me below mentioned error. I am not sure but I am guessing it is due to version conflict of some modules. Can anyone help me out? Thanks in Advance :) I looked for existing solutions or someone who faced similar situation but no success. -
drf-yasg doesn't include the "api/" portion of the urls
I'm using drf-yasg to generate a Swagger schema, but it removes the "api/" portion of the url. schema_view = get_schema_view( openapi.Info( title="My API", default_version='v1', description="...", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="hello@mycompany.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], ) router = routers.DefaultRouter() router.register(r'spaces', SpacesViewSet, basename='spaces') urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('api/', include(router.urls)), path('api/search-options', SearchPlacesOptionsView.as_view()), ] result on /swagger As you can see for the routes from the drf router, it doesn't include the /api portion of the url. However for the regular api/search-options endpoint it removes the /api portion as well, so I don't think it has something to do with the router. -
Creating a form for each comment jquey and djang
I want for my website in the comments section, when the user clicks on the answer, an input form will be added to the bottom of the same comment, and if there is another form for other comments, they will be hidden. this is my code html and django: <li class="comment" style="margin-right: 100px;"> <div class="comment-body"> <div class="single-comment"> <div class="comment-img" style="margin-left: 50px;"> {% bs_icon 'person' size='65' %} </div> <div class="comment-inner"> <h6 class="commenter"> <a class="hover-flip-item-wrapper" href="#"> <span class="hover-flip-item"> <span data-text="{{ reply.user_name }}">{{ comment.user_name }}</span> </span> </a> </h6> <div class="comment-meta"> <div class="time-spent">آبان 23, 1401 در 12:23 بعد از ظهر</div> <div class="reply-edit"> <div class="reply"> <a class="comment-reply-link hover-flip-item-wrapper" href=""> <span class="hover-flip-item"> <span data-text="Reply" id="reply-comment">پاسخ</span> </span> </a> </div> </div> </div> <div class="comment-text"> <p>{{ comment.text_comment}}</p> </div> </div> </div> </div> <div class="comment-respond reply-form" id="{{ comment.id }}" style="margin-right: 100px;display:none;" > <h4 class="title">پاسخ شما</h4> <form action="#"> <p class="comment-notes"><span id="email-notes">آدرس ایمیل شما منتشر نخواهد شد.</span></p> <div class="row"> <div class="col-12"> <div class="form-group"> <label>پاسخ شما</label> <textarea name="message" placeholder="بنویسید ..."></textarea> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>نام <span>*</span></label> <input id="name" type="text"> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>ایمیل <span>*</span> </label> <input id="email" type="email"> </div> </div> <div class="col-lg-12"> <div class="form-submit"> <button name="submit" type="submit" id="submit" href="#" class="axil-btn btn-bg-primary w-auto">ارسال پاسخ</button> </div> </div> … -
Web Scraping refreshing in Django Project
I have to create a project with the framework django, and I have to introduce a system of web scraping with bs4. I did it, but I can’t refresh the data. I scrap the data with bs4, requests and time, them display them into my html page. But when I print the data with 3 secondes refreshing with module time, the data are refreshing. But when I display the data into my html page, they don’t actualised them. I would like to be able to scrap and display data from other website into my django app. -
Django multiple table query - convert MySQL to Django (Python) query
I need to figure out how to translate MySQL query into Django (Python) language. Any help? Basically I need to get the total from each table plus the remain total after spend. class Trip(models.Model): name = models.CharField('Name', max_length=254) class Account(models.Model): name = models.CharField('Name', max_length=254) class Wallet(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) incoming_date = models.DateField(verbose_name='Incoming Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) class Expense(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) outcome_date = models.DateField(verbose_name='Outcome Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) SELECT *, (wallet_total - expense_total) AS remain_total FROM ( SELECT account.name, SUM(wallet.total) AS wallet_total FROM account INNER JOIN wallet ON wallet.account_id = account.id WHERE wallet.trip_id=4 GROUP BY account.name ) AS wallet, ( SELECT account.name, SUM(expense.total) AS expense_total FROM account INNER JOIN expense ON expense.account_id = account.id WHERE expense.trip_id=4 GROUP BY account.name ) AS expense; -
Django and AWS S3 returns This backend doesn't support absolute paths
I am working on a Django project whereby when users register their profiles get automatically created using the signals.py. Everything works fine in the localhost, but now I want to migrate to the AWS S3 bucket before deploying my project to Heroku. After configuring my AWS settings in settings.py, I get the error NotImplementedError: This backend doesn't support absolute paths. after trying to create a superuser through the python manage.py createsuperuser command. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', null=True, blank=True) bio = models.TextField() resume= models.FileField('Upload Resumes', upload_to='uploads/resumes/', null=True, blank=True,default='resume.docx') Here is the signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() And here is my settings.py; # S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID='' AWS_SECRET_ACCESS_KEY='' AWS_STORAGE_BUCKET_NAME='' # Storages configuration AWS_S3_FILE_OVERWRITE= False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Only public read for now AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL='public-read' STATIC_URL = '/static/' Inside the s3 bucket, I have the default.jpg and resume.docx in the root folder. Any assistance will be highly appreciated. Thanks. -
How to test all Object values in a python function
I would like to test all x values in this function, without calling each x value ( x[0] ...), so a kind of x[n] or ' for all values of x'. And to list all TickerZ values in a list depending on if the x value passed the IF statement. room = str('Bingo Bango Bungo EURUSD=X') x = room.split() def Symbol(symbol): aapl = yf.Ticker(symbol) ainfo = aapl.history(period='1y') if len(ainfo) >= 40: print('yes it is a symbol') global tickerZ tickerZ = symbol new_Memory = Memory.objects.create(user=current_user, raw_message=room, date1=datemin, date2=datemax, ticker=tickerZ, command=cmd_exec) new_Memory.save() return tickerZ symb1 = Symbol(x[0]) symb2 = Symbol(x[1]) symb3 = Symbol(x[2]) symb4 = Symbol(x[3]) Code explanation: So basically, i have a string, i'm splitting it into words, which represent all x values. In this case x[0] is Bingo. I'm passing all x's into a IF statement to filter the relevant x values. I know if a x is relevant if TickerZ has a value, because the variable is defined after the filter. -
How to make Django redirect to other page?
I have an app named "works" where all my works should contain. There are cards-previews to my works. So I want them clickable and redirecting to the work that is clicked and soon shown the html file of the work. The problem is in redirecting to that work. In myapp/urls.py is the following urlpatterns = [ path("", WorksView.as_view(), name="works"), path("<slug:work_slug>/", WorkDetailView.as_view(), name="work-detail"), ] myapp/models.py class Works(models.Model): -- other attributes -- slug = models.SlugField( null=False, db_index=True, blank=False, max_length=255, unique=True, verbose_name="URL", ) def get_absolute_url(self): from django.urls import reverse return reverse("work-detail", kwargs={"work_slug": self.slug}) So what class based view should be used in myapp/views.py for WorkDetailView? I have tried View, TemplateView, RedirectView, but neither of them work properly that I want to. The last try was that: class WorkDetailView(View): def get(self, request, *args, **kwargs): work = get_object_or_404( Works, slug=kwargs["work_slug"] ) print(work.get_absolute_url()) return render(request, work.get_absolute_url(), {"works_data": work}) The work.get_absolute_url works good, but Django cant find template My project folder: But when I change the return string to return render(request, f"{work.get_absolute_url()[1:-1]}.html", {"work": work}) it works and prints "works/not-found/", but I dont think that it is the correct way So how can I do it right? The last try was to make that using View but Django … -
Django signals / notification system
Is it a good aproach to use Django signals to implement email notification system? I have CustomUser model related with CustomUserPreferences planned as follows: class CustomUserPreferences(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, default=None, on_delete = models.CASCADE, primary_key = True) lesson_notification = models.BooleanField(default=True) journal_notification = models.BooleanField(default=False) login_notification = models.BooleanField(default=False) excercise_notification = models.BooleanField(default=False) homework_notification = models.BooleanField(default=True) class CustomUser(AbstractUser): ... email = models.EmailField(_('email address'), unique=True) preferences = models.OneToOneField(CustomUserPreferences, null = True ,default=None, on_delete = models.CASCADE) students = models.ManyToManyField(to = 'self', related_name = 'teachers', symmetrical = False, blank = True) Whenever a new object of lets say Lesson is created I want to send an email to the user and that's fine - becaouse it won't overload any server. The question is: will it pay off to use signals for a list of users that contains lets say 100s or 1000s of users? I'm afraid it will slow down the whole application. Is there any other "clear and elegant" way to do this? Django docs advices not to use signals whenever it's possible. -
api call method and viewset
I try to create a api call: class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGgroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer_class()(mainGroups) return Response(serializer.data) serializer: class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] So the main url works: http://127.0.0.1:8000/djangoadmin/groups/ But if I go to: http://127.0.0.1:8000/djangoadmin/groups/maingGroups/ I get this error: { "detail": "Not found." } urls.py: router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] and urls.py of admin looks: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("djangoadmin/", include('djangoadmin.urls')), path("admin/", admin.site.urls), ] Question: how to create api method in main url? -
I have created a django ModelForm that is not showing up in my html template, I am trying to determine why that code is not rendering my form?
models.py from django.db import models # Create your models here. class Subscriber(models.Model): """A subscriber Model""" email = models.CharField(max_length=255, blank=False, null=False, help_text="Subscriber Email Address", unique=True) full_name = models.CharField(max_length=100, blank=False, null=False, help_text="First and Last Name") class Meta: verbose_name = "Subscriber" verbose_name_plural = "Subscribers" forms.py from django.forms import ModelForm from .models import Subscriber class SubscriberForm(ModelForm): class Meta: model = Subscriber fields = ["email", "full_name"] views.py from django.shortcuts import render from .forms import SubscriberForm from django.http import HttpResponseRedirect from django.contrib import messages # Create your views here. def subscriber(request): if request.method == "POST": subscriber_form = SubscriberForm(request.POST or None) if subscriber_form.is_valid(): subscriber_form.save() messages.success(request, "") return HttpResponseRedirect("/") else: subscriber_form = SubscriberForm() context = { "form_subscriber": subscriber_form } return render(request, "subscriber/subscriber_form.html", context) subscriber_form.html {% block content %} <div> <form method="POST"> {% csrf_token %} {{ subscriber_form.as_ul }} <input type="submit" value="Submit"> </form> </div> {% endblock %} Only my submit button is publishing, however the form is never showing up for me. I have followed the django docs exactly and still am not getting any good results. -
how to call a function as a context in django
class User(AbstractUser): GENDER_STATUS = ( ('M', 'Male'), ('F', 'Female') ) address = models.TextField(null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) def get_full_name(self): return f'{self.first_name} {self.last_name}' i declare a function get_full_name and then i want too call it in my view and show it in my template. this is my view from django.shortcuts import render from accounts.models import User def about_us(request): fullname = User.get_full_name context = { 'fullname': fullname } return render(request, 'about_us.html', context=context) and this is my template as you can see i used a loop for my context <div class="container"> <div class="d-flex flex-wrap justify-content-around"> {% for foo in fullname %} <p>{{ foo }}</p> {% endfor %} </div> </div> but i cant get the get_full_name parameters in my template as value too show. i'll be more than happy if sombodey help me. THANK YOU!