Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django reds won't work on windows or in Ubuntu production
I have React-Django application (I am using Django Rest Framework) and I am trying to integrate websockets with the channels & channels-redis package from django. I follow this tutorial along with this video tutorial but I make adjustments based on the former when necesary. I've installed pip install channels pip install channels-redis but redis doesn't seem to work at all for me on my Windows OS On the local server I've got the following configurations: settings.py ASGI_APPLICATION = "mysite.asgi.application" . . . if config('CHANNEL_LAYERS') == 'redis': CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } else: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } asgi.py import os import django from django.conf.urls import url from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trike.settings") from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter # Models from logistics.consumers import OrderConsumer django.setup() application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter([ url(r"^order_update/$", OrderConsumer.as_asgi()), ]) ), }) Orders.js useEffect(() => { let wsStart = 'ws://' if (window.location.protocol === 'https:') { wsStart = 'wss://' } let endpoint = wsStart + window.location.host setSocket(new WebSocket(endpoint+'/order_update/')) }, []); useEffect(() => { console.log(socket) if (socket) { socket.onmessage = … -
React Native App not connecting via WebSocket after publishing it on the Play Store
In my application I have implemented real time application with socket and django channels that I deployed with daphne (ws://api.xxxxx.com). It works perfectly with my react native app in the development mode, where I just connect with javascript code: let socket = new WebSocket(ws://api.xxxxx.com). But the problem was when I published the app on the play store, which I just can't know why it's not connecting since I don't have any log showing the refusal of connection. These are the logs from daphne in the development mode: 1xx.x.x.x.x:45xxx - - [09/Dec/2020:23:27:34] "WSCONNECTING /ws/xxxxx/90/" - - 1xx.x.x.x.x:45xxx - - [09/Dec/2020:23:27:34] "WSCONNECT /ws/xxxxx/90/" - - With the play store version app, the daphne logs are just empty. Can anyone help me on how to solve this? -
Django - Implementing a Simple Search Bar
I'm new to Django and implementing a simple search bar on a site to search for article titles (This is for a class). No matter what I try, when I search for an article name that exists, the homepage just stays exactly the same, and only the URL changes to http://127.0.0.1:8000/?q=Apple. So everything after the ?q= is the title of the article (this one is called Apple). But the page I'm on stays the same and doesn't go to the actual page I'm looking for. I'm at the point where I've now copy and pasted code from other people, from this same assignment, just to see if it would work, and none of it works. I get the same result every time. Therefore I'm wondering if I'm just totally missing something? Maybe the issue is not in views.py or urls.py etc? I'm not really sure. Any help is super appreciated. If the query matches the name of an article entry, the user should be redirected to that entry’s page. Here is one of the examples I tried and all code associated in views.py: class SearchForm(forms.Form): """ Form Class for Search Bar """ title = forms.CharField(label='', widget=forms.TextInput(attrs={ "class": "search", "placeholder": "Search"})) … -
How Can I Associate A Foreign Key Of A Django Class Model Field To A Parent's Class Field
I am creating a question and answer django model where i want to set the correct answer to an option on the same class Essentially I Want To Do Something Like This class Question(models.Model): question = models.CharField(max_length=40) options = models.ManyToManyField('Answer') correct_answer = models.ForeignKey('self.options',on_delete=models.CASCADE) Unfortunately I'm Getting Errors From Django. -
Rtl direction in TinyMce scrambles codesample
my Django-TinyMce direction has turned rtl due to my language and everything looks fine except the code sample plugin which has gotten rtl and scrambles the code. I would appreciate anyone help me figure this out. I want code sample to be ltr while everything else is rtl. Thanks in advance -
Please review my code of my first web app
I wrote my first web app. Please let me know, what should i improve. I want to write as clean code as possible. I will be greatful for any advices. App is about adding and removing tasks from list. Backend written in Django, Frontend in Sass and Javascript. Link to my code on GitHub Link to app on heroku Cheers. -
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?