Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add item in django relation table created with manyToMany relation
Is possible to interact with a table created automatically by Django using manyToMany relation? I have a table that contains an user_id and an article_id, and i want to add a new article using a web form. This table has been created without using a User model (i used the ones provided by Django, so i've not created a new ones). The problem is that i don't want to create a new table for User nor for the relation. Is it possible? -
I'm not being able to access app front-end/login page
I'm a student learning Web app development. I have designed an app using Python-Django framework. Very simple, it is supposed to be a bookings/event management platform for a university, and staff and student should be able to login to their accounts and have specific permissions. Everything is OK, except I can access the admin page and login as staff, but I am unable to find the login page for a student. As in, the only page I am being able to access when I runserver, is Django Administration. I guess I need to add views/url but im not being able to figure out where/what to add. Sounds pretty simple for you pros out here. Here's what my directory looks like - [1]: [https://i.stack.imgur.com/E6hGZ.jpg][1] Here's the urls.py code - from django.contrib import admin from django.conf.urls import include, url __author__ = 'rs' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('NDEvents_api.urls', namespace='api')) ] -
How to Modify user input using Class Based Views in Django
I'm currently using generic class based views. Basically, I am trying to learn how to modify the user input, for instance make the user's input a negative number so I would think something like, fields = ['tname', 'recipient', 'amount'*(-1), 'date'] to modify the amount, or in the future I would like to be able to do amount*2.735 That doesn't work but regardless I'm not sure exactly which type of feature to utilize in Django or the best way to go about this. Here is my current class based view class TranCreateView(LoginRequiredMixin, CreateView): model = transactions success_url = '/users/tactionslist' fields = ['tname', 'recipient', 'amount', 'date'] def form_valid(self, form): form.instance.user_id = self.request.user return super().form_valid(form) The 'amount' is a DecimalField in the models. -
How to access a logged in user from a class based view?
How do I access a current logged in user from a class based view?. In a function view we can pass a request parameter but I can't pass a request parameter from a class view. I have seen ways to do it in the internet but I can't understand it. my models.py file class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=3500) category = models.CharField(max_length=255, default="uncategorized") views.py class HomeView(ListView, LoginRequiredMixin): model = Post template_name = "home.html" Thank you. -
trying to import a module in pycharm wouldnt work
from django.contrib import admin from generator import views when i import it gives me a Module not found error but the module file is in the same file. enter image description here -
Remove a part of string by Regex
I wanna Remove 'amp;' by Regex from this url https://pps.whatsapp.net/v/t61.24694-24/85536857_551478115508757_7310509839538811257_n.jpg?oh=e4b2c87c9691a84ee08e39dc674ea0c4&**amp;**oe=5FBBA259 Can You help me? -
Email body is showing html code in place of template in django
I am sending email using smtp in django but its showing its HTML code. Here is my django view and template view.py current_site = get_current_site(request) mail_subject = 'Activate Your Account' mail_message = render_to_string('mail_body.html', { 'user' : user, 'domain' : current_site.domain, 'uid' : urlsafe_base64_encode(force_bytes(user.pk)), 'token' : default_token_generator.make_token(user) }) mail_to = email, email = EmailMessage( mail_subject, mail_message, to = mail_to ) email.send() mail_body.html <div> {% autoescape off %} <b class="text-center">Hello {{ user.username }}</b><br> Please click on the link below to verify your email address and complete your registration. <a class="btn btn-primary btn-block" href="http://{{ domain }}{% url 'auth' uidb64=uid token=token %}" role="button" target="_blank">Verify</a> <hr /> <br /> If you think, it's not you, then just ignore this email. {% endautoescape %} </div> -
Django how to automatically generate username when registering user via email?
Currently in my Django application users register and login with their email. When a user registers, they don't specify a username in addition to registering their email. Since I want to make profile pages, I figured the best way to do this was to automatically generate a string of numbers to represent a "username" that would link to the individual's profile page during the create_user() method. Here is my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager import random class AccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), username=str(random.randint(1,9999)) + str(random.randint(1,9999))) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=63, unique=True) username = models.CharField(verbose_name="username", max_length=15, unique=True, blank=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(verbose_name="first name", max_length=31, blank=True) last_name = models.CharField(verbose_name="last name", max_length=31, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = AccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): … -
Django issue playing audio files
I am using Javascript in a Django project to make an audio player/visualiser but I am having the problem that when the link is clicked it is showing a 404 error, and that the current path is not in the project .urls. I have tried to add a path but not been able to get it to work, and below is the JS I have used to create the audio player. I am new to Django so any help would be brilliant, thanks. export default class AudioPlayer { constructor(selector = '.audioPlayer', audio = []) { this.playerElement = document.querySelector(selector); this.audio = audio; this.currentAudio = null; this.createPlayerElements(); this.audioContext = null; } createVisualiser() { this.audioContext = new AudioContext(); const src = this.audioContext.createMediaElementSource(this.audioElement); const analyser = this.audioContext.createAnalyser(); const canvas = this.visualiserElement; const ctx = canvas.getContext('2d'); src.connect(analyser); analyser.connect(this.audioContext.destination); analyser.fftSize = 128; const bufferLength = analyser.frequencyBinCount; const dataArray = new Uint8Array(bufferLength); const barWidth = (canvas.width / bufferLength) * 2.5; let barHeight; let bar; function renderFrame() { requestAnimationFrame(renderFrame); bar = 0; analyser.getByteFrequencyData(dataArray); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < bufferLength; i++) { barHeight = dataArray[i] - 100; const r = barHeight + (50 * (i / bufferLength)); ctx.fillStyle = `rgb(${r}, … -
create a list of nested dictionnaries in python
I want to create a list of parent, children object. My object is like that in my model: class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) group_name = models.CharField(max_length=100, null=False, blank=False, unique=True) My code is : # Logic for tree view with child and grandchild treeList = [] groups = Group.objects.order_by('groupParent_id') print (groups.query) for item in groups: # there is no parent. item is on 1st level of tree e = dict() e['key']=item.pk e['value']=item.group_name if item.groupParent_id is None: treeList.append(e) else: parent = item.groupParent_id.pk testParent = find_in_list_of_list(treeList,parent) treeList[testParent].append(e) I've a function but not sure it will works well when I will have to digg in more than one level of parent... def find_in_list_of_list(mylist, char): return next((i for i, item in enumerate(mylist) if item["key"] == char), None) at the end I would like a list like that: treeList = [ {'key':1,'value':rdtd}, [ {'key':32,'value':sdr}, [{'key':34,'value':fds}, {'key':45,'value':gtq}, {'key':4,'value':non}], {'key':12,'value':fgr}, [{'key':3,'value':dfr}, {'key':52,'value':ghvc}], {'key':100,'value':vte}, [{'key':46,'value':err}, {'key':76,'value':test}, {'key':200,'value':non}] ], {'key':265,'value':patate}, [{'key':456,'value':choux}, {'key':67,'value':bluet}, '{'key':9,'value':non23}] ] There is a undefined level of nested dict. At the end i will a tree view of multi level. thanks -
Is this good practice to save children object in "save" method of parent object?
If have two models called Company and Implantation. Obviously, a company can have multiple implantations , hence a ForeignKey field in Implantation class. There is a french API which will help gathering fields for companies. So I define a clean method for Company which is querying the API. This same call will also return information about the company's implantations. I'm thinking "why not create (and save) implantation's while saving the company ?". I may be able to achieve this using an atomic transaction within the save method of Company. So far, I've managed something like this (not entirely tested though...) : from django.db import models, transaction import requests class Company(models.Model): #this is the french "official" key of any company : siren = models.CharField("Numéro SIREN", max_length=9, blank=True, unique=True) #this is a field which can be found on the french API denomination = models.CharField("Dénomination", max_length=150, blank=True) def clean(self): if self.siren: #call to the french API s = requests.Session() r = s.get("https://entreprise.data.gouv.fr/api/sirene/v3/unites_legales/"+self.siren) if r.status_code: #'unite_legale' translates (here) to 'company' self.denomination = r.json()['unite_legale']['denomination'] #'unite_legale' translates (here) to 'implantation' self.implantations = r.json()['unite_legale']['etablissements'] def save(self, *args, **kwargs): self.clean() with transaction.atomic(): super().save(*args, **kwargs) for implantation in self.implantations: implantation = Implantation(etab['siret']) implantation.save() class Implantation(models.Model): #this is the french … -
why this is showing undefined variable request
from django.shortcuts import render,redirect from F_UI import models def blocks(): if request.method=="GET": return render(request,"blocks.html") -
How do I use a django url inside of an option tag in a dropdown menu?
I have a select tag with two options. I want the url to change based on the option selected. I want the url defined in URLPATTERNS in django to be linked to these options. My html: <select name="rec-type" id="rec-type"> <!-- <a href="{% url 'transactions' rec_type='expense' %}"> --> <option value="expense">Expense</option> <!-- </a> --> <!-- <a href="{% url 'transactions' rec_type='expense' %}"> --> <option value="income">Income</option> <!-- </a> --> </select> My url for transactions is : path('transactions/<str:rec_type>', views.transactions, name='transactions'), -
Perform database query in Django channels
I'm trying to create a very simple system where an user, in order to use a consumer, needs to input a key in the WS url, like : ws://127.0.0.1:8000/main?key=KEY. Once the consumer is called, Django Channels needs to perform a very simple DB query to check if the key exists: class TestConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): ... key_query = await database_sync_to_async(keys.objects.get(key=key)) ... But the problem with this code is that it will give the following error: You cannot call this from an async context - use a thread or sync_to_async. Is there any way to accomplish this? Any advice is appreciated! -
Django in a container (using runserver) and postgresql in localhost: app not display
I try to configure my dev environment like this: Django web app in a Docker container and running using runserver (django web server) Connect to Postgresql database locally (Windows) But even if all seems to be OK it doesn't works web app connect to postgresql database and create tables and if I run ````docker logs coverage-africa-on-docker_web_1``` I got Starting development server at http://0.0.0.0:8080/ Quit the server with CONTROL-C. when I try to access web app on url http://0.0.0.0:8080/ it failed (and with localhost:8080 I got this page (below): -
Django Channels throwing me a strange error
I am having troubles with sockets' framework for Django(Channels). I am using the latest version, 3.0.2. I've been using it in my several projects, but now I am getting a very strange, improperly described error. Here you can see my global routing config: application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter(routing.urlpatterns), ), }) And local app routing config: urlpatterns = [path("signup/", consumers.SignUpWebsocketConsumer.as_asgi())] Consumer is a totally default consumer realization: class SignUpWebsocketConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass My app loads completely fine: HTTP/2 support enabled HTTP/2 support enabled Configuring endpoint tcp:port=8000:interface=127.0.0.1 Configuring endpoint tcp:port=8000:interface=127.0.0.1 Listening on TCP address 127.0.0.1:8000 Listening on TCP address 127.0.0.1:8000 The problem occurs when my client try to reach socket. I am getting this error: socket.gaierror: [Errno -3] Temporary failure in name resolution I have been trying overcoming this problem for about 2 days, and still don't know, what cause this problem. Hope, that somebody here know something about that :) -
How to response dynamicly set of fields
I'm litter new in Django and I want to know how to dynamically return a set of fields by user type e.g. if user is a Manager so can get all the fileds in the model he requested but if the user is a Clerk they could see just some fields of the model that the manger specified and these set of fields are in a table for updating in the future. -
How to add a spefici template to buil-in Login system in django
I can't find anything about how I can add my personal custom template for my login page to the built-in Login system in django. I've tried to make a login view function to can connect my template with the login system but in this way I can't add login with google and facebook and because of that I can't use that function, but with this classed base view from django I can't handle to add my personal template to this class. Any ideas ? Template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body class="bg-gradient-primary"> <div class="container"> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user"> <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input … -
Django + React Able to create new user in database, but token-auth returns 400 bad request
So I have an app that I'm writing. It's working, for the most part, so far. I only currently have a login and signup setup, with a 'homepage' that just has a logout button and some text on it so I can test. When I do signup, it posts the user to the database, but then I get this: Bad Request Image Here is my Instructor Model: class Instructor(AbstractUser): displayname = models.CharField(max_length=80, blank=True, null=True) email_address = models.EmailField(blank=True, null=True) grade_taught = models.IntegerField(default = 0) room_number = models.IntegerField(default = 0) Serializer(Instructor and with Token): class InstructorSerializer(serializers.ModelSerializer): class Meta: model = models.Instructor fields = [ 'id', 'username', 'email_address', 'displayname', 'grade_taught', 'room_number' ] class InstructorSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only = True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = models.Instructor fields = [ 'token', 'username', 'password', 'email_address', 'displayname', 'grade_taught', 'room_number' ] Related Views: class InstructorList(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): serializer = serializers.InstructorSerializerWithToken(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) class InstructorViewSet(viewsets.ModelViewSet): queryset … -
Heroku Django value too long for type character varying(20)
The Django website is working fine in development, but on Heroku whenever I create a user instance I get this error django.db.utils.DataError: value too long for type character varying(20) from Heroku logs the error occurs at: try: user = User.objects.get(phone_number=phone_number). # It returns an error here except User.DoesNotExist: user = User.objects.create_user( phone_number=phone_number, username=phone_number) # Then another error here my user model looks like this: from phonenumber_field.modelfields import PhoneNumberField class User(AbstractUser): phone_number = PhoneNumberField(unique=True) username = models.CharField(max_length=30) ... bunch of other fields that are not related to the question And the method looks like this (Postman): { "phone_number": "+200000000000" } As I said it works perfectly In development, and in pythonanywhere. but for some reason, it gives this weird error on Heroku. I can make a guess that it's because PA and Dev servers were using a Sqlite3 DB while Heroku uses Postgres. Any idea about how to fix this? Also if using a MySql database will solve the problem are there any docs about how to use it? I'm a newbie to SQL and the only SQL database I worked with was Sqlite3 My settings.py try: import django_heroku django_heroku.settings(locals()). # for some reason when I run python3 manage.py runserver it … -
Dynamic filter and ignore empty value in Django
Does anybody know how can I ignore empty value when filtering data in django. It consumes time if I make a lot of conditions, the only selected item should be retrieve when contain value What I've already tried, but the problem is that my request Post/name from html is not the same value from my database kwargs = {} for field in ["data1", "data2","data3","data4", "data5","data6", "datefrom","dateto" , "data7","data8","data9","data10"]: try: kwargs[field] = request.POST[field] except KeyError: pass Filter_data = Datas.objects.filter(**kwargs) Also I tried this , I know this should not work data1= request.POST.get('data1', None) data2= request.POST.get('data2', None) data3= request.POST.get('data3', None) data4= request.POST.get('data4', None) data5= request.POST.get('data5', None) data6= request.POST.get('data6', None) data7= request.POST.get('data7', None) from= request.POST.get('from', None) to= request.POST.get('to', None) data8= request.POST.get('data8', None) data9= request.POST.get('data9', None) data10= request.POST.get('data10', None) #if one of this value is None: for example value data9 and data10 is empty or None then the rest contain value and when filtering, the data9 and data10 should not be include in filter . I think it should work using `in` Filter_data = Person.objects.filter( sample1 = data1,sample2 = data2 sample3 = data3,sample4 = data4, sample6 = data6,sample7 = data7, datefrom = from,dateto = to, sample8 = data8,sample9 = data9, sample10 = data10 ) … -
Adding Ajax to comments section not Working
I am trying to add Ajax to my comment section to avoid the page refreshing every time a comment is added. So I load the comments section to the post-details.html from new comments.html and followed the implementing Ajax to posts but my problem is that it is not making any effect and the page needs to refresh to show the new comment I have sub-classed Generic DetailView class in views.py and trying to figure out a way to return data in JSON format based on an argument received in the URL. Here's what I have tried doing: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked if self.request.is_ajax(): html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': html}) else: return context But this gave me TypeError as it should be: TypeError: context … -
Django - best approach to generate pdf file with charts and loading bar
my question is not that simple like in the title. First of all on my site I'm uploading a single file, which is Snort/Suricata alert, then it is possible to view some charts with ECharts. I would like to generate PDF file with some data and charts but not from a single file, but all files from a single users. So my questions are: Should I combine multiple files in one or collect data from seperate files ? What's the best package for this task to generate PDF ? (once I used xhtml2pdf but I'm not sure if it's a good option) I know it will take a long time to generate it, so I think about adding loading bar or a spinner, how should it be done ? Using AJAX or anything else ? If you need any of the code just let me know :) The version of Django is 3.1.1 -
image from DRF not loading in react js
My react js app just won't load any image from my DRF. I am suffering quite a while to fix this, but I just can't find a solution. In my react app, I am fetching data from https://randomuser.me/api/?results=20' (mapping the results to "<img.." etc.) and the fetched images are loaded with <img src="https://...." alt='image'> and they are displayed immediately. But when I fetch my DRF api, I get a timeout. <img className='user-avatar-settings' src={ this.state.photo} alt='user-avatar' /> where this.state.photo is https://127.0.0.1:8001/media/user_avatar/user_3.jpg Chrome is saying:127.0.0.1:8001/media/user_avatar/user_3.jpg:1 GET https://127.0.0.1:8001/media/user_avatar/user_3.jpg net::ERR_TIMED_OUT after a little while. *) The first url isn't correct, the second one is. *) When clicking the correct url, the image is not loaded (the click redirects to a new Chrome tab, so I am outside of the app). *) I first need to quit and restart the Django server, afterwards the image is loaded immediately in the Chrome tab - but not inside my react app. Even a GET Request with the image url is running into that timeout. And it's not up to that one specific image. None image from backend /media/ folder is showing up in react js - only that one little "placeholder" image from browser (a mini image). … -
Enable SSO for user authentication in django python project using keycloak as identity broker
I am trying to enable SSO using keycloak as identity broker and Microsoft AD as identity provider(where keycloak will delegate the client's authentication request to AD) in a django python project. Tech stack of application: frontend- React backend - django python For this I am using python-keycloak library in django to communicate with keycloak.What I am able to achieve is : setup a connection with keycloak and get access_token and refresh_token when username and password is provided like this: # Create Keycloak instance self.keycloak = KeycloakOpenID(server_url=self.server_url, client_id=self.client_id, realm_name=self.realm, client_secret_key=self.client_secret_key) # Get WellKnow self.config_well_know = self.keycloak.well_know() # Get Token self.token = self.keycloak.token("user","pwd") # get userinfo self.userInfo = self.keycloak.userinfo(self.token['access_token']) # userinfo returned ok But here i am providing username and password which I should not as I want to enable sso with Microsoft AD(Note: keycloak realm is configured to use Microsoft AD as default IDP) and only username should be sufficient to enable SSO with Microsoft. But it is giving error on passing only username. Question: How to authenticate user from Microsoft AD using keycloak broker and what should be the syntax for the same?