Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO 3.2 wont load images from declared media folder 404 error
#urs.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #setting.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' #model images = models.ImageField(upload_to='BonusVilla/image/', blank=True) #tempalte {%for i in images%} <img src="{{ i.images.url }}" /> {%endfor%} #the browser it renders this <img src="/media/BonusVilla/image/apple_3H8ByYb.jpg"> -
Django: Eccomerce website. When I proceed the checkout it's saving the order if person is not logged in, but when it's not AnonymousUser error
I am working on ecommerce website and it's time to make checkout. In my website, when to order product without an account it's saving the order, but if it's with an account, it's going to another page, but not erasing a cart and isn't saving the order. What is the problem? Can you please help me to solve this problem. It's not working only when client is logged in an account. views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) tel = data['shipping']['number'], address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id order.tel= tel order.address=address order.city=city order.state=state if total == order.get_cart_total: order.complete = False order.save() return JsonResponse('Payment submitted..', safe=False) html <form class="form" method="POST" action="#" id="form"> <div class="row"> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Имя<span>*</span></label> <div> <input type="text" name="name" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Фамилия<span>*</span></label><div> <input type="text" name="surname" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Email<span>*</span></label><div> <input type="email" name="email" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info shipping-info"> <div class="form-group"> <label>Номер телефона<span>*</span></label><div> <input type="number" name="number" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" … -
What is used where and how in Django 2022?
!Complete Beginner! I went into Django with the background of building Sass web apps. CSS, HTML, Django and you have something working, I thought. After some weeks now you also have the basics, but there you quickly reach your limits if you want to create "useful/modern" web apps Today I was thrown off with terms like "Ajax XMLHttpRequest needed" "django without javascript does not work" htmx? or javascript? Or both? json files, is this like a model in django? Random people talking about outdated Django features I have enough time to deal with everything, but for that I would have to know with what. Can someone explain to me, using a "modern" site like Twitter/YouTube/a web app, what is needed where now? Django tutorials may tell you how to create 1000 forms and create a To Do list, but that's as far as it goes. Down voting questions on stackoverflow, keep it. You knew everything from the beginning, you are so successful ^^ -
Uncaught SyntaxError: redeclaration of const check
I am working in django and i have written a simple code for dark and light theme, it is working perfectly, but when i inspect my page, it shows an error 'Uncaught SyntaxError: redeclaration of const check', so this is my js code, please tell me how i get rid of this error. const check=document.getElementById("check") if (localStorage.getItem('darkMode')===null){ localStorage.setItem('darkMode', "false"); } const link = document.createElement('link'); link.rel = 'stylesheet'; document.getElementsByTagName('HEAD')[0].appendChild(link); checkStatus() function checkStatus(){ if (localStorage.getItem('darkMode')==="true"){ check.checked = true; link.href = './static/css/modes/dark-mode.css'; }else{ check.checked = false; link.href = './static/css/modes/light-mode.css'; } } function changeStatus(){ if (localStorage.getItem('darkMode')==="true"){ localStorage.setItem('darkMode', "false"); link.href = './static/css/modes/light-mode.css'; } else{ localStorage.setItem('darkMode', "true"); link.href = './static/css/modes/dark-mode.css'; } } please help me -
How to change the chart data in bootstrap template for Django Project
I'm using the "start bootstrap" template for my Django project. I want to edit my own data in the sample chart. I think I need to change it in the "chart-pie-demo.js" file. However, the chart doesn't change when I edit any data. The code that is related to my chart in the "chart.html" is: <!-- Donut Chart --> <div class="col-xl-4 col-lg-5"> <div class="card shadow mb-4"> <!-- Card Header - Dropdown --> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Donut Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-pie pt-4"> <canvas id="myPieChart"></canvas> </div> <hr>Styling for the donut chart can be found in the <code>/js/demo/chart-pie-demo.js</code> file. </div> </div> </div> <!-- Page level plugins --> <script src="{% static 'Chart.min.js' %}"></script> <!-- Page level custom scripts --> <script src="{% static 'chart-area-demo.js' %}"></script> <script src="{% static 'chart-pie-demo.js' %}"></script> <script src="{% static 'chart-bar-demo.js' %}"></script> My "chart-pie-demo.js" which is under "static" is: var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Direct", "Referral", "Social"], datasets: [{ data: [55, 30, 15], backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, … -
How do i query children fields belonging to a parent class. Django
Navigation menu in real site do have dropdown menu when neccessary. That's exactly what i want to achieve here. The NavMenu class is the title you see in NavBar i.e Services. The Item class is the submenu under a NavMenu i.e List of services that appear under the service tab In my code i want to call the submenu that are under a particular title i.e Submenus under Service My Model: class NavMenu(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Item(models.Model): category = models.ForeignKey(NavMenu, on_delete=models.CASCADE) title = models.CharField(max_length=50) def __str__(self): return self.title class ItemMedia(models.Model): category = models.ForeignKey(NavMenu, on_delete=models.CASCADE, null=True) menu_item_p = models.ImageField() description = models.CharField(max_length=100) My views.py: class IndexPageView(TemplateView): model = NavMenu, Item, ItemMedia, template_name = 'index.html' extra_context = { 'navmenu': NavMenu.objects.order_by('title'), 'submenu': NavMenu.category_set.all(), 'media_items': NavMenu.category_set.all(), } -
How to perform 'SELECT a or b < c FROM Table' on Django QuerySet?
I have the following model: class DiscountCoupon(models.Model): is_used = models.BooleanField(default=False) expiration_date = models.DateField() def is_available(self): if self.used or self.expiration_date <= date.today(): return False return True Instead of calling the is_available method iterating through a QuerySet, I want to do this operation into the QuerySet to perform better, like this: SELECT (used OR (expiration_date < Now())) AS is_available FROM randomapp_discountcoupon; Is this possible? -
Image Upload from a different modal's view
So I have two models and in the update method of the first modal' viewset,(using model viewset) I'm trying to add an image to my second model but facing issues. def update(self, request, *args, **kwargs): data = request.data instance = self.get_object() serializer = self.get_serializer(instance, data=data) # partial=partial) if serializer.is_valid(raise_exception=True): # get image from recieved data # profileImage = data["profileImage"] profileImage = request.data.get("profileImage", None) ## update first modal self.perform_update(serializer) ## add an image to second modal, secondModel.objects.filter(user=request.user.id).update(profileImage=profileImage) I can see the url of image getting added but there is no image in the media directory. Actually I'm updating other field also, thats working fine but having issue in this image field. While direct updating in the views of the second models there is no issue. Sending formData from the frontend. So is there a different way dealing with file objects ? -
Add user's email when sending email in Django Rest Framework
I've got this working serializer: class ReportAnswerSerializer(serializers.ModelSerializer): complain_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = ModerateAnswer fields = ('answer', 'moderate_reason', 'moderate_comment', 'complain_by') extra_kwargs = {'moderate_reason': {'required': True}} def create(self, validated_data): instance = super(ReportAnswerSerializer, self).create(validated_data) send_mail( 'Dziękujemy za zgłoszenie', 'Zgłosiłeś odpowiedź: {}. Team Deor zajmie się teraz tą wiadomością'.format(instance.answer), 'info@deor.pl', [mail@mail.com], fail_silently=False, ) return instance But i don't want to statically send email. Everytime a user reports an answer i want to send them a mail "Thanks for reporting the answer" But i dont know how to format the [mail@mail.com] dynamically. I am using a custom user model. class CustomUser(AbstractUser): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) slug = models.SlugField(max_length=30, unique=True, null=True, blank=True, editable=False) email = models.EmailField(blank=False, unique=True) number_of_points = models.IntegerField(default=0) facebook_profile = models.CharField(max_length=128, null=True, blank=True) instagram_profile = models.CharField(max_length=128, null=True, blank=True) twitter_profile = models.CharField(max_length=128, null=True, blank=True) package = models.CharField(max_length=128, null=False, default='L') paid_till = models.DateField(null=True, blank=True) package_downgraded = models.CharField(max_length=128, null=True, blank=True) sex = models.CharField(max_length=128, null=True, blank=True) location = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) badges = models.ManyToManyField('users.Badge', blank=True) Do you have any idea how to do it? -
similarity word with Trigram
how i make a function for word similarity in search result. For example if i write in my search form "ugo" or "hugo". i try this : ("contenue" is my txt files in db postgresql) views.py class SearchResultsList(ListView): ... ... ... def get_queryset(self): query = self.request.GET.get("q") vector_column = SearchVector("contenue", weight="A", config='french') search_query = SearchQuery(query) search_headline = SearchHeadline("contenue", search_query) result1 = Q(contenue__search=query) result2 = Q(SearchVector("contenue")) return Actes.objects.filter(result1).annotate(headline=search_headline) .annotate(similarity=TrigramSimilarity('contenue', query),) .filter(similarity__gte=0.6).order_by('-similarity') when i don't add trigram i have a result but not work if i write "ugo" instead of "hugo" or "higo" instead of "hugo". Thank and sorry for my bad english -
mock django.core.mail.send_mail in another function
I want to mock django's send_mail() so that it throws an Exception. My approach is as below, but mails are still being sent, and no Exceptions being thrown. It works if I call send_mail() directly within the context manager, but not if I call a function that imports and then uses send_mail() # test.py import handle_alerts from unittest import mock class MailTest(TestCase): def test_handle_alerts(self): with mock.patch("django.core.mail.send_mail") as mocked_mail: mocked_mail.side_effect = Exception("OH NOES") handle_alerts() # ends up using send_mail # handle_alerts.py from django.core.mail import send_mail def handle_alerts(): send_mail(....) # valid call goes here -
Method not allowed when I do a get request from flutter web to Django server( both in same host)
I've hosted my Django backend server on VPS and used apache2 to run it, when I do requests from my flutter app running locally as debug it works perfectly, then I hosted the flutter web application in the same server under Django itself by creating a directory inside Django root and added a redirect to it from the Django URLs. I've used this method to add flutter web to Django it works normally and opened the flutter app but when the application sends a request to the django it saves this error in the apcahe2 errors.log [Fri Feb 04 14:06:08.154190 2022] [wsgi:error] [pid 17002:tid 140068315830016] [remote 156.194.221.19:59776] Method Not Allowed: /static-pages/api/on_boarding/ -
Python dictionary in jQuery
I've an ajax call in my html of a django application. How can I handle the returned object in javaScript if my python backend returns a list that includes python dictionary: html: $.ajax({ type: "GET", url: '/api/check_variable/?name='+$("#foo").val()+'&stat='+stat_id, data: "check", success: function(response){ alert("response[2]); } )} urls.py: urlpatterns = [ path("check_variable/", views.api_for_class_checking, name="check_variable"), ] views.py: def api_for_class_checking(request, **kwargs): return ['id1', 'id2',{'filabel': 'label F', 'svlabel': 'labelS', 'enlabel': 'labelEn'}] In this case my html page alerts just Object as response[2]. How can I get the attributes of the returned object, like the value of 'filabel' e.g. ? -
Create a new model in Django linked tothe User table
I'm new to Django and I've correctly created my first web app where I can register and login as an user. I'm using the standard from django.contrib.auth.models import User and UserCreationFormto manage this thing. Now, I would like to create a new table in the database to add new fields to the user. I'm already using the standard one such as email, first name, second name, email, username, etc but I would like to extend it by adding the possibility to store the latest time the email has been changed and other info. All those info are not added via the form but are computed by the backend (for instance, every time I want to edit my email on my profile, the relative field on my new table, linked to my profile, change value) To do that I have added on my models.py file the current code from django.db import models from django.contrib.auth.models import User class UserAddInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_time_email_change = models.TimeField('Last email changed', auto_now_add=True, blank=True) def __str__(self): return self.user.username And on my admin.py from django.contrib import admin from .models import UserAddInformation admin.site.register(UserAddInformation) The form to edit the email and the view can be found below forms.py class … -
CSS overflow not working with flex-grow or width/height in per cent
I am facing a problem that I don't really understand with the overflow of CSS. css: * { margin: 0; padding: 0; } html { height: 100%; } body { display: flex; flex-direction: column; font-weight: 400; font-family: 'Arial'; } .simulations { display: flex; width: 80%; margin: auto; padding: 5px 10px; margin-top: 50px; border-radius: 20px; box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; } .waiting-list { flex-grow: 1; } .waiting-list h3 { text-align: center; } .waiting-list .list { display: flex; margin-top: 10px; padding: 0px 5px 5px 5px; overflow-x: scroll; } .waiting-list .list .element { width: 200px; text-align: center; border-radius: 20px; border: 2px solid black; } .button { display: flex; margin-left: 10px; } .button img { margin: auto; width: 30px; cursor: pointer; } HTML (I am using Django): {% load static %} <!DOCTYPE html> <html> <head> <title>Test</title> <link rel="stylesheet" type="text/css" href="{% static 'css/test.css' %}"> </head> <body> <div class="simulations"> <div class="waiting-list"> <h3>Waiting list</h3> <div class="list"> {% for i in "x"|rjust:"10" %} <div> <div class="element"> <h4>Title</h4> <p>size</p> </div> </div> {% endfor %} </div> </div> <div class="button"> <img src="https://img.icons8.com/external-prettycons-lineal-prettycons/49/000000/external-enter-essentials-prettycons-lineal-prettycons.png"/> </div> </div> </body> </html> Visual of this code As you can see on the picture, the waiting list class is going over the button instead of … -
UserManager.create_user() missing 1 required positional argument: 'username' error while logging in with python-social-auth
I have created a custom AbstractUser user model and I am using python-social-auth to log in the user via Steam. But when I try to log in the user I will get this error. I have tried adding username to REQUIRED_FIELDS but both ways I get the same error. models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, unique=True) steam_name = models.CharField(max_length=32, blank=True) steam_id = models.CharField(max_length=17, unique=True, blank=True, null=True) extra_data = models.TextField(null=True) is_active = models.BooleanField(default=True, db_column='status') is_staff = models.BooleanField(default=False, db_column='isstaff') is_superuser = models.BooleanField(default=False, db_column='issuperuser') USERNAME_FIELD = "name" REQUIRED_FIELDS = ["username"] pipeline.py from .models import CustomUser def save_profile(backend, user, details, response, *args, **kwargs): CustomUser.objects.get_or_create( steam_name = user, steam_id = details['player']['steamid'], extra_data = details['player'], ) settings.py AUTH_USER_MODEL = 'main.CustomUser' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'main.pipeline.save_profile', ) -
Django/authentification: how to customize change password template (to get form-horizontal class for instance)?
I want to be customize password_change.html template to get form-horizontal class. To do this, in my owns views/forms I use django-crispy-form. But If I want to use django-crispy-form for authentification templates, I need to override PasswordChangeView and PasswordChangeForm right? Is there an easiest way to get this result and customize all authentification backend templates? thank in advance -
How can I send data to excel file/invoice from django models?
I have a Django model for different companies. When someone does not turn up for work at those companies they call our agency and we send an agent to cover that shift. They then have the manager at that company approve the digital timesheet and the values are saved in a Django model called timesheets. enter image description here My question: I want to implement payroll for over 50 users. Proposed solutions: Do I generate CSV files with the data from the model then pass the data from CSV to an excel file, or is there a better more elegant solution to this problem. PS: Please forgive my verbiage. -
Django Custom Field - Boolean -> CHAR YN
Due to a legacy system I'm trying to get Django boolean fields to save in the dB as a simple 'Y' or 'N' char field (VARCHAR not supported in said legacy system). Using a django custom field I have it working but struggling to get Django admin to work with the field. class BooleanYN(models.BooleanField): """ We need to save boolean variables as CHAR Y/N """ description = _("Boolean field stored as Y or N in the dB") def from_db_value(self, value, expression, connection): if value in ('Y', 'y'): return True if value in ('N', 'n'): return True raise ValidationError(_(f"Value in dB is not Y or N - {value}")) def get_prep_value(self, value): if value is True: return 'Y' if value is False: return 'N' return value def db_type(self, connection): return char(1) In Django admin, single record view + list view, the checkbox widget is always flagged as true even though 'N' is correctly saved in the dB and "to_python" is correctly being passed 'False' or 'True' as the value when its called by the modelform code depending on whether 'Y' or 'N' in the dB. Any help appreciated! -
Set timer for a Django view execution
I'm struggling trying to prevent a Django view from being executed more than once within an hour period. In other words, if the function runs at 15:00, all future requests should be ignored until 17:00 when it's allowed to run once again. Tried with a timer, but it does get reset every time the view is called. Maybe someone can point me in the right direction? Thanks!!! import threading as th def hello(): print("hello, world") def webhook(request): tm = th.Timer(3600, hello) if request.method == 'POST' and not tm.is_alive(): tm.start() code_to.ecexute() return HttpResponse("Webhook received!") -
Override Django Abstract Admin Model
I've the model below: class UrlsModel(TimeManager): name = models.CharField(max_length=70) url = models.URLField() def __str__(self): return self.name class Meta: abstract = True and its relative admin model: class UrlsModelAdmin(admin.ModelAdmin): list_display = ["name", "url"] There is a model that add a column to UrlsModel and now I need to add this column in list_display. How I can do this? -
How can i auto fill my field and make it non editable in django admin site
I need to autopopulate a field in admin site and make foreignkey field non editable with current_user : views.py: def my_view(request): obj = model.objects.first() response = HttpResponse(file, content_type=' application/vnd.ms-excel', ) return response urls.py: path('temo/fill',views.my_view,name = 'my-view') models.py class Model(BaseModel, SingletonModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator([''])] ) person_uploaded = models.ForeignKey( 'somemodel', related_name='s', null=True, on_delete=models.SET_NULL, ) admin.py: @admin.register(tTemplate) class TemplateAdmin(admin.ModelAdmin): list_display = ('file','person_uploaded',) readonly_fields = ('person_uploaded',) def save(self, request): if not self.id: self.person_uploaded = request.user super().save() -
How to count quantity with distinct?
I have 2 templates, one representing a product sheet and the other one an actual product in stock. The stock can have several products that have the same product sheet. Example: I can have a product record "Water bottle", and several "water bottle" in the stock. My models: class Stock(models.Model): machine = models.ForeignKey( "machine.Machine", verbose_name=_("machine"), related_name="machine_stock", on_delete=models.CASCADE ) product = models.ForeignKey( "client.Product", verbose_name=_("product"), related_name="product_stock", on_delete=models.CASCADE ) epc = models.CharField(_("EPC"), max_length=80) dlc = models.DateField(_("DLC")) class Product(models.Model): name = models.CharField(_('Name'), max_length=255) [...] I want to retrieve the products in stock sorted by both DLC and name. On my frontend I want to display a table with for each row: the name of the product the dlc the number of products with this name and this dlc Example: If I have 2 product sheets (Product Model) : water bottle bottle of coca cola and I have 5 products in stock (Stock Model) : 2 bottles of water whose dlc is 02/04/2022 2 bottles of cola whose dlc is the 02/04/2022 1 bottle of cola whose dlc is 03/04/2022 I want to display 3 lines in my table: Quantity | Name | DLC 2 | water | 02/04/2022 2 | cola | 02/04/2022 1 … -
Custom Django signup/login form
I have designed signup and login forms(HTML/CSS). How can I make them work in my Django project? Should I use something like allauth and put my design on already made forms() or create my own forms and views? In books that I read author always used auth or allauth apps.There wasn't any explanation on how to implement your own custom forms. Could you help me? My Login form: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/login.css' %}"> {% block title %}<title>Login</title>{% endblock title %} </head> {% block content %} <body> <div id="card"> <div id="card-content"> <div id="card-title"> <h2>LOGIN</h2> <div class="underline-title"></div> </div> <form method="post" class="form" action="{% url 'login' %}" > {% csrf_token %} <label for="user-email" style="padding-top:13px"> &nbsp;Email </label> <input id="user-email" class="form-content" type="email" name="email" autocomplete="on" required /> <div class="form-border"></div> <label for="user-password" style="padding-top:22px">&nbsp;Password </label> <input id="user-password" class="form-content" type="password" name="password" required /> <div class="form-border"></div> <a href="#"> <legend id="forgot-pass">Forgot password?</legend> </a> <a href="{% url 'home' %}"> <input id="submit-btn" type="submit" name="submit" value="LOGIN" /> </a> <a href="#" id="signup">Don't have account yet?</a> </form> </div> </div> </body> {% endblock content %} </html> -
<HttpResponseNotFound status_code=404, "text/html"> in django-test
I'm new to unit testing and I've been trying to test a GET method of the card game that I've built. My TestCase is the following: def test_rooms(self): c = APIClient() room_id = PokerRoom.objects.get(name='planning').id request = c.get('http://127.0.0.1:8000/room/{}'.format(room_id)) print(request) The id is a UUID that's why I'm using the room_id method. My url: path('room/<int:pk>', room), where room is a @api_view(['GET']) method and pk is the id of the room. But when I try to test it, an error occurs: <HttpResponseNotFound status_code=404, "text/html"> Checked if the room exists in the test database and it exists, now I don't know what is happening. Can someone help me?