Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a webpage with Django that displays two different queries?
For my Django project I decided to make a mock news website. I created a class for the various news articles. I made one of the variables “type” to designate whether the article was a news story or a podcast. I then created two templates: news.html and podcasts.html. Then, in views.py, I created a function that returns only the news stories for news.html and another function that returns only the podcasts for podcasts.html. def allArticles(request): articles = Article.objects.filter(type="news").order_by("-date") return render(request, 'article/allArticles.html', {'articles': articles}) def podcasts(request): articles = Article.objects.filter(type="pod").order_by("-date") return render(request, 'article/podcasts.html', {'articles': articles}) I am trying to create a third page with two sections, one that displays news stories and the other will display podcasts. I cannot just call the entire database because it will not be separated into the proper sections and there are other types of articles besides news stories and podcasts. I tried combining the code of news.html and podcasts.html into one html file, however it will only return one of the two. I also tried using snippets, it returned just the news articles twice. I feel like the solution is somewhere in the URL patters. Its like each path will only trigger one view so if … -
Why Django "migrate" reports OK for apps that have been skipped from migration?
I created custom database Router and properly configured it (and the database aliases) in settings.py. The router defines allow_migrate() method - which explicitly skips (returns False) undesired apps. Basically, there are two key requirements: Allow migrations ONLY for a given set of "desired" apps For those "desired" apps - allow migration only in a certain database I have very detailed unit test script that validates ALL possible test cases and proves everything is "routed" the way it should. I included debug print statements that print message when migration is allowed (returns True), and when I apply migrations (run "migrate") that includes both "desired" and "undesired" apps - it produces stdout (saying that migration for such-and-such app is allowed) ONLY for the right migrations. But... the output also includes "Applying ... OK" for all the rest apps (for which allow_migrate() returned False) as well. In the database, I see migrations applied ONLY to desired apps - but "migrations" table lists all of the migrations (both applied and the ones that are not applied). WHY "migrations" table gets records for migrations that have not truly been applied (and stdout shows OK)? What am I missing - how can I avoid migrations to … -
Changing the template for django-lockdown
I am trying to use my own template for the password page that is generated by django-lockdown. In the documentation it says, that I should use Djangos template loaders to change the location of the template, but I am not exactly sure how to do it. "If you want to use a different template, you can use Djangos template loaders to specify a path inside your project to search for templates, before searching for templates included in django-lockdown." "In your overwritten template the lockdown preview form is available in the template context as form" Anyone have any ideas? -
Unable to send an image using ajax to django rest framework
I'm trying to send an image from frontend using ajax to backend using django rest framework without result. The response error is: {"detail":"Unsupported media type \"image/png\" in request."} where instead of "image/png" I tried a lot o different types. (the img I'm sending is a png) HTML: <input type="file" name="" id="profilepic" enctype="multipart/form-data" accept="image/*"> <label id="uploadBtn" for="profilepic">Choose your profile photo</label> JS: Note that first I was sending all the nested data as JSON but later I splitted to send the img separeted. var my_data = { "user_url": user_url, "user": username, "atoms": [atom_dict] }; $.ajax({ url: origin + '/boonds_api' + userurl, type: 'PUT', contentType: "application/json", data: JSON.stringify(my_data), success: function (result) { console.log(my_data); } }); // Until here everything is fine sebding data to backend // Only img my_img = $('#profilepic')[0].files[0] var my_data = {"atoms": {"img":my_img}}; $.ajax({ url: origin + '/boonds_api' + userurl, type: 'PUT', contentType: "image/png", data: JSON.stringify(my_data), success: function (result) { console.log(my_data); } }); DJANGO models.py class Atom(models.Model): name = models.CharField(max_length=128,blank=True) bio = models.TextField() img = models.ImageField(null=True, blank=True, upload_to='users_app') user_account = models.ForeignKey(UserAccount, on_delete=models.CASCADE, null=True, blank=True, related_name="atoms") def __str__(self): return self.name views.py class UserAccountViewSet(viewsets.ModelViewSet): queryset = UserAccount.objects.all() serializer_class = UserAccountSerializer lookup_field = "user_url" permission_classes = [IsOwnerOrReadOnly] def update(self, request, *args, **kwargs): # … -
Getting "Uncaught TypeError: You must pass either a valid element or a valid id." when changing the video link from vimeo to vidyard
I'm trying change my video from vimeo to vidyard on my webpage. I've done all the necessary things for this but when i replace vimoe Ifmrae with a vidyard img tag, I'm getting "Uncaught TypeError: You must pass either a valid element or a valid id" error. Below is the code which is causing me errors. <div class="overlay"> <div class="video-container" id="{% hyphenate value=self.title %}-video-container"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <!-- <iframe class="vidyard_iframe" src="https://play.vidyard.com/2NNWyVPRXCtfikieAuBCku.html?" width="640" height="360" scrolling="no" frameborder="0" allowtransparency="true" allowfullscreen></iframe> --> <iframe id="video-{% hyphenate value=self.title %}" src="{{ self.embed_url }}" allowfullscreen title="{{ self.title }}" style="border: none;"></iframe> <img style="width: 100%; margin: auto; display: block;" class="vidyard-player-embed" src="https://play.vidyard.com/EPLHxfDKwSdr96WDiR3ReZ.jpg" data-uuid="EPLHxfDKwSdr96WDiR3ReZ" data-v="4" data-type="inline" /> </div> </div> Please let me know if you need more information. Thank you!! -
"Forbidden (CSRF token missing or incorrect.):" using Django and JS
I'm doing a POST request using Axios in my JS code to send some information to my locally hosted Django server. I have {% csrf_token %} in my html code form but don't know how to send the csrf token using Axios. I am getting this error in the terminal: "Forbidden (CSRF token missing or incorrect.): /api/scoring/submit_score_details". How do I correctly insert the csrf token in my axios post? Right now, I don't think JS can read {{ csrf_token }} as I have it. I've been searching Stack but it seems most people are using jQuery or some other type of JS. To save space I didn't post what the variables in the payload are. I can get the error to go away if I put @csrf_exempt above the my function in the views.py file. { let payload = { "csrfmiddlewaretoken": "{{ csrf_token }}", "math_problem": problem, "user_answer": userInput, "true_answer": correctAnswer, "question_status": questionStatus, } console.log(payload); axios.post('../api/scoring/submit_score_details', payload) } <div class="col text-center"> <button id="start" type="button" class="btn btn-primary btn-lg"> New Problem </button> <p id="math_problem"></p> <form id="inputForm" method="POST"> {% csrf_token %} <input id="user_input" autocomplete="off" class="form-control form-control-lg" type="text" placeholder="Type your answer here"> <input id="correct_answer" type="hidden"> </form> <br> <button id="result_check" type="button" class="btn btn-primary btn-lg">Check</button> <script src={% … -
Django: 'password_change_done' is not a valid view function or pattern name
In main urls.py I have this content: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('adm/', admin.site.urls), # path('adm/', include('django.contrib.auth.urls')), # Pre-built password_reset, password_change #path(r'^', include('django.contrib.auth.urls')), path('', include('account.urls')), ] And my app name is account. So I have this urls.py in account app: from django.urls import path from account import views from django.contrib.auth import views as auth_views urlpatterns = [ path('panel', views.panel_home_view, name='panel'), path('panel/register', views.registration_view, name='register'), path('panel/logout', views.logout_view, name='logout'), path('panel/login', views.login_view, name='login'), path('panel/profile/password_change/done', auth_views.PasswordChangeDoneView.as_view(template_name='account/user/authentication/password_change_done.html'), name='password_change_complete'), path('panel/profile/password_change', auth_views.PasswordChangeView.as_view(template_name='account/user/authentication/password_change.html'), name='password_change'), path('panel/password_reset/done', auth_views.PasswordResetCompleteView.as_view(template_name='account/user/authentication/tion/password_reset_done.html'), name='password_reset_done'), path('panel/reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('panel/password_reset', auth_views.PasswordResetView.as_view(), name='account/user/authentication/password_reset'), path('panel/reset/done', auth_views.PasswordResetCompleteView.as_view(template_name='account/user/authentication/password_reset_complete.html'), name='password_reset_complete'), path('panel/profile/edit', views.edit_profile_view, name='edit-profile'), ] Finally just after changing password successfully the page password_reset_done.html is not open and I see the following error: NoReverseMatch at /panel/profile/password_change Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Note that password is changing successfully. -
Store values from GET Request to reuse in POST request
I have a view that receives GET request data from a 'search', retrieves the values and uses the data to initialise another form i.e MyDynamicForm(foo=bar). When that form is POSTed, I need to re-instantiate the same form with the POST request (MyDynamicForm(request.POST)). Since the form's init method expects data in the kwargs to initialise it, I need to pass the same data as a parameter. ie MyDynamicForm(request.POST, foo=bar). I have no idea how to get this to work since the POST request won't be able to receive GET request data to form the required variable. Is there a way that the view can store dynamic data like this to be used in both methods? Or do I need to store the data in the session? Side note: I am using Django FormView and have been attempting to work with get_form_kwargs(). This works if using session data such as the current user but struggling to find examples with GET request data -
List pagination in Django
I want to paginate a list of books. The api end point is like this /books?page=num&size=num So the number of page and how many books to load will be variables. My response should look like: { pagesnum= totalpages booksnum=totalbooks books= [ {detailsofbook1}, {...}, {...} ] } My code: urlpattern: path('api/books?page=<int:page>&size=<int:size>/',BookView.as_view()), views.py class BookView(APIView): http_method_names = ['get'] permission_classes = (permissions.IsAuthenticated,) def index(request): books = Books.objects.all() books_per_page= request.GET.get('size') book_paginator = Paginator(books, books_per_page) page_num = request.GET.get('page') page = book_paginator.get_page(page_num) context = { 'count': book_paginator.count(), 'page': page queryset =Books.ojects.all() } return JsonResponse(context, status=200) This implementation doesn't work. First of all something is wrong probably with the url it doesnt seem to understand the variables. Or is something else wrong with my code? -
How to navigate from current html page to index page and insert image in django
index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'parkatdcu/index.css' %}"/> <img src= 'dcu_logo_stacked_red.png'> <h1>Welcome to ParkAtDCU</h1> <form action="{% url 'parkatdcu:carparks' %}" method="get"> Campus (Carpark): <input type="text" name="campus"> <input type="submit" value="Go"> </form> <form action="{% url 'parkatdcu:bus_stops' %}" method="get"> Campus (Bus stop): <input type="text" name="campus"> <input type="submit" value="Go"> </form> carparks.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'parkatdcu/carparks.css' %}"/> <h2> {% if campus %} {{ campus }} {% else %} No such campus {% endif %} </h2> {% if campus %} {% if carparks %} <ul> {% for carpark in carparks %} <li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities <br>Spaces available: {{ carpark.spaces_available }}<br><br> </li> {% endfor %} </ul> {% else %} <p>No carparks found</p> {% endif %} {% endif %} I'm trying to create a navigation bar to go from carparks.html to index.html and also put in an image on the index page. -
Styling an error message apart from a successful plot using plotly
I am using plotly in django. I have a plot defined to be: plot = plot_bar(df, agg_method='count', barmode='stack', legend_order=legend) There is also an if statement that checks if the data is empty and prints an error message. if plot is empty: plot = "No data to be displayed" Currently the error message get's displayed in the plot. I want to style the error message apart from a successful plot. How can I define one class that handles two different stylings? Can't find much documentation on this issue, thanks. -
Annotating in Django query based on a many to many relationship
I am using Django with Postgres. I have an object called Product and another called UserProfile. When a user likes a product, the product gets recorded in UserProfile's field like this: watchedProducts = models.ManyToManyField('Product', related_name='user_where_watched', blank=True) Now what I want to do is query the table of products and order products by the number of likes. What I have (it's not working) is: products = Product.objects.filter(fullSearchCondition).distinct().annotate(numOfLikes=RawSQL('SELECT COUNT(id) FROM "myapp_userprofile_watchedProducts" WHERE "product_id"=%s',(F('id'),))).order_by("numOfLikes") The thing I am not getting is how to inject the product id into the query. I also looked into Django's custom expression functions but it looks even more complicated to me. Could somebody let me know a good way of doing this? -
django-logpipe (kafka) implementation in django project
I'm trying to implement django-logpipe into my Django project. My goal is to organize requests from rest_framework.viewsets to the database into a queue, using kafka (indirectly by django-logpype). Using wemake-django-template as start point for my project, i successfully install 'django-logpipe' package and launch it, using this tutorial. Migration python manage.py migrate logpipe was successfull. This is my project hirerarchy: bills config docker docs locale server apps ... bill migrations static __init__.py admin.py apps.py forms.py managers.py models.py permissions.py router.py serializers.py tests.py urls.py views.py ... I've all ready made serilizars modification for django-logpipe. My next step: Producers and Consumers. As far as i could understand, according tutorial, i can implement Consumers of django-loppipe in apps.py by this: # bills/server/apps/bill/apps.py from logpipe import Consumer, register_consumer from django.apps import AppConfig class BillConfig(AppConfig): name: str name = 'bill' # Register consumers with logpipe @register_consumer def build_person_consumer(): consumer = Consumer('people') consumer.register(PersonSerializer) return consumer But, where i can put Producer? As far as i understand, Producer should send a JSON data to Consumer, which should serialize it in apropriate data structure and process it by registred serializer. Data i can receive from Django it self, and from rest api. First place in rest_framework.viewsets where i can see … -
Make redirection with param in django backend app and to react frontend app
I want to make a redirection with param from django backend app to react front end app component and read param. How can I do , I'm struggling with this, it give me Page not found. My redirection code in django backend view is : return redirect('http://localhost:3000/auth/new-password/', {'uid': uid, 'token': token}) and my route to target component is : <Layout exact path="/auth/new-password/:uid/:token/" component={ResetPasswordConfirm} /> Thanks for help. -
Django class sql data pull
I have class: class Like(models.Model): user = models.ForeignKey(User, related_name='likes', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE) ratingtype = models.IntegerField(default=0) that lets me display total amount of lines in database table with this tag: {{post.likes.count}} What would be the best way to modify this class so i can differentiate the counting by two ratingtype (true or false) -
How to change django application basepath with gunicorn
I want to launch my django app with basepath=/api, every url should start with /api, something like. urlpatterns = [ path("/api", include([ # all my urls ])) ] But I really don't want to do this in the code Is it possible to do this using gunicorn? -
Can't override drf nested serializer CREATE
I am trying to create an instance of Product class with postman but nothing works for me. I have tried just to add one category, also give a list of categories with category_ids, still no success. Can anyone point, what am I doing wrong? I have searched everywhere but couldn't find a solution. Why am I getting this keyError? models: class Category(models.Model): name = models.CharField(max_length=80) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): category = models.ManyToManyField(Category, blank=False) name = models.CharField(max_length=100) description = models.TextField(max_length=250) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(default=0) class Meta: ordering = ("name", ) def __str__(self): return self.name serializer: class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(many=True, required=False) category_ids = serializers.PrimaryKeyRelatedField(source='category', many=True, queryset=Category.objects.all()) class Meta: model = Product fields = ( "id", "name", "category_ids", "category", "description", "price", "quantity" ) def create(self, validated_data): categories = validated_data.pop('category') product = Product.objects.create(**validated_data) Category.objects.create(product=product, **categories) return product views: class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def perform_create(self, serializer): serializer.save(created_by = self.request.user) def perform_update(self, serializer): serializer.save(updated_by = self.request.user) def perform_destroy(self, instance): instance.deleted_by = self.request.user instance.deleted_at = timezone.now() instance.save() error: Exception Type: KeyError Exception Value: 'category' -
Couldn't import Django. Are you sure it's installed and available?
I built a django app. Now I am trying to run the project on local. then i got the issue. -
DRF Serializer is returning empty dictionary while doing serializer.data
I have a serializer like following: class LoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255, write_only=True) password = serializers.CharField(max_length=255, write_only=True) def validate(self, validate_data): username = validate_data.get('username', None) password = validate_data.get('password', None) if username is None: raise serializers.ValidationError({'error': 'Email is required!'}) if password is None: raise serializers.ValidationError({'error': 'Password is required!'}) user = authenticate(username=username, password=password) token = Token.objects.get_or_create(user=user) return {'username': user.username, 'token': 'token'} and a view for this: class LoginAPIView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) # this prints {} return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) I don't know what is wrong here, do I have to return validate_data? -
Rendering DataFrame to html using dynamic column names
I want to render a pandas dataframe on html as a table. The problem I am facing is that the column names are dynamic. Here is what I am doing in views. def index_1(request): df = pd.read_csv("my.csv") columns = df.columns json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = { 'dataframe': data, 'columns': columns } return render(request, "positions/options.html", context) Below is the relevant part of my html code. {% block content %} <table id="positions-table"> <thead> <tr> {% for i in columns %} <th>{{i}}</th> {% endfor %} </tr> </thead> <tbody> {% for i in dataframe %} <tr> {% for j in columns %} <th>{{i.j}}</th> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endblock %} I am able to add the column names dynamically but when I try to populate the table using i.j that's using i'th row and j is the column name, it returns a blank table. How can I populate my table dynamically without having to specify column names? -
Django - signing up multiple user-types with Dj-Rest-Auth
Would like some advice about authentication via Rest API, especially signing up with multiple user-types. I am quit new to Djangorestframework so hope to find some help. I Think Dj-Rest-Auth because 'django-rest-auth' is not supported anymore. Is this the right choice? This is how I modelled my User, Student and Teacher class models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) .... class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) .... I would like to sign-up either as a student or as a teacher. So I have to set the 'is_student' field or 'is_teacher' field direct after signing up. What is the best approach and has to be changed or added in the code to make this work? Best regards, Martijn -
Issue getting model name from ForeignKey
I have two models: Exercise and UserExercise class Exercise(models.Model): options = ( ('run', 'run'), ('jog', 'jog'), ('lift', 'lift'), ('yoga', 'yoga'), ) name = models.CharField(max_length=50, choices=options, unique=True) def __str__(self): return str(self.name) class UserExercise(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.ForeignKey(Exercise, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False, default=0) calories_burned = models.FloatField(null=False, default=0) def save(self, *args, **kwargs): self.person_of = self.person_of self.name = self.name self.quantity = self.quantity self.calories_burned = self.calories_burned super(UserExercise, self).save(*args, **kwargs) def __str__(self): return str(self.name) The problem is when I try to create a new UserExercise from a dropdown form containing the choices in Exercise, I can't get the exercise name to be any other than None. if request.method == 'POST': name = request.POST.get('name' 'False') quantity = request.POST['quantity'] calories_burned = request.POST['calories_burned'] exercise = UserExercise.objects.create(person_of=request.user, name=name, quantity=quantity, calories_burned=calories_burned) -
update context in get_context_data
Hi I am trying to use get_context_data succesively by lazy_reverse the page. def get_context_data(self, **kwargs): context = super(PublicationCreate, self).get_context_data(**kwargs) context['files'] = UploadedFile.objects.filter(pk=self.kwargs['pk']) return context How do I save the queryset and concatenate it later on? -
Product Variations in Django: How to handle variant combinations?
I want to implement product variants for size and color. My desired output is: Product #1: Size: Medium, Color: White - Price $10.99 Product #1: Size: Large, Color: White - Price $11.99 Product #1: Size: Medium, Color: Black - Price $11.50 How can I combine color and size into one variant for customers to select. This is the issue I'm dealing it. Eventually, I'll Use Ajax to disable the selected color and size labels that aren't a variant combination. Here are my Models class Products(models.Model): product = models.CharField(max_length=120) created = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Color(models.Model): name = models.CharField(max_length=24) def __str__(self): return str(self.name) class Size(models.Model): name = models.CharField(max_length=24) def __str__(self): return str(self.name) class VariantProduct(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) name = models.CharField(max_length=256) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.PositiveIntegerField(default=0) active = models.BooleanField(default=True) def __str__(self): return str(self.color).upper() + ', ' + str(self.size) + ' - ' + str(self.product).capitalize() class Meta: verbose_name_plural ='Variant Products' HTML {% for product_variation in product_variations %} <input type="radio" name="color-radio" id="color-{{ product_variation.color }}" value="{{ product_variation.color }}"> <label style="background-color:{{ product_variation.color }};" for="color-{{ product_variation.color }}"></label> {% endfor %} {% for product_variation in product_variations %} <input type="radio" name="size-radio" id="size-{{ product_variation.size }}" value="{{ product_variation.size }}"> … -
Django Quiz App, getting previous question
I am trying to create a quiz portal and learning on the go. I am using https://github.com/tomwalker/django_quiz/ as a starting point and adding features on top that. I wanted to add a feature to get previous questions, so I added a button <form action="" method="POST" class="shadow p-4 mb-4 bg" id="question-form"> {% csrf_token %} <input type="hidden" id="duration" value="{{quiz.durationtest}}"> <input type="hidden" id="quizid" value="{{quiz.id}}"> {% if progress %} <input id="currnumb" type="hidden" value ="{{ progress.0|add:1 }}"> <input id="totalques" type="hidden" value ="{{ progress.1 }}"> <div class="countdown float-right" style="font-weight:900; font-size:16px;"></div> <p class="lead">{% trans "Question" %} {{ progress.0|add:1 }} {% trans "of" %} {{ progress.1 }}</p> {% if question.questionmarks %} <p class="lead"><strong>Marks: {{question.questionmarks}}</strong></p> {% endif %} <div class="progress mb-5"> <div class="progress-bar" id ="progress-bar" role="progressbar" > </div> </div> {% endif %} {% if question.figure %} <img src="{{ question.figure.url }}" alt="{{ question.content }}" /> {% endif %} <input type=hidden name="question_id" value="{{ question.id }}" class="question_id"> <div class="row"> <div class="col-md-12 column " oncontextmenu="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false " ondragstart="return false" onselectstart="return false"> <div class="panel panel-primary"> <div class="panel-heading "> <h3 class="panel-title mb-3" style="pointer-events: none;" > {% autoescape off %}{{ question.content }}{% endautoescape %} </h3> </div> <div class="panel-body "> <ul class="list-group"> {% for answer in form.answers %} <li class="list-group-item quiz-answers"> …