Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to pass URL template tag from database to template in Django?
I apologize if my question is poorly worded. Basically, I am making a database of fictional characters and in the database, I have a biography of the character. I would like to link to other characters using the {% url 'viewname' otherchar.slug %} method. However, all I get back from the database is literally that line of code. I understand it may not be possible, but is there a way to get Django to see that line and turn it into an absolute URL like it would if I manually added the URL tag into the page? Something to add - I am using TinyMCE so the content in the database is being saved with HTML - I want to be able to save external links, subheadings, and whatnot, which is why I chose to use TinyMCE and its HTML field. models.py class Character(models.Model): name = models.CharField(max_length = 255) faction = models.IntegerField(default = 0) rankIMG = models.ImageField(upload_to = 'rankIMG/', blank = True) department = models.IntegerField(default = 0) content = HTMLField() slug = models.SlugField() views.py class CharacterFull(DetailView): model = Character context_object_name = 'character' def get_context_data(self, **kwargs): context = super(CharacterFull, self).get_context_data(**kwargs) context['factionDict'] = charFaction context['deptDict'] = charDepartment return context urls.py app_name = … -
Retrieve Access/Refresh token with username/password from Django REST API
I am trying to build an application on Google AppScript that should communicate with a third-party API. This API uses Django REST Framework and JWT. I have a username and password to access domain/api/token, login and get the access and refresh tokens. I can do this manually but I would like to implement some sort of a login on my application side that will get a new access/refresh (if needed) token from the API so it can start fetching data from the service. My question is, how can I structure the POST request to retrieve the access/refresh token pairs so I can continue with the next requests? This is what I'm trying to do: var formData = { 'async': true, 'crossDomain': true, 'method': 'POST', 'headers': { 'Content-Type': 'application/json', 'username': 'user', 'password': 'secretpassword' }, 'muteHttpExceptions': true } var url = 'domain/api/token' var res = UrlFetchApp.fetch(url, formData); -
Fetching results from a method in Django
My Django app ('crisismode') has two models : Events and Actions I would like to display events and actions related to these events. For each event, I only want to display active actions, so I used a method (activactions). How to prefetch these actions ? class Event(models.Model): description = models.CharField(max_length=1000, blank=True) active = models.BooleanField(default=True) def activeactions(self): actions = Action.objects.filter(event=self, active=True) if actions: return Action.objects.filter(event=self, active=True) else: return None class Action(models.Model): description = models.CharField(max_length=1000) active = models.BooleanField(default=True) event = models.ForeignKey(Event, on_delete=models.SET_NULL, related_name="actionsforevent", null=True, blank=True) I perform the following query: events = Event.objects.filter(crisis=crisis, active=True).prefetch_related('actionsforevent') But django-debug-toolbar shows me that there are multiple queries for it : FROM "crisismode_action" WHERE ("crisismode_action"."active" = true AND "crisismode_action"."event_id" = 323) ORDER BY "crisismode_action"."order" ASC, "crisismode_action"."id" ASC 10 similar queries. Duplicated 2 times. -
Why isn't my image loaded/fetched from AWS RDS in my React application?
So I have my Django Rest Framework deployed with AWS EC2. I also have RDS instance for saving images. Then I have a React application deployed that fetches some objects(including the images) from DRF. Now when I load the page, all the other fields(?) of each object are loaded but the image. I see 404 Not Found error, and have no idea what is going on. I have console.loged and saw the object myself, and the url of the image is just fine. http://ec2-some-address.ap-northeast-2.compute.amazonaws.com/media/None/myimage.jpg. the media/None/ directory is as expected. Any idea? Thanks a lot in advance :) -
Problem with mixing Detail View and Form Mixin django
I am trying to create a comment system for the blog portion of my app with Django. I have attempted to mix my detail view with the form mixin and I'm struggling a bit. When the form is submitted, it doesn't save and no error is present. If any of you can help I would greatly appreciate it. Here is my View class DetailPostView(FormMixin, DetailView): model = Post template_name = "blog/post_detail.html" context_object_name = "posts" form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form"] = CommentForm return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk": self.object.pk}) The model class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created_on"] def __str__(self): return self.title -
Django Find custom user with the same value of JSONfield
I have a django application, where I use custom user model. Model has a JSONfield, which represents which programming languages do this user use. It looks like this: {"langs": [1, 2, 3, 4]} These numbers are ID's of Language DB model. So is it possible to find users in DB, who have 1 or more same language as the current user. I want to get an array with custom user objects sorted by number of matching langs. Sorry if this question is too stupid. -
compress.js made the CACHE directoly under uwsgi not nginx
I am using Django Compressor on nginx & uwsgi I have each docker container for nginx & uwsgi I copied static folder to nginx:/static and others to uwsgi:/myapp/ in advance. However compress.js made the compress file dynamically and set under uwsgi:myapp/static/CACHE of uwsgi container. <script src="/static/CACHE/js/output.b6723c2174c0.js"> So consequently 404 not found for this file, because this request is redirect to nginx:/static not uwsgi:/myapp/static How anyone solves this problem? my nginx setting is below server { listen 8000; server_name 127.0.0.1; charset utf-8; location /static { alias /static; } location / { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://uwsgi:8001/; include /etc/nginx/uwsgi_params; } } -
implement dynamic database models for messenger web app django
i want to create a messenger webapp in django in which a sql table will be created which will only store the conversation of two user . the naive approach is to create a table for messages which will store info like id,message_text,sender,reciever etc. but in case of large user this will not be efficient. if we allot a conversation between two user in a single table then it will reduce the searching time. i dont know how to implement dynamic models . Is there any better approach for this problem? -
CSRF token missing or incorrect in EditorJS and Django
Error: Can not upload an image, try another Forbidden (CSRF token missing or incorrect.): /fileUpload views.py @requires_csrf_token def upload_image_view(request): f = request.FILES['image'] fs = FileSystemStorage() filename = "blog/"+str(f).split('.')[0] file = fs.save(filename, f) fileurl = fs.url(file) return JsonResponse({'success': 1, 'file': {'url': fileurl}}) urls.py path('fileUpload',csrf_exempt(upload_image_view)), -
how to show error messages in django forms?
i want to show an error message if the password and the confirmation doesn't match how can i do this? class Register_form(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'class': '', 'placeholder': 'username'}), max_length=16, label="") gender = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': '', 'placeholder': ''}), choices=GENDER_CHOICES, label="") email = forms.EmailField(widget=forms.EmailInput(attrs={'class': '', 'placeholder': 'email'}), label="") password = forms.CharField(widget=forms.PasswordInput(attrs={'class': '', 'placeholder': 'password', 'minlenght': '8', 'maxlenght': '64'}), label="") confirmation = forms.CharField(widget=forms.PasswordInput(attrs={'class': '', 'placeholder': 'password confirmation', 'minlenght': '8', 'maxlenght': '64'}), label="") error_messages = { 'password_mismatch': 'passwords must match', } def clean_password(self): password = self.cleaned_data['password'] confirmation = self.cleaned_data['confirmation'] if password != confirmation: raise ValidationError( self.error_messages['email_invalid'], code="email_invalid" ) -
RuntimeError: Model class project6.models.Emp doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I declared models.py in project directory. Don't have any apps. If we make the form at project level then its run but when we add that form with database through models then occurs the 'run time error'. "RuntimeError: Model class project6.models.Emp doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." I have tried many times to resolve but not successed. Please resolve this problem All are in projects directory This is my views from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect # from .forms import InputForm from .models import Emp, Man from .forms import ContactForm # Views @login_required def home(request): return render(request, "registration/success.html", {}) def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) def maker(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): emp = form.cleaned_data['emp'] name = form.cleaned_data['name'] email = form.cleaned_data['email'] man = form.cleaned_data['man'] p = Emp.objects.create(emp=emp, name=name, email=email) q = Man.objects.create(man=man) # messages.success(request, 'Form submission successful') return HttpResponseRedirect(request.path_info) return render(request, 'success.html', {'form': form}) THis is my … -
How to get base64 image through selenium (2captcha)?
I need to get the base64 from a captcha image to pass it to a method that solves it. The thing is, how do I manage to do that? This my view but so far I only get an exception from the resolve_simple_captcha function that says: "Error getting the captcha id". The function needs image_base64 to work. This is the code: DRIVER_PATH = 'C:/Users/python/chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('https://seti.afip.gob.ar/padron-puc-constancia-internet/ConsultaConstanciaAction.do') driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) wait = WebDriverWait(driver, 30) elem = wait.until(EC.presence_of_element_located((By.XPATH,"//input[@id='cuit']"))) elem.send_keys(cuit_r) #get catpcha elem2= wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/div/div/div/table/tbody/tr/td/form/table/tbody/tr[3]/td[2]/div/div/div[1]/img"))) img_captcha_base64 = driver.execute_async_script(""" var ele = arguments[0], callback = arguments[1]; ele.addEventListener('load', function fn(){ ele.removeEventListener('load', fn, false); var cnv = document.createElement('canvas'); cnv.width = this.width; cnv.height = this.height; cnv.getContext('2d').drawImage(this, 0, 0); callback(cnv.toDataURL('image/jpeg').substring(22)); }, false); ele.dispatchEvent(new Event('load')); """, elem2) resolve_simple_captcha(img_captcha_base64) elem4 = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@id="btnConsultar"]'))) elem4.click() Basically I have to pass the base64 image to my resolve_simple_captcha method in order to get it solved. How do I do that? This is how the method works: resolve_simple_captcha(image_base64) I got the img_captcha_base64 from another forum and even though the function it's not working well, it finally responds. The function takes these parameters: payload = { 'method':'base64', 'key':"", 'body': image_base64 } -
Want to first save user profile data and then automatically create user
This application is for a school where the admin(through django admin) can upload the student's data and based on that, a user is created ( username is ID and password is dd/mm/yy).Basically removing the need for all the students to register themselves on the platform. I've seen videos where signals are used to create profile from user using post_save() but to create user from profile I can't use that since profile editing is also allowed which will trigger post_save() and try to create a user, even though one already exists for that profile. Any help will be appreciated. Thank you -
How to track monthly subscription usage of user in django?
I have the scenario where I have three models: Subscription Model User Model (Has Subscription Model ForeignKey) Match Model (Has User Model ForeignKey) Users can choose to sign up for 6 month/ 12 month/ 18 month subscriptions where they can have a maximum of 10 matches PER MONTH. Users may start the subscription on any given date of the month. My question is how do I track how many matches are assigned to the user in a given month(with the first date of the month being the date he signed up on)? How do I reset the number of matches back to 10 after every month finishes? -
Django HTML page is showing template code for form as text
I'm pretty new to Django (technically this is written in Django-Mako-Plus), and I'm trying to display a form on an HTML page, but it is displaying the template code as text and I can't figure out why. I've set up my form in forms.py: class FilterForm(forms.Form): def init(self): self.fields['keywords'] = forms.CharField(label='Keywords') self.fields['hours'] = forms.CharField(label='Training Hours') self.fields['instructor'] = forms.CharField(label='Instructor') self.fields['subject'] = forms.CharField(label='Course Subject') self.fields['agegroup'] = forms.CharField(label='Target Age Group') I've added the form to my context variable in the view: from django import forms from .forms import FilterForm @view_function def process_request(request, cat_id:int = None, pnum:int = 1): currentDate = datetime.today() currentYear = currentDate.year #allcourses = hmod.Courses.objects.all() allcourses = hmod.Courses.objects.only("courseid", "coursetitle", "coursephoto", "coursedescription") form = FilterForm() context = { # sent to index.html: 'current_year': currentYear, 'allcourses': allcourses, 'form': form, } return request.dmp.render('courselist.html', context) And I've tried to display the form on the page in the template. <form action="/your-name/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> The problem is, when I go to the page, instead of showing the form, {% csrf_token %} and {{ form.as_p }} show up as text on the page. If anyone knows what the problem is, or can point me to a similar answer, that … -
Is there a dynamic web framework I could use in R that's comparable to Django
I've been using django and python to create a web application and I was wondering if there's any alternatives in R. I have more experience using R and I've made static sites using blogdown and netlify, as well as dashboards using Shiny but I want to know if there's something out there that's similar to django that I can do some research on. -
How to add exception to a dictionary if the result is useless for my data?
So I have this code to get the id of a person and check if the person exists in a database. The code works but I forgot to add an exception for people who exist but their id is not a "useful" one. I tried adding an exception to my code that says: except cuit == "CUIL": print("it's not a cuit") But this is ignored and I get the data anyway even though I don't want it. So what's a better way of doing it? The info is in response["persona"]["tipoClave"] This gives two results: "CUIL" (not useful) and "CUIT" (useful). So how do I prevent the useless ids to be passed as useful? This is the code: class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): form = MonotributoForm(request.POST) email = request.POST['Email'] #Verificar cuit en padron13 una vez que es ingresado cuit_r = int(request.POST["CUIT"]) response = get_persona(cuit_r) try: nombre = response["persona"]["nombre"] apellido = response["persona"]["apellido"] cuit = response["persona"]["tipoClave"] except KeyError: nombre, apellido = None, None print("El CUIT ingresado es incorrecto") except TypeError: nombre, apellido = None, None print("El CUIT ingresado es incorrecto") except cuit == "CUIL": print("it's not a cuit") else: print(nombre, apellido) if form.is_valid(): cuit = form.cleaned_data.get('CUIT') email = … -
VueJS v-for on Django template
I'm using vuejs with typescript on Django template and I'm facing Property or method "ingredient" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property my vue code is like this. export class MyApp extends Vue { constructor(selector) { super(); this.$options.delimiters = ['${', '}']; this.$options.el = '#app'; this.$options.data = { 'ingredients': [{"id": 1, "name": "test"}] } } } my template is like this. <tr @for="obj in ingredients"> ${obj} <-- error </tr> When I just set property and it works with this delimiters. But, when I use v-for and can't get the obj.. -
How to change the template of password-reset-email properly Django
This line of code is responsible from sending an email which contains a password reset link. path('accounts/password-reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), However the email looks completely dull and it is difficult to distinguish important parts while reading. To attract the attention of the user and direct them better I would like to add style to this body of email. It is possible to add custom template to the email by these lines: ... path('accounts/', include('django.contrib.auth.urls')), path('accounts/password-reset/', auth_views.PasswordResetView.as_view(html_email_template_name='registration/password_reset_email.html'), name='password_reset'), ... The thing is the reset-link inside the email consists of a uidb64 value and a token, such as: localhost:8000/password-reset/calculated_uidb64/calculated_token What is the proper way to pass these values to the custom template of password_reset_email.html? -
How to format the output of database to java code in django?
I am working on a project where I am creating a multiple choice quiz on questions relating to Java. I am using Django to do this and I have the display done I just need assistance with the formatting. Does anyone have any ideas to combating this issue? model.py class Questions(models.Model): question = models.CharField(max_length = 3000) questionLevel = models.IntegerField() class Answers(models.Model): answer = models.CharField(max_length = 500) correct = models.BooleanField() answerForQuestion = models.ForeignKey(Questions, on_delete=models.CASCADE) views.py @login_required def sampleQuestions(request): questions = Questions.objects.all() answers = Answers.objects.all() return render(request, 'sampleQuestions.html', {'questions' :questions, 'answers' : answers}) @login_required def sampleComplete(request): return render(request, 'sampleComplete.html') Samplequestions.html {% extends 'home.html' %} {% load crispy_forms_tags %} {% block content %} <div id="questionForm" class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend id="headerForm" class="border-bottom mb-4">Complete your sample quiz! This will generate your level!</legend> {{ form|crispy }} </fieldset> </form> <div id ="displayQuestions" class="question-section"> {% for q in questions %} <table> <tr> <td> {{q.question}}</td> </tr> {% for a in answers %} {% if a.answerForQuestion == q.id%} <tr> <td> <input type="radio" id="{{ a.id }}" value="{{a.answer}}"> {{a.answer}}</td> </tr> {% endif %} {% endfor %} </table> {% endfor %} </div> <button type="submit" class="btn btn-primary">Generate your level</button> </div> {% endblock content %} -
How do I use google's reCaptcha V3 service in my selenium script?
I was given a google code to solve captchas on a website. The thing is, now that I wrote the scraping script, I don't know how I'm supposed to use this code for it to solve me the captcha in my target website (I'm using selenium). I located the element but with my code it just prints "incorrect". So where do I use the method if it's like this?: resolve_simple_captcha(image_base64) Or what do I do with this in my selenium script?: c_data = { 'response': request.POST.get('g-recaptcha-response'), 'secret': "" } resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=c_data) captcha_response = resp.json() if not captcha_response.get('success') or captcha_response.get('score') < 0.6: print("incorrect") else: print("correct") This is my view: from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from .forms import Mon from app.ws_sr_padron import get_persona from app.captcha import resolve_simple_captcha from time import sleep from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): form = Mon(request.POST) email = request.POST['Email'] cuit_r = int(request.POST["CUIT"]) response = get_persona(cuit_r) try: nombre = response["persona"]["nombre"] apellido = response["persona"]["apellido"] except KeyError: nombre, apellido = None, None print("El CUIT ingresado es incorrecto") except TypeError: nombre, apellido … -
Heroku remote ERROR: Could not find a version that satisfies the requirement django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt
I'm updating my heroku by using a django-admin-black==0.0.1, but heroku does find this version. How can I handle this ? remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.1.6 remote: Downloading Django-3.1.6-py3-none-any.whl (7.8 MB) remote: ERROR: Could not find a version that satisfies the requirement django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt (line 4)) (from versions: none) remote: ERROR: No matching distribution found for django-admin-black==0.0.1 (from -r /tmp/build_e45a4b07/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... -
side bar not in the right position using django template
I am trying to create a reddit-like platform. In my base file, there is the header, and then the page is divided into two sessions. Here is what my base looks like: <html> <head> <link rel="stylesheet" href="{% static 'css/reddit.css' %}"> </head> <body class="base-master"> <div class="page-header-container"> <div class="page-header"> <!--more page header stuff> </div> </div> <div class="content-container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> <div class="col-md-4"> {% block sidebar %} {% endblock %} </div> </div> </div> </body> </html> This seems to work pretty fine for most of my html, I have two columns, the left one being much larger while the right one is essentially a side bar. When I applied this template to my post_detail.html, which on the left side is post detailed content + comment session and the right side is supposed to be the same side bar. The side bar doest show up on the right but rather got wrapped to the bottom after the comment session. When i remove the comment session, it seems to be working. The comment session is called into another html, the format looks like this: {% extends 'Reddit_app/base.html' %} {% load humanize %} {% block content %} <div … -
ProgrammingError - Trying to have images appear under multiple categories
I have a model called CarModel and a model called CarModelImage. I want to be able to have images be associated to multiple CarModels. For this I tried using a ManyToManyField. When I visit the admin page for CarModelImage I get the following error. ProgrammingError at /admin/cars/carmodelimage/ Exception Value: column cars_carmodelimage.model_id does not exist Why is it that I can use the many to many in CarModel but not in CarModelImage? Is there a way I can add id to all my models without having to drop the database? class CarModel(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(CarCategory) ... class Meta: verbose_name_plural = "Car Models" def __str__(self): return self.title class CarModelImage(models.Model): timestamp = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='cars/') model = models.ManyToManyField(CarModel) # This is what I had before: model = models.ForeignKey(default=1, on_delete=models.CASCADE, to='cars.CarModel') def filename(self): return basename(self.image.name) class Meta: verbose_name_plural = "Car Model Images" ordering = ["timestamp"] def __str__(self): return self.filename() -
Why is my xpath not working with selenium?
I need to write a script that given the user's input in my website it connects to this page to submit the number and download a file. The thing is, the xpath is not working at all. What am I doing wrong? This is the view (I deleted the parts not relevant to the question): from django.shortcuts import render, HttpResponse import requests from django.views.generic import FormView from time import sleep from selenium import webdriver class ConstanciaInscripcion(FormView): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): form = MonotributoForm(request.POST) email = request.POST['Email'] cuit_r = int(request.POST["CUIT"]) #Selenium script DRIVER_PATH = 'C:/Users/python/chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('https://seti.afip.gob.ar/padron-puc-constancia-internet/ConsultaConstanciaAction.do') driver.implicitly_wait(20) cuit = driver.find_element_by_xpath("//input[@id='cuit']").send_keys(cuit_r) submit = driver.find_element_by_xpath("//input[@id='btnConsultar']").click() return render(request, 'app/constancia-inscripcion.html') The website also has a captcha and I was given a method to deal with it, should I also add the captcha field to a driver.find_element and pass the method there?