Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update form: does not conform to the required format, "yyyy-MM-dd"
I am using Django in the backend to save a date that the user inputs. Then later, I want to allow the user to update that date input by bringing them to a new page, showing them the old date input, and allowing them to update it. I am using a datepicker input field for the frontend to easily allow the user to pick a date. After I input my date, and I go to the update page to change it, the datepicker input field on the update page is empty every time. In the console I see The specified value "Jul. 4, 1776" does not conform to the required format, "yyyy-MM-dd". I think the problem is that when I am retrieving the date from the database it is coming in as a different format than the forntend wants it. The date is coming from the backend as Jul. 4, 1776 format and the frontend form needs it in 1776-07-04. I was wondering how I can fix this so both frontend and backend are happy, and the old date inputted by the user is shown in the update page datepicker input field -
I am having issues with my website getting the static files
I am having an issue with my website getting the static files to render for the website and i don't know what the issue might be. I noticed that the static files are working for only the home page and I have a response like this from the terminal. They all share common base files which they use to render. homepage response on the terminal [06/Mar/2021 17:58:34] "GET / HTTP/1.1" 200 19153 [06/Mar/2021 17:58:34] "GET /static/img/logo/logo-new.png HTTP/1.1" 200 9967 [06/Mar/2021 17:58:34] "GET /static/img/icon/icon1.svg HTTP/1.1" 200 5207 [06/Mar/2021 17:58:35] "GET /static/js/vendor/modernizr-3.5.0.min.js HTTP/1.1" 200 8638 [06/Mar/2021 17:58:36] "GET /static/js/popper.min.js HTTP/1.1" 200 19191 [06/Mar/2021 17:58:36] "GET /static/js/vendor/jquery-1.12.4.min.js HTTP/1.1" 200 97166 [06/Mar/2021 17:58:36] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 48950 but for forum page, the response is like this on the terminal Not Found: /forum/static/js/vendor/jquery-1.12.4.min.js [06/Mar/2021 17:58:54] "GET /forum/static/js/popper.min.js HTTP/1.1" 404 3627 Not Found: /forum/static/js/select2.min.js [06/Mar/2021 17:58:54] "GET /forum/static/css/bootstrap.min.css HTTP/1.1" 404 3642 Not Found: /forum/static/js/moment.min.js [06/Mar/2021 17:58:54] "GET /forum/static/js/vendor/jquery-1.12.4.min.js HTTP/1.1" 404 3669 [06/Mar/2021 17:58:54] "GET /forum/static/js/select2.min.js HTTP/1.1" 404 3630 and like this for about page [06/Mar/2021 18:02:11] "GET /about/static/img/gallery/about3.png HTTP/1.1" 404 3645 Not Found: /about/static/js/bootstrap.min.js [06/Mar/2021 18:02:11] "GET /about/static/js/bootstrap.min.js HTTP/1.1" 404 3636 Not Found: /about/static/js/jquery.slicknav.min.js [06/Mar/2021 18:02:11] "GET /about/static/js/jquery.slicknav.min.js HTTP/1.1" 404 3654 Not Found: /about/static/js/owl.carousel.min.js [06/Mar/2021 … -
How to display the fields of a foreign key in django admin form?
What I want to do is, say I have a model Person, I want to display the contact number of the Person anywhere(I mean I don't care where to place it, as long as someone can see it but preferably on the top so it's easy to find) in the Form after selecting it on the auto complete and when viewing a record. I was able to show the contact number when selecting from the auto complete using a Form, a rest_api and js. But when the fk field is read_only, I want to still get the Person and display the contact number as well. When the Person fk is read_only, I will use the Person of the person logged in, which I can already get in get_form, but I can't seem to set the Person to it's field. I already tried multiple ways of doing this. Using get_form and set the form['field'] for it, setting initial when declaring the Form, make a view for my PersonForm in views.py, using widget but still can't seem to make it work. And unfortunately it seems like no one has made this scenario before so I didn't find any definitive answer to my … -
How to return a message on expired PasswordResetConfirmView?
How to generate an error message if reset password's token has expired? I added PASSWORD_RESET_TIMEOUT = 100 to my settings.py based on Docs. How I declare my resets urls.py path('reset_password/', views.MyPasswordResetView.as_view( template_name="../templates/logauth/reset_password.html", subject_template_name='../templates/logauth/password_reset_subject.txt', email_template_name='../templates/logauth/password_reset_email.html', html_email_template_name='../templates/logauth/password_reset_email.html', from_email=settings.EMAIL_HOST_USER,), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="../templates/logauth/reset_password_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="../templates/logauth/reset_password_2.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="../templates/logauth/reset_password_complete.html"), name="password_reset_complete"), -
Django-filter pagination duplicates
I'm trying to filter a model and paginate it, but for some reason, I get duplicates in my query. I try to filter the following model by brand: class Post(models.Model): brand_choices = [ ('Apple', 'Apple'), ('Samsung', 'Samsung'), ('Honor', 'Honor'), ] brand = models.CharField(max_length=30, choices=brand_choices, blank=False, null=True) price = models.IntegerField(validators=[MinValueValidator(0)], blank=False, null=True) Here is my current model state: +----+---------+-------+ | id | brand | price | +----+---------+-------+ | 1 | Apple | 1 | | 2 | Apple | 2 | | 3 | Apple | 3 | | 4 | Apple | 4 | | 5 | Apple | 5 | | 6 | Samsung | 6 | +----+---------+-------+ And everything is ok when I try to get all the objects, it returns this query: <QuerySet [<Post: Post object (6)>, <Post: Post object (5)>, <Post: Post object (4)>, <Post: Post object (3)>, <Post: Post object (2)>, <Post: Post object (1)>]> And it renders in template like this: Samsung 6 Apple 5 Apple 4 Apple 3 Apple 2 Apple 1 But when I filter model by brand=Apple it returns almost the same queryset: <QuerySet [<Post: Post object (6)>, <Post: Post object (5)>, <Post: Post object (4)>, <Post: Post object (3)>, <Post: … -
I am having issues collecting the staticfiles in my django application
I am trying to collectstatic files in django using the command python manage.py collectstaic but i keep getting the error The system cannot find the path specified: 'C:\\Users\\Habib\\Documents\\django\\FIVERR\\Eduo\\OTTO\\staticfiles' I have configured the STATICFILES_DIRS but it still doesn't work. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] MEDIA_URL = '/media/' MEDIA_ROOT = '/media/' -
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?