Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to refresh the active django webpage without using return redirect(...)?
I'm trying to have the current webpage refresh itself after the function is completed, and I'm aware that the best way to accomplish this is through redirect(...), however in order for the code to do what it's supposed to it is already returning a value, and I don't think it's possible to return both at the same time (every time I've tried I got an error). So that leaves me wondering if there is another way to refresh the window. I'm fine with either doing it within the views.py file or as a javascript function, I just don't know how to have the two communicate if using javascript. Here is my HTML Code: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&family=Roboto:wght@100;300;400;500;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select the files you want to convert.</p> <p>Once you click "Submit" the … -
Django with Huey - delay a task
For a scenario with sales orders, I'm needing to execute a task with a given delay. To accomplish this, I added a task in my tasks.py file like so: from huey import crontab from huey.contrib.djhuey import db_task @db_task(delay=3600) def do_something_delayed(instance): print("Do something delayed...by 3600 seconds") However, this delay setting doesnt seem to delay anything. The task is just scheduled and executed immediately. What am I doing wrong? -
Passing form data between 2 seperate views without carrying it via URL arguements
basically i have two separate views, but i need form data from the first view to pass to the second view without having to pass it via URL parameters. is this possible? NOJS -
How to mention id from html in django
I'm working on a single page website where the pages are made with id in the main html page. Now the problem is I want to connect the "contact" id's form with database. but I don't know how to mention the id in code. I mean i know what to do if the pages are separated htmls but don't know how to use id from one html site. There's another html page for blogs only. I'm mainly confused on how to use post method in this case. views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse # Create your views here. def home(request): if request.method=="POST": print("This is post") return render(request, 'index.html') def blog(request,id ='contact'): if request.method=="POST": print("This is post") return render(request, 'blog-single.html') urls.py of main project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('portfolio.urls')) ] urls.py from app: from django.contrib import admin from django.urls import path, include from portfolio import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] template file: <form action="#contact" method="post" role="form" class="contactForm"> {% csrf_token %} <div id="sendmessage">Your message has been sent. Thank you!</div> <div id="errormessage"></div> <div class="row"> <div class="col-md-12 mb-3"> <div class="form-group"> <input type="text" name="name" class="form-control" … -
Azure Linux based web app Restart automatically
I am Running Django Application on an Azure Linux Web App, I have noticed that after a certain point the application restarts. when drilling down the issue, I found that the Container disk or memory is not sufficient. My Image size is around 5-6 gb which is under 15 gb limit. Is there any better way of Deploying Django application ? -
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?
I want to push my Django project to GitLab and build a build with the pipeline. But I get this error message every time: Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running? gitlab-ci.yml -
Rebuilding the database when 'Reverse for 'wagtailadmin_explore' with arguments '('',)' not found error' occurs
I flushed the wagtail database using python manage.py flush and now have this error. I found that in this question somebody else had the same issue and managed to solve it by using docker. Reverse for 'wagtailadmin_explore' with arguments '('',)' not found However, I just want to restore the wagtail site I was working on to a working state in the development server. I already tried flushing again and rebuilding the db but I can't seem to figure it out. Is there a way to fix this error by not using docker? -
How can I create a movie rating site in Django using the TMDB API?
I would like to create a movie review site using TMDB's API and have a question. 1.I am getting an error saying "Movie matching query does not exist. I am thinking that I have defined a Movie model and movie = Movie.objects.get(id=movie_id) is wrong. 2. I would like to list the comments and movies commented by the User in views.py. How do I add this? 3.User can only comment on one movie, but I want to add edit and delete, how can I do that? def view_tv_detail(request, tv_id): if request.method == "POST": user = request.user comment = request.POST.get("comment") stars = request.POST.get("stars") if not request.user.is_authenticated: user = User.objects.get(id=1) Comment(comment=comment, star = stars, user=user,movie_id = tv_id).save() return redirect(f"/tv/{tv_id}/") else: data = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comment_list = Comment.objects.filter(movie_id=tv_id) comments = reversed(Comment.objects.filter(movie_id=tv_id)) n_comments = comments.count() if n_comments == 0: average = 0 else: average = sum([comment.stars for comment in comments]) / n_comments return render(request, "Movie/tv_detail.html", { "data": data.json(), "recommendations": recommendations.json(), "type": "tv", "comments": comments, "average" : average, }) class Movie(models.Model): def get_comments(self): return Comment.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: return sum([comment.stars for comment in comments]) / n_comments else: return 'No comments posted yet' class Comment(models.Model): class Meta: unique_together … -
sync labels for multiple data-sets in chart.js
I am making a website that keeps track of your expenditure, so I want to display a graph showing the expense made by each subfield, be it weekly, monthly, yearly, or even daily. Question how do I sync the labels with multiple databases, so what's happening is when I go to show my data weekly. the sports field's data is not getting in sync with the labels. in the first column (labeled week 23) the data which is being shown with week 23 of body is actually the data of week 27 of sports so what I want to do is, sync the labels and make sure that the data of week 27 is being shown in week 27 only, no matter where the data-set starts. code views.py @login_required def maingraph(request, pk): lb_wa = Body.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").order_by( "week").distinct() wa = Body.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").annotate( total=Sum(F('price') * F('quantity'), output_field=FloatField())).order_by("week") s_lb_wa = Sport.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").order_by( "week").distinct() s_wa = Sport.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").annotate( total=Sum(F('price') * F('quantity'), output_field=FloatField())).order_by("week") return render(request, 'main_app/m_graph.html', {"wa": wa, "lb_wa": lb_wa , "s_wa": s_wa, "s_lb_wa": s_lb_wa}, ) HTML {% extends "main_app/main_base.html" %} {% block scripts%} <script> $(document).ready(function(){ const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for item in lb_wa %}'{{item.week }}',{% endfor … -
Is there a tutorial or easy method to view django database db.sqlite3? [duplicate]
Essentially, I would like to see the tables and their contents of the database for my Django project so that I can keep track of my data and seeing if everything is working correctly? Do I need to use a third party software such as MySQL, MariaDB, etc.? -
Django Many-To-Many through form with specific queryset
I have the following models Program and Exam with foregin keys to University. class Program(models.Model): university = models.ForeignKey(University, on_delete=models.CASCADE) ... exams = models.ManyToManyField(Exam, through='ProgramExam') class Exam(models.Model): university = models.ForeignKey(University, on_delete=models.CASCADE) ... And they have a many-to-many relation through the model ProgramExam which adds extra fields. class ProgramExam(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, on_delete=models.DO_NOTHING) coef = models.FloatField( validators=[MinValueValidator(0.0), MaxValueValidator(3.0)] ) class Meta: unique_together = [['program', 'exam']] How do I set the queryset in forms.ModelChoiceField so to only display instances of Exam that have the same fk as the instance of Program class ProgramExamForm(forms.ModelForm): exam = forms.ModelChoiceField(queryset=Exam.objects.none()) I tried passing a queryset in my view but it interferes with request.POST def create_program(request): user = request.user exams = user.university.exam_set.all() program_exam_form = ProgramExamForm() program_form.fields['exam'].queryset = exams if user: if hasattr(user, 'university'): if request.method == 'POST': program_exam_form = ProgramExamForm(request.POST) if program_exam_form.is_valid(): program_exam = program_exam_form.save() ... context = {'program_exam_form': program_exam_form} return render(request, 'create_program.html', context) -
Remove Server Header from TemplateResponse Django 3.1?? (header not showing)
So I have to remove or hide the server header from a django app I am working on for security (I was asked to remove it). I tried removing it from a middleware but the header is not showing! Nonetheless it is shown when the page loads. I tried this, but it raises a ValueError "too many values to unpack" class NoServerHeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response._headers['Server'] = "Empty" return response When I explore the response this is all there is: {'content-type': ('Content-Type', 'text/html; charset=utf-8'), 'content-length': ('Content-Length', '26292'), 'x-frame-options': ('X-Frame-Options', 'SAMEORIGIN'), 'vary': ('Vary', 'Cookie'), 'x-content-type-options': ('X-Content-Type-Options', 'nosniff'), 'referrer-policy': ('Referrer-Policy', 'same-origin')} So, not being Server header in there I can not really modify it can I? What am I missing? Where could the header be being added? -
JWT auth using python-social-auth and django-rest-framework
I'm trying to convert a snippet of code that I found (using python-social-auth) to make it handle JWT authentication instead of simple token authentification. Here is the code: @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def oauth_exchange_token_view(request, backend): serializer = SocialAccessTokenSerializer(data=request.data) if serializer.is_valid(raise_exception=True): # set up non-field errors key try: nfe = "non_field_errors" except AttributeError: nfe = 'non_field_errors' try: # this line, plus the psa decorator above, are all that's necessary to # get and populate a user object for any properly enabled/configured backend # which python-social-auth can handle. user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: # An HTTPError bubbled up from the request to the social auth provider. # This happens, at least in Google's case, every time you send a malformed # or incorrect access key. return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) return Response({'access': token.key}) else: return Response( {'errors': {nfe: 'This user account is inactive'}}, status=status.HTTP_400_BAD_REQUEST, ) else: return Response( {'errors': {nfe: "Authentication Failed"}}, status=status.HTTP_400_BAD_REQUEST, As you can see in the code above, the token is returned like this: token, _ = Token.objects.get_or_create(user=user) return Response({'access': token.key}) But I would like it to return a JWT using djangorestframework-simplejwt instead. -
Django Filter with custom field_name and Custom value as an argument in queryset
I am using the filter in Django queryset, as it requires an argument and a value assigned to it. eg. ModelName.objects.filter(name="Amit").values() in such a case I am sending both the values from the API request so that both can be custom as per the need [like in the custom field we can search any custom value], but unable to use in this Filter function. Please let me know where I am doing wrong, can it be possible like this too. Thanks -
I can't create in related tables in django using serializers
Please, help! I need create a stock database postgresQL. I use the command in Visual Studio Code. But I have error on string "StockProduct.objects.create" in serializers.py. The stock is created in base, but without products in this stock. command in Visual Studio Code: ### # create a stock POST {{baseUrl}}/stocks/ Content-Type: application/json { "address": " stock_ address ru3", "positions": [{"product": 2, "quantity": 250, "price": 120.50}, {"product": 3, "quantity": 100, "price": 180}] } serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('title', 'description') class ProductPositionSerializer(serializers.ModelSerializer): class Meta: model = StockProduct fields = ('quantity', 'price') class StockSerializer(serializers.ModelSerializer): positions = ProductPositionSerializer(many=True) #id = serializers.IntegerField() # configure the serializer for the warehouse class Meta: model = Stock fields = ('address', 'positions') def create(self, validated_data): positions = validated_data.pop('positions') # create stock stock = super().create(validated_data) for position in positions: StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity'])# 1.Variant #StockProduct.objects.create(stock=stock, **position) # 2. variant "logistic_stockproduct" relation violates NOT NULL restriction # defaults = {'price'=position['price'], 'quantity'=position['quantity']}) #product=position['product'], price=position['price'], quantity=position['quantity']) # StockProduct.objects.create(position) #position=position # StockProduct.objects.create(stock('id'), position) #StockProduct.objects.create(positions) # quantity = position.pop('quantity') # price= position.pop('price') # StockProduct.objects.create(quantity=quantity, price=price) return stock variant Error # 1 variant Error . line 36, in create StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity']) KeyError: 'product' # 2. variant: DETAIL: The … -
Using JavaScript onclick function to change innerHTML to form field
I am trying to use the JavaScript onclick() function to change a piece of HTML to a Django Model Form field when clicked? Using the code below, I would expect that when the {{ tasks.owner }} is clicked, the html with id "task_owner" would change to {{ task_update_form.owner }}. My Django template is below: <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "{{ task_update_form.owner }}"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> If I use the below code - substituting {{ task_update_form.owner }} with "Test" it works perfectly. <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "Test"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> I have also tested it using non-form context from my views.py and it works. {{ task_update_form.owner }} works fine when inserted into the Django template normally. My experience with JavaScript is limited and I would be grateful for any help. -
Query Django custom user model with many-to-many field
I'm very new at Django. I have a custom user model: accounts\models.py: from django.contrib.auth.models import AbstractUser from django.db import models from tradestats.models import Webhook class CustomUser(AbstractUser): webhook = models.ManyToManyField(Webhook, blank=True) I have a tradestats app with a Webhook model: tradestats\models.py from django.db import models class Webhook(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) name = models.CharField(verbose_name='Webhooks name', max_length=50, null=False, blank=False) url = models.URLField(max_length=255, null=False, blank=False, unique=True) def __str__(self): return self.name class Meta: ordering = ['name'] I have a class based View. In this View I like to query the logged in user all Webhooks url field and pass to render() as a context. tradestats\view.py: context = { 'form': form.cleaned_data, 'variable': value1, 'variable2': value2, } return render(request, template_name='renko/renko_calculate.html', context=context) How can I query the webhook.urls and pass into context? Thank you so much. -
I create speech to speech translation using python how can deploy on flask to take input from microphone bcz after deployment PyAudio not working
I create speech to speech translation continously using thread using python how can deploy on flask to take input from microphone because after deployment PyAudio not working -
How to check if a django model attribute is of type ManyToMany
I have a django model in which I am inspecting the fields types and I want to check if a field is a ManyToMany field. When I call the type(attribute) function however, the returned type is a ManyRelatedManager object and not a ManyToManyField. This is a bit of a problem because I can't use the isinstance(attribute, ManyRelatedManager) because from what I see in the source code, this class is in a closure context and can't be accessed externally. How would I check if a field in django is of type ManyToMany? I checked out this answer but this doesn't seem to be my scenarion, I don't care what is the model of the ManyToMany I want to know if it is a many to many -
DRF - serializer for list of dictionaries
I've a serializer class which return "single" data well, like: class MySerializer(serializers.Serializer): num: Decimal = serializers.DecimalField(max_digits=10, decimal_places=4, required=True uid: str = serializers.CharField(max_length=30, required=True) . I'd like to add a parameter (other) to this serializer which would return list of dictionaries, but I can't find out how to do it. The structure of other would look like this: [ {'p1': int, 'p2': int, 'p3': {another dict which has already a serializer class} } ] What would be the way to achieve this? If I add serializers.DictField or serializers.ListField I always got back "'list' object has no attribute 'items' AttributeError" or "Object of type PoCo is not JSON serializable TypeError" where PoCo is a class of mine. Thanks. -
Django View Unit-Test: assertHTML selector 'body' is empty
I am trying to Unit-Test my Django-Views via pytest -s my_view.py. Currently I am testing one like this: table_selector = CSSSelector("table.tableClass tbody tr") response = self.client.get(reverse("endpoint", args=(object.id,)), follow=True) with self.assertHTML(response, "body") as (body,): print(response.content) # shows HTML as expected print(body.text) table_rows = table_selector(body) print(table_rows) # empty array print(body.text) gives me this output: basically just empty spaces / new lines even though response.content contains a <body>-tag! How is this possible? Any ideas why this doesn't work? -
D3.js Fix Date Issue on Line Graph - Django as Backend
I am following some examples of d3.js to plot graphs. For reference here is the link. Following is the code where I've used the LineChart function to build the plot. With Django as backend. <!DOCTYPE html> {% load static %} <html> <script src="https://d3js.org/d3.v6.js"></script> <body> <h1> Hello! </h1> <div id="chart"></div> </body> <script> // set the dimensions and margins of the graph const margin = { top: 10, right: 30, bottom: 30, left: 60 }, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // Copyright 2021 Observable, Inc. // Released under the ISC license. // https://observablehq.com/@d3/line-chart function LineChart(data, { x = ([x]) => x, // given d in data, returns the (temporal) x-value y = ([, y]) => y, // given d in data, returns the (quantitative) y-value defined, // for gaps in data curve = d3.curveLinear, // method of interpolation between points marginTop = 20, // top margin, in pixels marginRight = 30, // right margin, in pixels marginBottom = 30, // bottom margin, in pixels marginLeft = 40, // left margin, in pixels width = 640, // outer width, in pixels height = 400, // outer height, in pixels xType = d3.scaleUtc, // the … -
Password must be a string or bytes, got list Django Rest Framework
I have an API that has a createaccount endpoint. I pass a password when creating the user and the password is passed as string. However, when it is passed to the serializer it comes out as a list, which causes this error: Password must be a string or bytes, got list this error also duplicates itself to my other two attributes, username and account_type as seen below. I have had to do list comprehension by getting the first element of the lists to get the values which I feel is the incorrect way of dealing with this issue. Here is my models.py for the Account model with its associated Manager: from django.db import models import django.contrib.auth.models as auth_models class AccountManager(auth_models.BaseUserManager): def create_user(self, username, account_type, password=None): if not account_type: raise ValueError("Users must have an account type") if not username: raise ValueError("Users must have a username") requested_account_type = account_type[0] user = self.model(username=username, account_type=requested_account_type) user.set_password(password[0]) user.save(using=self._db) return user def create(self, username, account_type): if not account_type: raise ValueError("Users must have an account type") if not username: raise ValueError("Users must have a username") requested_account_type = account_type[0] user = self.model(username=username, account_type=requested_account_type) user.save(using=self._db) return user def create_superuser(self, username, password, account_type="jool-admin"): user = self.create_user( password=password, username=username, account_type=account_type ) … -
Image not visible on webpage despite adding every crucial code
I am trying to upload my image to make it visible on the webpage but it isnt happening,the alt="no image found" comes.I am doing a CRUD project using serializers this surely means that there is no problem with the paths that I have inserted but the problem is there elsewhere but I am unable to figure it out and I have tried many times. below are the show and insert function def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) data = serializer.data for i in range(len(data)): product = Products.objects.filter(id=data[i]['id']).first() data[i]['categories'] = product.categories.__str__() data[i]['color'] = product.color.__str__() data[i]['size'] = product.size.__str__() data[i]['sub_categories'] = product.sub_categories.__str__() context = {"data":data} return render(request,'polls/product_list.html',context) def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['image'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) … -
I want to click a Tkinter button and then export the searched item to excel file, how can I do that?
def print_area(self, txt): try: con = pymysql.connect(host='localhost', user='root', password='', db='philanthropy') cur = con.cursor() cur.execute("select * from istavrity where familycode LIKE '%"+self.var_search.get()+"%'") row=cur.fetchall() for i in row: fName = i[1] if len(row)>0: row_list = [] columns = ('S.N.', 'Family Code', 'Family Name', 'Ritwik', 'Swastyayani', 'Family Name', 'Ritwik', 'Swastyayani', 'FamilyCode', 'Family Name', 'Ritwik', 'Swastyayani', 'FamilyCode', 'Family Name', 'Ritwik', 'Swastyayani', 'ravv') self.employee_tree.delete(*self.employee_tree.get_children()) for i in row: self.employee_tree.insert('',END,values=i) row_list.append(i) treeview_df = pd.DataFrame(row_list, columns = columns) print(treeview_df) treeview_df.to_excel(f"excel_backup/{fName}.xlsx") else: self.employee_tree.delete(*self.employee_tree.get_children()) except Exception as ex: messagebox.showerror("Error",f"Error due to {str(ex)}") The search area code is # btn_search = Button(root, text="Search", font=("times new roman", 12), bg="white",fg="black").place(x=800,y=5, height=20) self.txt_search = Entry(root,textvariable=self.var_search, font=("goudy old style",15,'bold'), bg="white",fg="blue") self.txt_search.place(x=870,y=5,height=20,width=250) self.txt_search.bind("<Key>", self.search) And the button code is: self.btn_print = Button(root,text="Print", font=("times new roman", 15), bg="red", fg="white") self.btn_print.pack() The problem is, just by searching the fcode, it gets exported without clicking button.