Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can concat strings in Django template?
I'm trying to localize a component with get_current_language and I need to pass the language_code inside a filter: {% get_current_language as LANGUAGE_CODE %} {{ field|set_data:'flatpickr:{"locale": LANGUAGE_CODE}' }} but set_data argument is a string. How I can achieve this? -
TemplateDoesNotExist on Django Site
I am currently coding a webpage using django but there when I run python server, a TemplateDoesNotExist error pops up. Here are my template Django settings: DEBUG = True ALLOWED_HOSTS = ['*'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wiki2.wsgi.application' How do I fix this? -
Does 'Docker-compose build' run pip as root?
I ran docker-compose build as a non-root user from the terminal of my IDE with activated virtual environment. When building the service relative to my Django app, and installing requirements.txt I got the red message warning about the well known dangers of running pip as root, immediately followed by pip installing everything in requirements.txt. Is it safe and normal behavior because it is in a container? I'm new to orchestrator so I'm asking for confirmation. -
Django model filter elements
I have four models as follows: class modelA(models.Model): name = models.CharField(...) class modelB(models.Model): date = models.DateTimeField(...) A = models.ForeignKey(modelA, ...) class modelC(models.Model): email = models.CharField(...) B = models.ForeignKey(modelB, ...) class modelD(models.Model): uid = models.CharField(...) C = models.ForeignKey(modelC) Given modelA element id, I have to filter modelD elements based on that id. But I am not sure about how to do that. I appreciate any ideas! -
Making my Django Endpoint Restricted so that only I can access it
I'm very new to websites. I'm trying to process payments using Stripe in a JS file, and this file is static meaning it is public. I'm trying to take the part that makes an API request with a secret key and move it to the backend and then call the backend to receive the response that comes from using the secret key. However, currently any person is able to make the request, which defeats the purpose of what I am doing. def payment(request): return render(request, 'interface/about.html') def get(self, request, *args, **kwargs): return(HttpResponse("laterthere")) urls.py path('payment', views.payment, name="payment") JS: var resp1 = await fetch('https://url.com/payment', { method: 'GET' }); Is there any way to do this? If suggesting a better direction to go in please do provide resources. -
Writing Integration Test of a Django ListView
How to write an integration test of the following list view in django? I need an example. class HomeView(ListView): model = Donor template_name = 'recipient/home.html' context_object_name = 'donors' paginate_by = 10 def get_queryset(self): form = self.request.GET.get('q') if form: return Donor.objects.filter( Q(name__icontains=form) | Q(location__icontains=form) | Q(sex__icontains=form) | Q(age__icontains=form) | Q(blood_group__icontains=form) ).order_by('id') queryset = Donor.objects.all().order_by('id') return queryset def get_context_data(self, **kwargs): kwargs['q'] = self.request.GET.get('q') return super().get_context_data(**kwargs) -
Django - Get input of Radio buttons in a loop
I need a page for absence control, where there are looped over all users and with each user is displayed 3 radio buttons : present, absent and allowed_absent. After it is filled in for each user, it should be submitted. This is the important part of my code: HTML baksgewijs_attendance.html <form class="createattendance-form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {% for user in users %} {{ user }} <div class="form-group"> <div> {{ form.attendance}} {{ form.attendance.errors }} </div> </div> {% endfor %} <br> <div class="form-group"> <button type="submit" class="btn btn-primary save"> Save absence </button> </div> </form> Models.py class Attendance(models.Model): attendance = models.CharField(max_length=13) forms.py attendance_choices = ( ('absent', 'Afwezig'), ('allowedabsent', 'Geoorloofd afwezig'), ('present', 'Aanwezig'), ) class CreateAttendance(forms.ModelForm): class Meta: model = Attendance fields = ['attendance'] widgets = { 'attendance': forms.RadioSelect(choices=attendance_choices) } views.py def baksgewijs_attendance(request): peloton = Peloton.objects.all() users = User.objects.all() if request.method == "POST": form = CreateAttendance(request.POST, request.FILES) if form.is_valid(): form.save() message = messages.success(request, ("De aanwezigheid is opgeslagen")) return HttpResponseRedirect(reverse("baksgewijs_index"), { "message" : message }) else: return render(request, 'baksgewijs/baksgewijs_attendance.html', {"form": CreateAttendance}) User.objects.all gives all user names. The problem is: in this way I can only select one option in total, while I want to be able to select the absence per … -
Django channel consumer sending message twice to the frontend
I'm trying to build a simple chat application using django channels using simple websocket. it is working fine but when i'm sending message to other user it is appearing twice on both end I think consumer chat method is calling twice. i can't figure out how to solve this issue! group send function I think doing this it is echoing back its user and sending that particular message to other user as well Here is the consumer class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): room_name = data['room_name'] room = Room.objects.filter(room_name=room_name).first() sender = data['from'] receiver = data['to'] sender = User.objects.filter(username=sender)[0] receiver = User.objects.filter(username=receiver)[0] messages = Message.objects.fetch_last_10_messages(room.room_name,sender.id,receiver.id) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): room_name = data['room_name'] room = Room.objects.filter(room_name=room_name).first() sender = data['from'] receiver = data['to'] sender = User.objects.filter(username=sender)[0] receiver = User.objects.filter(username=receiver)[0] message = Message.objects.create( sender=sender, receiver=receiver, room=room, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) room = Room.objects.get_or_create_personal_room(me, other_user) self.room_name = … -
Django doesn't print array variable in template
In my django controller function I get "annotations" of a specific web server from database. For all annotations I build annotationsId, annotationsCode, annotationsName array. They are annotationsId = [1, 2, 3, 4, 5] annotationsCode = ['codicefiscale', 'partitaiva', 'telefono', 'data', 'targa'] annotationsName = ['codice fiscale', 'partita iva', 'telefono', 'data', 'targa'] I pass these arrays to view_process_show_saveandanalize.html through tmplAnnVar. My output is this <li><a class="dropdown-item active" href="#" data-active="1" data-annotation-web-server-id data-annotation-code data-func></a> </li> As you can see microdatas (data-annotation-web-server-id example) don't have a value. def show_results(request): #verifico che L'utente abbia scelto un server di annotazioni isChooseWebServer = False userId = int(request.session['id']) userWebServerDao = UserWebServerDAO() userWebServerRec = userWebServerDao.getUserWebServer(userId) userWebServerRec = userWebServerRec[0] idWebServer = userWebServerRec["web_server_id"] if idWebServer > 0: isChooseWebServer = True isThereAnnotation = False #ottengo la lista delle annotazioni del server scelto dall'utente annotationWebServerDao = AnnotationWebServerDAO() annotations = annotationWebServerDao.getAnnotationsWebServer(idWebServer) if len(annotations) > 0: isThereAnnotation = True annotationsName = [] annotationsCode = [] annotationsId = [] i = 0 for annot in annotations: print(annot) annotationsId.append(annot["annotation_web_server_id"]) annotationsCode.append(annot["annotation_code"]) annotationsName.append(annot["annotation_name"]) i = i + 1 print(annotationsCode) print(annotationsName) print(annotationsId) messageSaveAndAnalize = "" if isChooseWebServer is False: messageSaveAndAnalize = "imposta server annotazioni" elif isThereAnnotation is False: messageSaveAndAnalize = "Non ci sono annotazioni per il server scelto." tmplAnnVar = {} tmplAnnVar["messageSaveAndAnalize"] … -
Make a POST request to a View from a Django static Javascript file
I'm currently making a POST request to my view on Django. I am doing this in my HTML file. Post request: class EventDetailView(DetailView): model = Event def post(self, request, *args, **kwargs): return xyz HTML: <form method="post" onsubmit="return confirm('Confirm?');">... </form> How can I create this post request from a static Javascript file that my HTML file interacts with instead of from the HTML File. Thanks in advance for your help. -
Django and React : [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]
I added the encryption type for the form 'multipart/form-data' same thing in axios call too, but i still get the same error. I have a model like this: class MyModel(models.Model): img = models.ImageField(upload_to='media',blank=False) in views.py: class MyModelView(viewset.ModelViewSet): serializer_class = serializer.MyModelSerializer def post(self,request): data = serializer.MyModelSerializer(data=request.data) print(data.is_valid()) # this is false, means there is an error print(data.errors) #This one will display the error shown in the title of this question if data.is_valid(): img = data.data['img'] return Response('Success') return Response('Fail') in serializer.py: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' in frontend side (React) function ImgComp(){ let [img,setImg] = useState({'image':''} let {image} = img function handleChange(e){ setImg( { ...img,[e.target.name]:e.target.value } ) } function submitForm(e){ e.preventDefault() axios.post('127.0.0.1:8000/mymodelurl/',img,{withCredentials:true,headers:{'Content-Type':'multipart/form-data'}}) return( <div> <form method='post' encType='multipart/form-data' onSubmit = {(e)=>submitForm(e)}> <input type='file' value={image} name='img' onChange={(e)=>handleChange(e)}/> </form> </div> } } if i debug the img i get something like : C:\\fakepath\\img.png any help is appreciated. -
How do I fully authenticate a test user in my test cases with django-two-factor-auth to access OTPRequiredMixin views?
I'm trying to write test cases for my class views that are secure behind django-two-factor-auth OTPRequiredMixin. I'm not sure how to write the setUp function to fully authenticate the user through OTP. I've tried self.client.force_login() but when I try to browse to that url in my test function, I am landing on the "Permission Denied" page that prompts to enable two-factor authentication for the user, instead of the expected url. Permission DeniedThe page you requested, enforces users to verify using two-factor authentication for security reasons. You need to enable these security features in order to access this page.Two-factor authentication is not enabled for your account. Enable two-factor authentication for enhanced account security. Here's an example of one of the class views: class ProjectCreateView(OTPRequiredMixin, CreateView): model = Project template_name = 'project_create.html' fields = ['name', 'description'] And here's an example of my setup and a test: class ProjectTestCase(TestCase): def setUp(self): self.user = get_user_model().objects.create( username='jsmith', first_name='John', last_name='Smith', email='johnsmith@test.com', password='secure' ) [...] self.client.force_login(self.user) def test_project_create(self): response = self.client.post( '/project/create/', {'name': 'Test Project', 'description': 'A basic test project'} ) self.assertEqual(response.status_code, 200) Thanks in advance for your insight and wisdom! -
Is there a way to pass a secret Heroku environment variable in my Django project to a static Javascript file?
I don't have a lot of website experience. I'm trying to get my site up and running. I have a secret environment variable on my Heroku app that I want to pass into a static file. Is there a way to do this securely? I've decided I don't care if bad actors can see the file, I just don't want them seeing the key. -
Second fetch in sequence of two doesn't seem to have access to data returned from first fetch
I want to query a (django) server for an (RESTful) API schema, then use that schema for subsequent list and CRUD operations as may be defined therein. I'm using OpenAPI to autogenerate the schema, server-side. Trying to get a client-side API working was taking too long, so I switched to just using fetch instead. The first fetch hits the endpoint that serves the API schema, and works fine. The problem arises when I try to dereference a string within the returned schema in my second fetch call - this one to retrieve a list of "widget" objects from my server. I found a way past this by simply assigning the string I needed to another const within the same function, then passing this to the second fetch. This works, but I don't understand why I need to do this to be able to use data from the first call. I'm able to reference it by console.logging it. I can see it using the browser's debug console. But, for whatever reason, a reference to anything in the object returned by the first fetch becomes undefined in the second (or any subsequent?) fetch. Can someone who understands javascript internals well explain this, … -
Create superuser without password
I have implemented custom user as follows: class UserManager(BaseUserManager): def _create_user(self, email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields): if not username and (is_superuser or not number or not shop): raise ValueError('Users must have a username') now = timezone.now() email = self.normalize_email(email) user = self.model( username=username, email=email, shop=shop, number=number, is_superuser=is_superuser, total_points=total_points, used_points=used_points, last_login=now, date_joined=now, is_staff=is_staff, **extra_fields ) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(**{'{}__iexact'.format(self.model.USERNAME_FIELD): username}) def create_user(self, email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields): return self._create_user(email, username, shop, number, is_superuser, total_points, used_points, is_staff, **extra_fields) def create_superuser(self, email, username, password=None): user = self.model(email=email, username=username, shop=None, is_superuser=True, total_points=0, used_points=0, is_staff=True) user.is_superuser = True user.is_staff = True user.shop = Shop.objects.create(name="openformat") user.save(using=self._db) return user class AbstractUser(AbstractBaseUser): uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=64, unique=True) email = models.EmailField() number = models.CharField(max_length=20) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(null=True, blank=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] class Meta: abstract = True class User(AbstractUser, PermissionsMixin): shop = models.ForeignKey(Shop, null=False, blank=False, on_delete=models.CASCADE) total_points = models.IntegerField(default=0) used_points = models.IntegerField(default=0) objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.uid) def has_perm(self, perm, obj=None): return self.is_superuser def get_full_name(self): return self.username def get_short_name(self): return self.username def __str__(self): return self.username … -
Django Login form issue
Views.py def Tourist_login(request): if request.method == 'POST': form = Tourist_login_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username,password=password) print(user) if user is not None: login(request,user) messages.success(request,'logged in') return redirect('home') else: messages.error(request,"Invalid login credentials!") return redirect('touristlogin') else: return redirect('touirstlogin') else: form = Tourist_login_form() return render(request,'accounts/tourist_login.html',{'form':form}) In the above code , authenticate function returns none value. But if I'm passing input in form through superuser credentials then it is working fine. I'm not able why is it not taking the username and password passed by the user and only taking superuser username and password. -
Graph_helper.py Send on behalf of another user - Django
I have the following code (graph_helper.py), which I copied when completing the Microsoft Graph - Django. The create_event and create_online_event functions works fine for the logged in user. What I ideally need is rather than the calendar events coming from the logged in user, they come from another shared mailbox they have access to. I have tried adding into additional properties including organiser and isOrganiser but these didnt work. https://docs.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0 I also tried editing the below requests.post in the create_events to include the calendar id I want the invites to come from but still no luck. https://docs.microsoft.com/en-us/graph/outlook-create-event-in-shared-delegated-calendar?tabs=http#code-try-0 requests.post('{0}/me/events'.format(graph_url), headers=headers, data=json.dumps(new_event)) Appreciate any help I can get with this issue. I know I can sign in as the shared account but will be better if I can set this up to allow sending on behalf of the logged in user. Graph_helper.py import requests import json graph_url = 'https://graph.microsoft.com/v1.0' def get_user(token): # Send GET to /me user = requests.get( '{0}/me'.format(graph_url), headers={ 'Authorization': 'Bearer {0}'.format(token) }, params={ '$select': 'displayName,mail,mailboxSettings,userPrincipalName' }) # Return the JSON result return user.json() def get_calendar_events(token, start, end, timezone): # Set headers headers = { 'Authorization': 'Bearer {0}'.format(token), 'Prefer': 'outlook.timezone="{0}"'.format(timezone) } # Configure query parameters to # modify the results … -
Javascript code is not displaying in django
here Javascript code is not displaying in Django. even before I did lot of research on it but unable to find. I really don't know what to do here. please anyone guide me how to do this. This help will be precious for me. static/js/script.js: var bar = new ProgressBar.Circle(container, { color: '#ff0000', // This has to be the same size as the maximum width to // prevent clipping strokeWidth: 4, trailWidth: 1, easing: 'easeInOut', duration: 10000, text: { autoStyleContainer: false }, from: { color: '#ff0000', width: 5 }, to: { color: '#00cc00', width: 9 }, // Set default step function for all animate calls step: function(state, circle) { circle.path.setAttribute('stroke', state.color); circle.path.setAttribute('stroke-width', state.width); var value = Math.round(circle.value() * 100); if (value === 0) { circle.setText(''); } else { circle.setText(value); } } }); bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif'; bar.text.style.fontSize = '2rem'; bar.animate(1.0); // Number from 0.0 to 1.0 html file: <div id="container"></div> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] I'm getting correct output in command prompt but it is not displaying on template. output in cmd: "GET /static/js/script.js HTTP/1.1" 304 0 -
How to make a for loop break on counter in jinja2?
How can I make the for product in products loop break after the if condition is fulfilled 3 times. I have been trying to set up a counter but that isn't working... because set is not accepted inside of for loops. Though testing it out a bit more it isn't being accepted anywhere. When I use set it throws this exception or a variation of it: Invalid block tag on line 11: 'set', expected 'endblock'. Did you forget to register or load this tag? I am aware that I should put all the logic I'm using jinja2 for inside of the view and then pass it through the dictionary but it would take too much time to research everything about that and i just want to be done with this. Honestly I am really tired it is 6am and idk what to do. Thank you for your help in advance. :) HTML {% for category in categories %} <div> <h5 class="text-line"><a href="" class="store-category"><span>{{category.name}}</span></a></h5> </div> <!-- Cards Container --> <div class="shop-cards"> {% set counter = 0 %} {% for product in products %} {% if product.category.categoryID == category.categoryID %} <!-- CARD 1 --> <div class="card"> <image class="product-image" src="{% static 'images/product-4.png' %}"></image> … -
Django Vs Laravel for Web Development
I saw this But I am still confused. I started web development with vanilla PHP and was recently informed about a Python framework Django. So my question is, what's the point and benefit of using Django, PHP is designed directly to plug into a web page, whereas Django goes around the bush, and if you prefer a framework, there is Laravel, but for some reason, PHP is getting disrespected by developers. I understand that Python might be a more simple syntax, so easier to write and read, but is there anything else? And is worth learning Python, just for making web apps? Please trow your opinion and your advice will be very appreciated. Thanks -
Django for loop only parsing first row from json data on html template
I am able to access the entire json data when I make the call to the themoviedb api in the DOM, but when I try to loop/print it as an html template, it only parses the first row of the json object. How do I access the entire search results from the json object? def index(request): post = Show.objects.all().order_by('title') for lists in post: data = requests.get(F"https://api.themoviedb.org/3/search/tv?api_key={api_key}&language=en-US&page=1&include_adult=false&query={lists}") r = data.json() pprint(r) -
where is going data from <select> box
ive wrote a code to practice html and python i used django to build a add music page its for uploading musics the whole form used models and i know wheni i want to save sth its all related together but i added another option today for tags this option is not in form nor models its just in html file so what will happen if i choose and press submit and also if i want to make same in model how should i do {% extends 'pages/base.html' %} {% block content %} <!DOCTYPE html> <head> <meta name="description" content="page of adding music"> <meta name="keywords" content="music,upload_music"> <title>adding music</title> </head> <body> <p>here you can upload music</p> <form action="{% url 'pages:add_music' %}" method='post' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <div> <h3 style="border:2px blue; color:blue;">tags:</h3> <select style="padding: 4px;" id="tags" name="tags" multiple required="required" size='6'> {% for tag in tags %} <option value="{{tag}}">{{tag}}</option> {% endfor %} </select><br> </div> <button type='submit' value="submit" style="margin: 20px; background-color: yellow; color: green;">add</button> </form> </body> {% endblock %} -
Secure way to accept payments on Django Heroku?
I'm trying to accept payments on Django using Heroku. I've had a ton of issues using Stripe because I don't know much about client-side/server-side and every time I get something that works, I have to expose my private key. I feel like there's no resource out there for this. Does anyone have something that can help? -
Django inspectdb lost comment
I use mysql to test model.with django_comment_migrate save help_text to sql comment. Original model.py below: from django.db import models class Foo(models.Model): name = models.CharField(max_length=20, verbose_name='alias_name', help_text='alias_name') Run python manage.py inspectdb got result below, lost help_text. class App1Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20) class Meta: managed = False db_table = 'app1_foo' -
Django class variable to instance variable
It seems like name and tagline would be class variables, how have they managed to define name and tagline as instance variables. Creating an instance of blog would be like Blog(name='...', tagline='...'). Wouldnt the variable be available like so, Blog.name and Blog.tagline class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name