Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profile "relation username slug" alternative
I'm using a profile system as each user can see. I'm looking for an alternative. Because if a user register from FB or Google he always has "." in username. So if I want to reach his profile with slug I got a 404 error. Because username != slug. Do you have any idea? In my UserProfile I got unique slug for each user. def userpublicpostview(request, slug): userid = get_object_or_404(User.objects.select_related('userprofile'), username=slug) posts = Post.objects.filter(author_id=userid.id) comments = Comment.objects.filter(user_id=userid.id) pictures = Picture.objects.filter(user_id=userid.id) story = Story.objects.order_by('-created_on').all() return render(request, 'user_public_profile.html', { 'user_posts': posts, 'current_user': userid, 'user_comments': comments, 'user_pictures': pictures, 'story': story, }) -
How do I fix the NoReverseMatch Django error?
I am trying to complete a CS50 Project, I want to render a HTML page, the template is in respective templates/encyclopedia directory. The error page for url 127.0.0.1:8000/wiki/HTML says NoReverseMatch at wiki/HTML. Reverse for 'edit' not found. 'edit' is not a valid view function or pattern name. The responsible URLS.py are "wiki/<str:search>" and "wiki/random". I'm sorry but I don't want to post this long code here but I am stuck at this problem for weeks now. I have tried many ways don't know what's wrong with this code. The below is my URLS.py, the projects index url includes the below urls: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/newpage", views.newpage, name="newpage"), # path("wiki/<str:edit>/edit", views.edit, name="edit"), path("wiki/random", views.random, name="random"), path("wiki/<str:search>", views.search, name="search"), path("wiki/", views.find, name="find") ] The below is my VIEWS.py: from django.shortcuts import render, redirect from django.contrib import messages import markdown2 as md from . import util from django import forms import re, random as rand def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def search(request, search): if search in util.list_entries(): html = md.markdown(util.get_entry(search)) return render(request, "encyclopedia/search.html", { "search": search, "html": html }) else: return render(request, "encyclopedia/error.html") def random(request): randomPage = rand.choice(util.list_entries()) … -
How to fix inconsistent migration history after cloning application from GitHub
I am using the book 'Django for Beginners' to learn Django. I cloned a repository from GitHub containing code for a website that simply allows users to create an account, log in and log out. This is the repository: https://github.com/wsvincent/djangoforbeginners/tree/master/ch10-bootstrap My goal is to use this website, be able to create an account and log in and log out with it. I entered the folder and ran these commands in the terminal: pipenv shell pipenv install python manage.py runserver This was the output in the terminal: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 05, 2020 - 12:58:48 Django version 3.1, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I tried to create an account in the website, it gave the following error: OperationalError at /accounts/signup/ no such table: accounts_customuser To fix this I tried running the following commands: python manage.py makemigrations python manage.py migrate It was successful and gave this output: No changes detected Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. However, when I try to create an account, it still gives the same error: … -
Django queryset filter with iregex returns all objects even if filter condition is not matched
I need to query database to get list of users based on case insensitive regex search of emails. User.objects.filter(email__iregex=f'({"|".join(emails)})') Here emails is a list containing email ids of users. When emails is an empty list the above returns all users from the database. I am unable to figure out why this is occuring? Ideally when emails is empty list, empty queryset should be returned. Can somebody tell me what is wrong with above code. -
Where do I Start for create a Full-Stack web aplication Project?
I'm thinking of creating a queue where there will be a user login stored in the sqlite3 database. And somehow use the queue data Structure for this project, my emphasis is to practice the queue data structure and the association with the Django framework.(i'm using python 3.6.9 and django 3.1.1) -
Why does my form receive this error, when I press the save button many times, of my form?
use Django y Python, can you help me, I have a question. I have a form, my intention is to do the testing process, and I realized, when I press the save button many times, the page is loading and in 1 minute it responds and in the console it gives the following error. ¿Is there a way to prevent the user from pressing the save button on the form x number of times? By JS or other method ?. View.py @login_required(login_url="iniciar_sesion") def save_evento(request, interno, ): params = Parameters(request) if request.POST: nombre_completo = None responsabilidad = request.POST.get('responsabilidad') cod_operador = request.POST.get('cod_operador') conductor = None try: if cod_operador == "" : cod_operador = 000 conductor = models.Conductor.objects.get(cod_operador=cod_operador) rut_input_conductor = None except ObjectDoesNotExist as NotFound: conductor = None rut_input_conductor = request.POST.get('rut_input_conductor') tabla = request.POST.get('tabla_reg') graffiti = False if responsabilidad == 'V': if request.POST.get('graffiti'): graffiti = True linea = request.POST.get('tabla_linea') observacion = request.POST.get('observacion') evento = models.Evento( responsabilidad=responsabilidad, cod_operador=cod_operador, conductor=conductor, sin_codigo=rut_input_conductor, tabla=tabla, usuario=params.getUsuario(), bus=models.Bus.objects.get(interno=interno), patio=params.getUsuario().patio, recorrido=linea, graffiti=graffiti ) if evento.save(): print('Evento Guardado Con Exito..!') dano = models.Dano(evento=evento, observacion=observacion) if dano.save(): print('Daño guardado!') if request.FILES.get('foto1'): models.FotoDano(foto=request.FILES.get('foto1'), dano=dano).save() print("Foto 1 guardada para evento: " + str(dano.evento.id)) if request.FILES.get('foto2'): models.FotoDano(foto=request.FILES.get('foto2'), dano=dano).save() print("Foto 2 guardada para evento: " + … -
Get the good Meta for shared news in Django template
I'm trying to share article on social network from my news.html. The news.html {extend layout.html} but on : https://developers.facebook.com/tools/debug/ the og:title, og:description ... are empty how can I send the good meta from the article that user would like to share ? Here the head of my layout.html : {% load static %} {% load compress %} <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]--> <meta name="author" content="YMED SAS"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link rel="shortcut icon" href="{% static 'img/favicon.ico' %}"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto+Slab:100,300,400,400italic,700"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,400,500,700,700italic"> {% block extra_head_tags %} {% endblock %} </head> Here the news.html : {% extends "layout.html" %} {% load static %} {% block content %} <div class="page-title style2 topnews"> <div class="container"> <div class="row"> <div class="col-md-6 col-xs-12"> <h1> <span class="text-white">Actualités</span> </h1> </div> </div> </div> </div> <div class="page-title"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="breadcrumbs"> <div class="breadcrumb-trail"> <a href="{% url 'homepage' %}">Bienvenue</a><span class="sep">/</span> Actualités </div> </div> </div><!-- /.col-md-12 --> </div><!-- /.row --> </div><!-- /.container --> </div> <div class="main-content has-heading"> <div class="container"> {% for new in news %} <div class="row" id="{{ new.id }}" style="border-bottom:2px solid #000000; padding-top:20px; padding-bottom:20px"> {% if new.photo %} <div class="col-md-3"> <img src="{{ new.photo.url }}" alt="photo de {{new.photo.title}}"/> … -
How to make one-to-one chat using django Channels?
I have a django app. I want to add chat functionality in it. So far I've followed the tutorial given in Channels Docs which builds group chats. I want to make the chat ONE-TO-ONE just like facebook messenger so two users can have individual chats. I've been working on this but haven't figured it out yet. So need help. Thanks in advance -
Getting object back in js using AJAX POST
i have a ajax request: const CreateTweet = () => { const tweetContent = document.getElementById("tweet_input_content").value; console.log(tweetContent) $.ajax({ url: "api/tweet-create/", method: "post", dataType: "json", data: { "content": tweetContent } }).done( console.log() ) } There is my view: def validate_tweet(request): obj = request.POST.get("content") print(obj + 'OBJ HERE') import json ctx = { "content": obj, "id": request.user.id, } t = Tweet(content=obj, user=request.user) t.save() return JsonResponse(ctx) And the question is - how can I get already sent data by ajax to the server in my console log? I'm sending the data, and I would like to insert it into HTML if it is correct. -
Django + Graphene, after registering a user, a confirmation letter has arrived in the developer's console. How can I get control of this email?
I am learning Django + Graphene + React(Apollo), after registering a user, a confirmation email has come to the developer console. How can I get control of this email? class AuthMutation(graphene.ObjectType): register = mutations.Register.Field() verify_account = mutations.VerifyAccount.Field() After I send data from the client side, the user is registered, but to confirm it, I have to perform a mutation with the token that comes in the letter. mutation { verifyAccount(token: "YOUR TOKEN FROM LETTER") { success, errors } } Letter <h3>{{ site_name }}</h3> <p>Hello {{ user.username }}!</p> <p>Please activate your account on the link:</p> <p>{{ protocol }}://{{ domain }}/{{ path }}/{{ token }}</p> My goal is to confirm registration via email -
hiding secret key in django project on github after uploading project
I uploaded my django project on github and I have a lot of commits on my project. I don't want to delete my project and reupload it again. what is the easiest way to hide secret key after uploading project to github and after a lot of commits? -
Needing help: Trying to receive a POST request on a django server from an external piece of hardware
okay here is the deal: i'm rather new to this, so i don't know much. I have a piece of hardware, that is connected to my network, and i have a django server running. The hardware is able to send data in a specific typ, like this: $,,,,,*\r\n examples: $GPRP,CCB97E7361A4,CB412F0C8EDC,-49,1309696773206D65736820233220285445535429020106 so what i need is, to receive this information,maybe print it as a first step just for visualization,save it and then and process it. For exmple i need to have three of these hardware pieces and take every RSSI-value of them, and calculate with them, to get a new information out of it. The problem is, i dont know how to write that code, and i dont know what i should search for exactly to solve my problem. Maybe some of you can help! -
Making webpage hit count/trending section for blog
I am trying to make this simple feature of sorting by the most viewed articles in the last 24 hours. I did this by saving the timestamp every time the webpage gets a request. Now the most "trending" article is the one that has maximum timestamps saved in T-24 hours. However, I don't think that this is the right way to do it as the list keeps getting bigger, and it must be slowing down the webpages (which will become noticeable after a critical number of views). [I'm using Django] -
How to update a specific manytomany field in django
My Area model has an exercise attribute with a ManyToManyField to my Exercise model: class Area(models.Model): name = models.CharField(max_length=100) exercise = models.ManyToManyField(Exercise) class Exercise(models.Model): name = models.CharField(max_length=100) My AreaView displays a list of areas, which each link to their own list of specific exercises, shown by AreaDetailView: class AreaView(ListView): model = Area template_name = 'workouts/areas.html' class AreaDetailView(DetailView): model = Area template_name = 'workouts/exercises.html' def get_context_data(self, **kwargs): context = super(AreaDetailView, self).get_context_data(**kwargs) context['e_form'] = AddExerciseForm return context e.g: areas.html - abs - biceps - cardio - legs ... exercises.html Abs - Ab-wheel - Cable-crunch - Plank ... Biceps - Barbell curl - Cable curl - Dumbbell curl AreaDetailView also displays a form which I would like to allow the user to create their own exercises, which will be specific to their corresponding area. Here is my form: class AddExerciseForm(forms.ModelForm): class Meta: model = Exercise fields = ['name'] My template: <form action="{% url 'exercise_add_new' %}" method="post"> {% csrf_token %} {{ e_form }} <button type="submit">Save changes</button> </form> My url: path('exercise-add-new', ExerciseFormView.as_view(), name='exercise_add_new'), And my attempt at building the logic: class ExerciseFormView(CreateView): form_class = AddExerciseForm success_url = '/' def form_valid(self, form): form.save() area = Area(id=self.kwargs['id']) area.exercise.add(form) area.save() return super(ExerciseFormView, self).form_valid(form) My form is being displayed … -
In Django, how can the Graphene GraphQL endpoint be protected for API usage?
Graphene provides a GraphQL integration into Django and supplies a view to create a URL endpoint. The question is how can the endpoint be protected for API usage? The recommend method is to use a LoginRequiredMixin which is great for logged in users, but not for use as an API. I've tried integrating it with DRF tokens, but still end up with the session middleware requiring CSRF. The only solution that works is adding a CSRF exempt decorator, but I fear that this opens up a security vulnerability. # urls.py path("graphiql/", root_views.SessionGraphQLView.as_view(graphiql=True), name="graphiql"), path("graphql/", root_views.TokenGraphQLView.as_view(graphiql=False), name="graphql"), # views.py class TokenLoginRequiredMixin(AccessMixin): """A login required mixin that allows token authentication.""" def dispatch(self, request, *args, **kwargs): """If token was provided, ignore authenticated status.""" http_auth = request.META.get("HTTP_AUTHORIZATION") if http_auth and "Token" in http_auth: pass elif not request.user.is_authenticated: return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) @method_decorator(csrf_exempt, name="dispatch") class TokenGraphQLView(TokenLoginRequiredMixin, GraphQLView): authentication_classes = [TokenAuthentication] class SessionGraphQLView(LoginRequiredMixin, GraphQLView): pass -
Django modelform not saving
I've had a google, a look through the other topics on here too. Still my form isn't saving. View def newapprentice(request): form = NewApprenticeForm() if request.method == 'POST': #print('Printing POST:', request.POST) form = NewApprenticeForm(request.POST) if form.is_valid(): form.save() return redirect('apprentices/index.html') return render(request, 'apprentices/newapprentice.html', {'form': form}) Template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>New Apprentice</h1> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.email|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.role|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.cost|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.p_name|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.p_time|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.division|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.line_manager|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.on_course|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.finished_course|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.left_course|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.finish_date|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.notes|as_crispy_field }} </div> </div> <button … -
Can I use Django and HTML extensions at the same time in VSCcode?
I recently started learning Django and when I am writing templates, I have to switch between HTML and Django HTML extensions to use the tab for autocompletion. With the HTML extension, I can autocomplete the tags using the tab but when Django HTML is in use, it does not work anymore and have to write all the tags manually. Switching between the two is also frustrating, and sticking with the HTML extension means writing the Django syntax (eg. loops, if, and so on) manually also. Is there any extension that provides this? Or is there any way to use both at the same time? If not, even a quick shortcut for switching between the two would help. Thanks. -
Append data in select (option) got from server
I am trying to append the data got from Server via AJAX task in the select options but whenever the append function get executed by clicking the select Button(Day) each time the data get appended like this: 1, 2 ,3.... 1, 2, 3 Means the same data gets appended multiple times. <div class="form-group col-sm-3 d-inline-block" style="padding: 0px;"> <select class="form-control" id="Day" name='day' onclick="get_max_np_date()"> <option disabled selected>Day</option> <script> var max_day; function get_max_np_date() { //Return the maximum Days in Nepali Date System (Bikram Sambat) var get_year = document.getElementById('Year') var get_month = document.getElementById('Month'); year = get_year.options[get_year.selectedIndex].value; month = get_month.options[get_month.selectedIndex].value; console.log(Boolean(year && month)); if (year && month){ $.ajax({ url: 'max-np-day', type: 'get', data: { 'year':year, 'month':month }, success: function (data) { max_day = data; var days; DayElm = document.getElementById("Day") for (days = 1; days <= max_day; days++) { var optionElm = document.createElement("option"); //optionElm.value = days; var daysNode = document.createTextNode(days); optionElm.appendChild(daysNode) DayElm.appendChild(optionElm) } // var node = document.createElement("LI"); //var textnode = document.createTextNode("Water"); /// node.appendChild(textnode); //document.getElementById("myList").appendChild(node); } }) } }; </script> </div> -
Set the ROOT URL for Django Application in Apache
Running my Django App in localhost, working absolutely fine. But as I hosted it on Apache, the url got set to 10.5.10.28/myportal/ and when I try to click a button to switch to another page its taking URL as 10.5.10.28/list which is not found. It should take 10.5.10.28/myportal/list/ to work fine. Or 10.5.10.28/myportal/add/ or 10.5.10.28/myportal/search/ I want 10.5.10.28/myportal/ to be my root URL and rest path should switch after this. from django.urls import path from Device import views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.main_page, name='main'), path('list/', views.list_system, name='list'), path('listdevice/', views.list_device, name='listDevice'), path('search/', views.search, name='search'), path('searchresult/', views.searchresult, name='searchresult'), path('add/', views.add, name='add'), path('addalert/', views.addalert, name='addalert'), # path('delsys/', views.delsys, name='delsys'), # path('deldev/', views.deldev, name='deldev'), path('delmsg/<str:sysin>/<str:sys>/', views.delmsg, name='delmsg'), path('update/<str:sysin>/<str:sys>/', views.update, name='update'), path('updatemsg/<str:dev>/', views.updatemsg, name='updatemsg') ] -
How to add length of 2 lists which has dictionaries it it in Django
I have two lists, both the lists are having number of dictionaries. eg.: list_one = [{"key1": "value"}, {"key1": "value"}] list_two = [{"key2": "value"}, {"key2": "value"}] I want to add length of these two lists in django template tag, so the output will be 4 in this case. I have tried with below but couldn't make it. {{ list_one|length|add:list_2|length }} Please help. -
(venv) (base) both active on a python project
So I am using vscode with conda (for a django project), and trying to activate my virtual environment named "venv". And it goes from: (base) C:\Users\User\Desktop\pfa-master\pfa-master\venv\Scripts> .\activate to something like this: (venv) (base) C:\Users\User\Desktop\pfa-master\pfa-master\venv\Scripts> And if I try to find out Python version, it shows error like this: (venv) (base) C:\Users\User\Desktop\pfa-master\pfa-master>which python 'which' is not recognized as an internal or external command, operable program or batch file. Note: I have Python in environment variables for anaconda. What am I doing wrong? -
pass a parameter from view to context_processors
I have the following structure polls / context_processors.py: def link_list(request,link): link = link data = Page.objects.filter(link=link) return {'link':data} polls / views.py: ... content = { 'content':content } link = request.POST["link"] template = loader.get_template('pages/pages.html') response = HttpResponse(template.render(content , request)) return response what I want to do is to send a parameter from views( might set for each page depending on certain scenario) and and I want to pass this parameter to context_processors. is this possible ? -
when user reply to a comment it is showing time of comment. It should show actual time. How can I fix?
I am learning django. I am working on a blog. When user reply to a comment it is showing time of its parent comment. It should show actual time of reply. I attached a picture with this post.Please have a look , you will better understand my question. How can I fix? I tried but all in vain. may be it is a silly mistake from me or i am not getting it. Thanks in advance view.py def blogPost(request, slug): post = Post.objects.filter(slug=slug).first() comments = BlogComment.objects.filter(post=post, parent=None) replies = BlogComment.objects.filter(post=post).exclude(parent=None) replyDict = {} for reply in replies: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno] = [reply] else: replyDict[reply.parent.sno].append(reply) context = {'post':post, 'comments':comments, 'user': request.user, 'replyDict': replyDict} return render(request, 'blog/blogPost.html',context) def postComments(request): if request.method == 'POST': comment = request.POST.get('comment') user = request.user postSno = request.POST.get('postSno') post = Post.objects.get(sno=postSno) parentSno = request.POST.get('parentSno') if parentSno == "": comments = BlogComment(comment=comment, user=user, post=post) comments.save() messages.success(request, 'Your Comment has been posted Successfully') else: parent = BlogComment.objects.get(sno=parentSno) comments = BlogComment(comment=comment, user=user, post=post, parent=parent) comments.save() messages.success(request, 'Your reply has been posted Successfully') return redirect(f"/blog/{post.slug}") models.py class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField(max_length=10000) author = models.CharField(max_length=20) region = models.CharField(max_length=20) slug = models.CharField(max_length=50, default="") timestamp = … -
DRF not getting ImageField data
I am trying to update the post. #urls.py postdetail = BlogPostDetailView.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) path('<slug>/edit', postdetail, name='postdetail') #views.py class BlogPostDetailView(viewsets.ModelViewSet): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) #serializers.py class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ('id', 'title', 'slug', 'category', 'thumbnail', 'content', 'date_created', 'author') lookup_field = 'slug' when I go to url to update a post, it shows thumbnail field empty " No file selected". Why it is not showing anything in thumbnail? -
Link back to main app ( path `/` ) from Sphinx docs
I'd like to link back to the main django app from theh sphinx documentation. Main app is hosted at root / Sphinx docs hosted at /docs Nginx serving app, docs and static files All configured in Docker w/ docker-compose Ideally, the link back should extend the small "menu" in the top right, so that instead of: (previous |) (next |) modules | index It would say : (previous |) (next |) modules | index | main app And link back to / for the main app link. Been having problems both adding the link, and then I've simply no idea how to force it where I want it even if I can. I tried this just above toctree, but nothing shows up: MainApp: MainApp_ .. _MainApp: /