Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing objects in models django
i'm trying to show all the data that i have saved in my admin page to users visiting my website . this is what i have in models: class Movie(models.Model): name = models.CharField(max_length=255) genre = models.CharField(max_length=255) date_of_release=models.CharField(max_length=255) IMDb=models.CharField(max_length=250) cast=models.TextField(max_length=500,null=True) summary=models.TextField(max_length=500,null=True) image=models.TextField(max_length=500,null=True) def __str__(self): return self.name i want the movie name to be shown to users and when they click on the name it takes them to another page that contain all the information about the movie . i'd appreciate it if you have any idea how to do that. -
Django OneToOneField and queryset
counter_app: class Logs(models.Model): name = models.CharField(max_length=250) number = models.PositiveIntegerField(default=0) ... mail_app: class Logs(models.Model): subject = models.CharField(max_length=250) counter = models.OneToOneField(Logs, on_delete=models.CASCADE) ... def save(self, *args, **kwargs): c = Logs(name=self.subject, number=0) c.save() self.counter = c super(Mail, self).save() How can I get access to the "c" object? How should I connect it with 'counter' field? And also I need it's 'number' field to be used further. Many thanks in advance! -
how to combine to class base views into one class base view?
I have to class base views. And I want to combine them together to just a single one class base view: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): pass class ReadingExcel(View): def get(self, request): form = ExcelForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): pass and then I want to two above classes combined in this class: class readingPDFAndExcelForm: reading_file = ReadingFile() reading_file.get() reading_file.post reading_excel = ReadingExcel() reading_file.get() reading_excel() Or is there a other solution for? -
Django how to shuffle a queryset without speed lose
I want to shuffle a list of objects without losing any speed in terms of optimization and performance speed. let's say I have the following query. related_products = Announcement.objects.filter(category=category).exclude(id=announcement.id) pythonically, i would import the random module and then random.shuffle(related_products). But I am not sure if it will store something in the memory on my view or use some CPU speed or whatever terminology I don't know. So I wonder what's the best way to make it optimized. Thanks! -
Good practice to use a single update view function for multiple tasks?
I was wondering whether it is considered DRY and good practice to aggregate many small actions such as updating first name, last name, email, etc... using the same update method? First, I thought that it was a good idea because my validation is model based but right now I became septic due to the fact that my ability to custom the http response is greatly impaired. I attach my case to the question. Thanks class Update_Mixin(ModelViewSet): @action(detail=False, methods=["patch"], url_path="update_sdata") def update_few_things(self, request): WHAT_TO_UPD = ('bio', 'user__first_name', 'user__last_name', 'user__email', 'user__phone_number', 'user__gender') usr_profile = self.get_object() serializer = self.serializer_class( instance=usr_profile, data=request.data, context=self.get_serializer_context(), fields=WHAT_TO_UPD, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=204) -
How to dynamically calculate field using a function and order by that calculated field?
The context is the following: I have a model of products. And i need to make a queryset on products calculating a new field compatibility that is not in the model because i need to dynamically calculate it based on the user that makes the request, and finally I need to order the queryset based on this new field. I was trying to do something like this using annotate but since the logic to calculate the compatibility is kinda complex and for that i need to know some m2m of the current product i can't call a function inside of Value. qs = MyModel.objects.all().annotate(compatibility=Value(my_func_to_calc_compatibility(), output_field=FloatField())).order_by('compatibility') Is there another way of doing this? Do you have any ideas on how to achieve this? -
onclick function is running only once
I am using an edit button to edit the posts but when I am clicking the button the onclick function executes and it works perfectly like it edits the post and updates the post content(not from backend). But the problem is when I click the edit button again the onclick function is not running. My HTML code :- <div class="post"> <b><a href="{% url 'profile' post.author.id %}">{{post.author}}</a></b> <input type="hidden" name="postid" value={{post.id}}> <!-- <br><br> --> <p>{{post.content}}</p> {% csrf_token %} <textarea name="edit_content" id="edit_content" cols="50" rows="5"></textarea> {% if user.is_authenticated %} {% if post.author == user %} <button class="edit" onclick="edit(this)">Edit</button> {% endif %} {% endif %} <p><small class="text-muted">{{post.created_on}}</small></p> Here textarea display is set to 'none'. My javascript code :- function edit(ele){ var parent = ele.parentNode; console.log(ele.parentNode); var post = parent.querySelector('p'); var textarea = parent.querySelector('textarea'); var id = parent.querySelector('input'); post.style.display = 'none'; textarea.style.display = 'block'; ele.innerHTML = "Save"; ele.id = "save"; ele.disabled = true; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; textarea.onkeyup = () => { if( textarea.value.length > 0){ ele.disabled = false; } else{ ele.disabled = true; } } var save = document.getElementById('save'); save.onclick = () => { fetch("http://127.0.0.1:8000/edit", { method : "PUT", headers: {'X-CSRFToken': csrftoken}, body : JSON.stringify({ "postdata" : textarea.value, "id" : id.value }) }).then(() => … -
How do I call a function inside another function from different files in django and display its objects on the frontend?
Please, can anyone help me out. I am trying to call a function I defined in my views.py under food_app into another application in my project. after calling it, it works but I have a problem in reading out the function objects on my html template. it usually displays "₦<HttpResponse status_code=200, "text/html; charset=utf-8">" But the objects prints out on the terminal after when printed. This is the first function defined views.py #food_app def price_in_packs(request): total_price1 = "" total_price2 = "" total_price3 = "" total_price4 = "" total_price5 = "" total_price6 = "" total_price7 = "" total_price8 = "" total_price9 = "" total_price10 = "" total_price11 = "" total_price12 = "" price_pack_box1 = "" price_pack_box2 = "" price_pack_box3 = "" price_pack_box4 = "" price_pack_box5 = "" price_pack_box6 = "" price_pack_box7 = "" price_pack_box8 = "" price_pack_box9 = "" price_pack_box10 = "" price_pack_box11 = "" price_pack_box12 = "" food = "" food_price = "" #try and except is used here to avoid a null or empty value input by the user. A user can forget to input a price in pack value, which can break the code. if request.method == "POST": if request.POST["form"] == "form1": try: price_pack_box1 = int(request.POST.get("price1")) food = Food.objects.get(pk=1) … -
Is it possible to apply list_filters for parent's object's fields in django?
I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp. One solution would be to create a new DateTimeField in model B, but then I would store redundant information. How can I do that with Django? For example: #models.py class A(models.Model): timestamp = models.DateTimeField(null=True) class B(models.Model): key_to_a = models.ForeignKey(DjangoPage, on_delete=models.CASCADE, null=True) ########## #admin.py class BAdmin(admin.ModelAdmin): def german_timestamp(self, B): return B.key_to_a.timestamp.strftime('%d-%m-%Y %H:%M:%S') german_timestamp.short_description = "timestamp" list_display = ("german_timestamp") list_filter = ("german_timestamp") #This breaks my code as there is no field called "german_timestamp" -
Computing difference between two datefields in Django Model
I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost. models.py class Booking(models.Model): """Stores the bookings, for example when it was made, the booking date, and the car ID.""" # Unique ID for this booking. start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True) Most answers recommend extracting the days function (using start_date.day) but that doesn't work. If a booking starts on November 30, and ends on December 2, the function will return 28 days because it subtracts the integers alone. Using simple addition and subtraction: duration = end_date - start_date returns an error: TypeError: Unsupported Operand type(s) for -: 'DateField' and 'DateField' I've tried using a function nested within the model, which subtracts each day from end_date until it reaches start_date: def get_total_days(self): """Computes total number of days car will be rented from with a basic While loop.""" # Create separate instances of start and end day so as not to tamper with db values. start_day = self.start_date end_day = self.end_date days = 0 while end_day > start_day: days += 1 end_day -= 1 … -
How to add godot html5 game to my django website
I'm creating a website with django where users can play games, I already made the game on godot and exported to html5 but I don't know how to add the game to the website (I also don't know if its possible which I think it is). I am trying to achieve something where I can always add new games and their names through the admin panel. I not sure if I,m supposed to ask a question this short but I'm very new to python and django so I don't know what to do. -
Filter TreeNode children by parent
How i can order my queryset, by category_views field in treenode model I tried with ordering = ["category_stats__category_views"] (on settings "DEFAULT_FILTER_BACKENDS" configured with "rest_framework.filters.OrderingFilter") but it's, not working # category models.py from tree_queries.models import TreeNode class Category(TreeNode) foo = models.CharFiled() bar = models.CharField() class CategoryStats(models.Model) category = models.ForeingKey(Category, related_name="category_stats") category_views = models.IntegerField() # category views.py class CategoryViews(FrontEndListView): serializer_class = serializers.CategoryListSerializer # ordering = ["category_stats__category_views"] lookup_field = "id" def get_queryset(self): queryset = models.Category.objects.filter(parent_id=self.kwargs.get("id")) for item in queryset: return item.children.all()#.order_by("category_stats__category_views") -
Snowflake sample database tables are retrieved instead of my private database-Django-snowflake package
I have specified correct database config variable with all the required credentials of my local database that is hosted,but when I am trying to auto generate models for my tables from inspectdb command,I am receiving only SNOW_FLAKE_SAMPLE schema tables into my models file Please provide me a solution I tried using options key which is specified on django-snowflake package description but receiving same tables from snowflake_sample_database schema -
Random color selection from list in django
I have a list of colors in models like: COLOR_CODE = ( ('bg1', '#8AD7E0'), ('bg2', '#E0BD75'), ('bg3', '#EAC2AC'), ('bg4', '#C0AFDB'), ('bg5', '#96B2E0'), ('bg6', '#8BE0B0'), ('bg7', '#D2A1E0'), ('bg8', '#BCE080'), ) i need to use them in serializers, how can i do that? I am very new to django and i tried codes like ''.join([random.choice(chars) for c in range (10)]) the above was for random choice for passwords -
Django data was not brought to heroku
I have Django apps, which include users and posts models. The apps work perfectly at local following making migrations and migrating. I tried two different ways to deploy the apps to Heroku. First, using Heroku Git, the apps works on Heroku the same as at local. When using GitHub, however, all data were not brought to Heroku. I tried to run "python manage.py makemigrations" and "python manage.py migrate", but the data from local was not brought still. I would really appreciate it if you could please explain and help with the issue using GitHub. Thank you -
Javascript doesn't execute when the html is called by a hx-get
I have the following html's that i load in a Django app: pie_chart.html {% load i18n %} <div id="chartcontainer" > <div style= "width: 400px;" "height: 400px;"> <canvas id="pie-chart"></canvas> <b>Balance: </b> {{balance}}<br> </div> <div> <h5>Detail group: <select name="group" id="group" hx-get="groupdetail/" hx-trigger="click changed delay:1s" hx-target="#groupchart" hx-include="[name='year']" hx-swap="innerHTML" >} {% for l in labels %} {% if l == groupcode %} <option value={{l}} selected>{{l}}</option> {% else %} <option value={{l}}>{{l}}</option> {% endif %} {% endfor %} </select> </h5> </div> <div id=groupchart> {% include 'bar_chart.html' %} </div> </div> <script> var config_pie = { type: 'pie', data: { datasets: [{ data: {{ data|safe }}, backgroundColor: {{ backgroundcolor|safe }}, label: 'Amount_EUR', }], labels: {{ labels|safe }} }, options: { responsive: true } }; var ctx_pie = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx_pie, config_pie); </script> bar_chart.html {% load i18n %} <div> <div style= "width: 400px;" "height: 400px;"> <canvas id="group-chart"></canvas> <b>Balance: </b> {{groupbalance|safe}} <br> <p id="data"> her should com the config_bar var</p> </div> </div> <script> var config_bar = { type: 'bar', data: { datasets: [{ data: {{ groupdata|safe }}, backgroundColor: {{ backgroundcolor|safe }}, label: 'Amount_EUR', }], labels: {{ grouplabels|safe }} }, options: { indexAxis: 'y', responsive: true } }; var ctx_bar = document.getElementById('group-chart').getContext('2d'); window.myBar = new Chart(ctx_bar, config_bar); document.getElementById("data").innerHTML = … -
How to generate an automatic incrementing custom id to created forms in django?
I'm working on a bug tracker system and I would like to generate automatic incrementing id for eg: BUG001, BUG002, BUG003 etc. Also I need to create IDs like this for the existing ones as well. How can I establish this mechanism? models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30, label="Fixed by/Assigned to") phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] ` Generate automatic incrementing custom ids. -
How to persist data when uploading content to texbox?
Ok, I am really stuck with this. And I am searched a lot for it. But I can't figure out how to deal with the following issue. The situation is as follows: I have two submit buttons and two forms. And I want to upload a file independent of the other upload file. Because I have one upload for PDF and the other one for uploading a Excel file. But the problem now is when a user upload a PDF file and the content displays in a text box and the user choose for uploading a Excel file in the other textbox. The content of the PDF file will be erased. Because of refresh. So this is the template stuff: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </form> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="" cols="65" rows="25"> {{content_excel}}</textarea> </div> </div> </form> … -
How to compare old and new field values in Django serialiazer?
Good afternoon! I have a Django model which has a many to many field. When adding or changing a record in this table, I need to perform certain actions. Because the table contains a many to many field, I can't perform model-level validation using the save method.(Correct me if I am wrong, but when i add or remove many to many field then save method on main table is not called) So I'm trying to override the save method on the serializer. def save(self, **kwargs): obj = super(PlanningExchangeRateSerializer, self).save(**kwargs) return obj Can you please tell me how to determine whether any field values have changed? -
Stripe implementation in django not redirecting to success page
I was trying to implement stripe in django and everything worked fine until i tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? Any help would be appriaceted views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) gig = get_object_or_404(Gig, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'product_data': { 'name': gig.seller, }, 'unit_amount': int(gig.price * 100), }, 'quantity': 1, } ], mode='payment', success_url='http://127.0.0.1:8000/checkout/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/checkout/failed/', ) order = OrderDetail() order.customer_email = request_data['email'] order.gig = gig order.stripe_payment_intent = checkout_session.payment_intent order.amount = int(gig.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) class PaymentSuccessView(TemplateView): template_name = "checkout/payment_success.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponse("failed") stripe.api_key = settings.STRIPE_SECRET_KEY session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(OrderDetail, stripe_payment_intent=session.payment_intent) order.has_paid = True order.save() return render(request, self.template_name) models.py from django.db import models from django.core import validators class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) gig = models.ForeignKey( to=Gig, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = … -
redirect not happening despite the request being announced in the console
I have an increment function in views.py that sends and receives data. At each data reception it increments a value and when this value reaches a threshold it redirects to a page, page2.html I have the request indicating that it accesses page2 but nothing happens. I always stay on page 1 "POST incremente HTTP/1.1" 302 0 "GET page2 HTTP/1.1" 200 1395 views.py from django.http import JsonResponse def page1(request): # load and init data request.session["nb"] = 0 return render(request, 'page1.html', context:{"nb": 0) def incremente(request): request.session["nb"] = request.session.get("nb") +1 if(request.session.get("nb") < 5): return JsonResponse({"nb": request.session.get("nb")}) else: print("goToScore") redirect("p2") def page2(request): return render(request, "page2.html") page1.html <body> <h1 id="title"> </h1> <form id="myForm" method="POST"> {% csrf_token %} <button id="submit" type="submit">Valider</button> </form> <script type="text/javascript"> document.getElementById("titre").textContent = "{{nb}}" const form = document.getElementById('myForm') form.addEventListener('submit', sendData); function sendData(event){ event.preventDefault(); const csrf = $('input[name="csrfmiddlewaretoken"]').val() $.ajax({ type: "POST", url: 'incremente', // data: { csrfmiddlewaretoken : csrf, "result": "data" }, dataType: "json", success: function (data) { document.getElementById("title").textContent = data["nb"] }, failure: function () {alert("failure");} }) } </script> </body> urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('page1', views.initQuiz, name="p1"), re_path(r'^incremente$', views.incremente), path('page2',views.page2,name="p2"), ] -
I'm Trying to create a superuser model and i'm getting the error below
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager Create your models here. class MyUserManager(BaseUserManager): # create user def create_user(self, email, phone, password=None): if not email: raise ValueError('----------EMAIL REQUIRED----------') if not phone: raise ValueError('----------PHONE NUMBER REQUIRED----------') user = self.model( email = self.normalize_email(email), phone = phone ) user.set_password(password) user.save(using=self._db) return user # create super user def create_superuser(self, email, phone, password=None): if not email: raise ValueError('----------EMAIL REQUIRED----------') if not phone: raise ValueError('----------PHONE NUMBER REQUIRED----------') user = self.create_user( email = email, phone = phone, password = password ) user.is_admin = True user.is_staff = True user.is_supersuser = True user.save(using=self._db) return user my user class model class MyUser(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=50, unique=True) phone = models.CharField(verbose_name='phone', max_length=50) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] objects = MyUserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_lable): return True Project setthing AUTH_MODEL_USER = serivce.MyUser /* I'm tried to create an admin user login with the command python manage.py createsuperuser the email I used : coded@gmail.com the error i'm getting: Error: Enter a valid email address. */ -
Replace some special characters from username in django
how i can set django username as telegram username characters example testuser_user testuser_user_5 jQuery(function($) { $("#id_username").on("keyup blur", function() { $(this).val($(this).val().replace(/[^a-z0-9]/ig, '')); }); }); -
Is there a way to order Wagtail Blocks in the Admin Panel
Currently I have all blocks split out into different groups for the page editors to easily navigate through the different block options. However, from reading the documentation I cannot see any way to specifically order the groups. It would be great to be able to customise this so that I could have the text editor group at the top, the image group/carousel block next to each other etc. -
path in FileField django
I prepared my model to create PDF filled by all the fields it includes and I try to to link generated file to the pdf = models.FileField(). However the path to the file seems to be ok I can't reach the file through the view. models.py: class Lesson(models.Model): # fields # ... pdf = models.FileField(upload_to = 'pdfs/', default = None, blank = True) def render_template(self, request): #some magic BASE_DIR = str(Path(__file__).resolve().parent.parent) file_name = 'myfile' os.system(f"pdflatex -halt-on-error --output-directory={BASE_DIR}/media/pdfs {BASE_DIR}/media/tex/rendered/{file_name}") os.system(f"rm {BASE_DIR}/media/tex/rendered/{file_name}.tex") os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.aux") os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.log") return f"{BASE_DIR}/media/pdfs/{file_name}.pdf" views.py: def create_lesson(request): lesson = Lesson() lesson.pdf = lesson.render_template(request) lesson.save() message = { 'tag' : 'success', 'body' : "Successfully added new lesson!" } return JsonResponse({'message' : message}) But when putting <a href="{{ lesson.pdf }}">CLICK TO VIEW FILE</a> the link directs to: http://localhost:8000/docs/lessons/media/pdfs/myfile.pdf What path should be set to pdf field to direct to media/pdf/myfile.pdf in models.py?