Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form_valid error. Can anyone find the error?
I am trying to use the value from the URL on CreateView My models are like that: Categoria > Serie I have made a URL that path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'), The URL to create a new Serie is like that: /nova-serie/3 I am trying to use form_valid but I am receiving this message: Cannot assign "'3'": "Serie.categoria" must be a "Categoria" instance. views.py class NovaSerie(CreateView): model = Serie form_class = SerieForm template_name = 'nova_serie.html' success_url = reverse_lazy('home') def form_valid(self, form): url = self.request.path_info parte_final_url = url.replace('/nova-serie/', '') form.instance.categoria = parte_final_url return super(NovaSerie).form_valid(form) forms.py class SerieForm(forms.ModelForm): class Meta: model = Serie fields = ( 'serie', ) widgets = { 'title': forms.TextInput(), # attrs={class="title"} } Can anyone here give me a help? -
Cannot read property 'value' of undefined when adding CSRF token to request headers plain JS
I am trying to add CSRF token to request headers, but it returns the error: TypeError: Cannot read property 'value' of undefined In my django template I have added {% csrf_token %} and my function looks like this: addFavorites (id) { return fetch(`/favorites`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.getElementsByName('csrfmiddlewaretoken')[0].value }, ... What did I miss? -
Data attribute fails to identify itself on Django
In my html file, I have something like this: {% if posts %} {% for post in posts %}' <div onclick="change_like('{{post.id}}')" <small data-id="{{post.id}}" id="laiks">{{post.liked_by.all | length}}</small> </div> {% endfor %} {% endif %} The change_like() function is this one (down here I show you the relevant part): elem = document.querySelector('small'); id = elem.getAttribute('data-id'); console.log(id) So now, in my html page I have a lot of posts and when I click that div The console.log(id) it shows only the first id, no matter in which post I click. I could click in the last one, but the log will be the id always of the first one. So when I want to change the number of likes on X post, it only changes on the first one. Any ideas? -
i'm getting a 429 status when making api request call in django production on DO server but no such error occurs when running from local host
i have wrote this code as TOMTOM doesn't have python SDK for it services this function is called multiple times for route calculation when calling it on django production mode it throws the status of 429 after some 10 to 15 requests to api service but this doesnt happen on when i run it on local host in debug False even if the api calls are made more than 20 to 50 times. def directions(request,geocodes): points = '' for p in geocodes: points += str(p['coordinates'][::-1]).replace('[','').replace(']','').replace(',','%2C').replace(' ','') points +='%3A' # try: req = f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}' r =requests.get(f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}') status = r.status_code print(r.status_code) if status == 200: results = r.json() return results elif status == 429: time.sleep(int(r.headers["Retry-After"])) r =requests.get(f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}') results = r.json() return results if i can get help on why this is happening it will be very much appreciated.thankyou -
How can you integrate two programming languages in one enviroment?
I'm currently working on a health care project with multiple people that write code in different languages. The back-end is meant to be built using laravel framework in php, but a couple of my colleagues and i myself are more proficient in Nodejs and DJango framework. Is there a way we can all work on building this platform using multiple languages and frameworks? Thank you. -
Handle website layout when viewed by mobile-browser vs desktop-browser in Django html template?
I would like to handle the layout of my django site based on whether the user is viewing the site from a mobile or desktop browser. Based on the refs I show at the end of this post, I tried to add some css to the head based on the "is_mobile" filter. My site uses base_menu.html to show all of my pages with a menu bar, and that file extends base_bootstrap.html, which has a lot more of the styling as so on. I tried adding this to base_menu.html to insert this mobile based css if the user is on a mobile device. {% if request|is_mobile %} {% block extra-head %} <!-- test if request|is_mobile is working--> {% endblock %} {% endif %} I have two problems. This html commentline was just my test of the if statement, but it is included whether the device is really "mobile" or note, suggesting the if isn't working. I can see it in the header when I look in developer mode I don't what to actually include in the css when the I do detect that the user is using a mobile-browser. My fundamental question, though, is "is there an easy way optimize display … -
Query intermediary model in one line Django
I have two models. They are default django user model and another model which looks like following: class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='recipes', blank=False, null=False ) ... And an intermediary one: class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='selecting', blank=False) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='selected', blank=False) Is it possible to retrieve all instances of Recipe model which have relation between them and request.user in one line? -
Django invalid literal for int() with base 10: b'11 20:11:22'
I want to copy an object from one model to another and I'm this ValueError "invalid literal for int() with base 10: b'11 20:11:22' " MODEL: class TempLog(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE, null=True,) start_date = models.DateTimeField(null=True, blank=True, auto_now=True) end_date = models.DateTimeField(null=True, blank=True) def save( self, *args, **kwargs ): employee = self.employee entry = TempLog.objects.filter(user=user) if entry.exists(): TempLog.objects.filter(user=user).update(end_date=Now()) All of these is fine, but if I do: queryset = TempLog.objects.filter(user=user).values('start_date', 'end_date', 'user') new_object = [PermanentLog(**values) for values in queryset] PermanentLog.objects.create(new_object) I need them in datetime format not in integer, how can I by pass this? -
How implement django multiple usertype with CustomUser model and class-based views?
everyone! I'm making a school site where there will be three user types: Principal, Staff and Student. I have managed to successfully(sort of) implement CustomUser model and associate new user to their respective model with receivers. Now my problem is, I have this form in the principal dashboard to add teacher. For that, I need a field in the form to give password as well which I want to store in CustomUser model. I want 'password' field in the form so that when I add Staff, it also automatically become a user. Now my question is, I don't know how to get this password and email from CustomUser model in StaffCreateView. I want save email and password in CustomUser model. In FBV, I could do it by creating an object of CustomUser model, user=CustomUser.objects.create_user( username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2 ) In short, how do I do similar thing in CBV? My code below: CustomUser model.py from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class CustomUser(AbstractUser): user_type_data = ((1,"Principal"),(2,"Staff"),(3,"Student")) user_type = models.CharField(default=1,choices=user_type_data,max_length=10) class Principal(models.Model): principal = models.OneToOneField(CustomUser,on_delete=models.CASCADE) name = models.CharField(max_length=200) mobile_num_regex = RegexValidator(regex="^[0-9]{8,11}$", message="Entered … -
GET request does not send results to view
I am trying to make a GET request to bring a list of books, however when I render again I do not get any results, it should be clarified that when print by console I do get results. What am I doing wrong? views.py def search_book_basic(request): form_class = SearchBookBasicForm form = form_class(request.POST or None) if request.method == 'GET': string_search = request.GET.get('string_search','') books = Book.objects.filter(Q(title__icontains=string_search) | Q(author__name__icontains=string_search)) for book in books: print(book.title) render(request, 'products/searchProductBasic.html',{'form': form, 'books':books}) return render(request, 'products/searchProductBasic.html',{'form': form}) searchProductBasic.html <div class="row justify-content-center"> <div class="col-md-10"> <div class="card"> <div class="card-header">Search/div> <div class="card-body"> <form method="GET"> {% for field in form %} <div class="form-group row"> <label class="col-md-4 col-form-label text-md-right"> {{ field.label }}</label> <div class="col-md-6">{{ field }}</div> </div> {%endfor%} <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary">Search</button> </div> </form> <br/> <br/> {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endfor %} </div> </div> </div> </div> </div> {% for book in books %} <h1>{{ book.title }}</h1> {%endfor%} -
get_object_or_404 is undefined
I'm trying to update my Profile model with some data that I get from a form, but I get this error name 'get_object_or_404' is not defined Here's my code for the view (It's pretty basic at this point) from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from users import models from users.models import Profile from .forms import WeightForm # Create your views here. def home(request): profile = get_object_or_404(pk=id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save return render(request, 'Landing/index.html',{'form':form}) -
Facebook has detected Believer isn't using a secure connection to transfer information
Well I am trying to add login and sign up with facebook functionality and when i click on login with facebook it takes me to facebook but shows an error such as Facebook has detected Believer isn't using a secure connection to transfer information. Until Believer updates its security settings, you won't be able to use Facebook to log into it. -
Django - can't compare offset-naive and offset-aware datetimes or no result appears
I got a model / view for Story project. My goal is to give only a time to stories to appear on my website. class Story(models.Model): ... ... image = models.ImageField(upload_to='story/') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self): super().save() @property def is_active(self): #now = timezone.now() if (self.created_on + timedelta(days=10)) > datetime.now(): return False return True @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class StoryList(generic.ListView): queryset = Story.objects.order_by('-created_on') template_name = 'user_list_story.html' model = Story I get this issue: can't compare offset-naive and offset-aware datetimes So I've tried to correct it in order to the same comparaison. @property def is_active(self): now = timezone.now() if (self.created_on + timedelta(days=10)) > now: return False return True But nothing appears on my page. Here is the code template. {% for story in story_list %} {% if story.is_active %} {{ story.title }} {% endif %} {% endfor %} -
Create spacing in data list
How do I space out the output, i considered using the each() method but I couldn't figure out how to use it. I can do this with Django for loop without ajax, but with ajax it seems the for loop tag doesn't work here's the code. current output = 1.0768411833.01.28164125.6340.91000 expected output = 1.07684 11833.0 1.28164 125.634 0.91000 <h2 id="prices"></h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> const doAjaxWithDelay = (delay) => { setTimeout(() => { var data = $(this).data() $.ajax({ url: "/price", type: "GET", success: function(data) { document.getElementById('prices').innerHTML = data; console.log(data) } }).done(() => { doAjaxWithDelay(5000) }) }, delay) } doAjaxWithDelay(0) </script> -
Django's invalid regular expression: invalid escape \ sequence [duplicate]
I'm trying to filter my records with __regex field lookup. It works fine until I started using unicode property group (\p{whatever}), or, letter group (\p{L}). DB i'm using - postgresql. Code that I got looks like this: f1 = Q(field__regex=r'[^\d\p{L}]anystr[^\d\p{L}]') f2 = Q(field__regex=r'[^\d\p{L}]strany[^\d\p{L}]') MyModel.objects.filter(f1 | f2) After launch of this code, I got this error: django.db.utils.DataError: invalid regular expression: invalid escape \ sequence I tried to dig deeper and found nothing that could cause problem in python code. Last point of exception is: django\db\backends\utils.py", line 86, in _execute, so, i placed pdb point there. There are 2 variables, sql and params. sql - contains raw sql code without values of django's Q objects yet (seems like it will be added by format strings, because of %s's) params - Q object's values itself. In my example it was: ('[^\\d\\p{L}]anystr[^\\d\\p{L}]', '[^\\d\\p{L}]strany[^\\d\\p{L}]') 1 line later exception like above was thrown again. But, If I paste one of generated values of Q in search of DB itself, no error seen. -
Adding additional serializer field that will be using posted data from the client
How can I use Django Channels with my Django Rest Framework so that I can use it with my Flutter Mobile App ? -
how to assign different id in button in django template so that javascript click event won't select all post
I am new to django and also have very little knowledge in javascript. Here I am trying to assign id to the delete and update button so that when clicking them javascript won't select all the same button. If anyone can help this poor man. this is my django template that contains update and delete button {% for obj in queryset %} <div class="ui grid"> <div class="row"> {% ifequal request.user obj.author.user %} <button class="ui button bwhite-lg " id='modal-udt-btn'>Update</button> <button class="ui button bwhite-lg " id='modal-dlt-btn'>Delete</button> <!-- modal --> <div class="ui basic modal update"> {% url 'posts:post_update' obj.pk %} </div> <div class="ui basic modal delete"> {% url 'posts:post_delete' obj.pk %} </div> {% endifequal %} </div> </div> {% endfor %} Here is the part with javasript <script> $(document).ready(function(){ $('#modal-dlt-btn').click(function(){ console.log('deletebtn') $('.ui.basic.modal.delete') .modal('show') ; }) }); $(document).ready(function(){ $('#modal-udt-btn').click(function(){ console.log('updatebtn') $('.ui.basic.modal.update') .modal('show') ; }) }); </script> -
How can I reuse Django admin search feature?
I'm developing an application with Django.I'm using Django admin's search feature like this: class ProductAdmin(admin.ModelAdmin): search_fields = ('image_name', 'product_name', ) And it gives a very nice search on these columns. Now I want to use this search in my views and inside my code. I mean I want to reuse this search which Django uses for the admin page in my code. I've read the code of ModelAdmin class but I couldn't reuse it, because it uses some objects from other layers of Django. So I couldn't figure out how can I do this. -
The SECRET_KEY setting must not be empty, django by example
I am getting this error while running the following command: python manage.py runserver The is a result of the execution of the code from the book; Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Anaconda_3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Anaconda_3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Anaconda_3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Anaconda_3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "D:\Anaconda_3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Anaconda_3\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
How to retrieve information in Django - Post Request?
I am trying to send a JavaScript array to Django via ajax, as follows: document.getElementById('input-generate').onclick = () => { // Get the token const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; // Create new request add token const generateRequest = new XMLHttpRequest(); generateRequest.open('POST', '/generate'); generateRequest.setRequestHeader('X-CSRFToken', csrftoken); generateRequest.onload = () => { console.log('generateRequest'); }; // Add the motif to send with the request const data = new FormData(); console.log(notes); // [{…}] 0: {duration: "4", note: "E4", dot: false} length: 1 __proto__: Array(0) data.append('motif', notes); // Send request generateRequest.send(data); }; On views.py: @require_http_methods(["POST"]) def generate(request): # See if method was post if request.method == "POST": # Retrive seed seed = request.POST.get("motif") print(seed) print(type(seed)) # Sanity check if not seed: return JsonResponse({"succes": False}, status=400) # Return the seed return JsonResponse({"seed": seed}, status=200) But when I print seed and type(seed) I only see: [object Object] <class 'str'> How can I print the actual array I am sending? -
Django models.CASCADE in ManyToManyRelation
I have a m2m relationship with users and posts. A user can like a many posts and at the same time a post can be liked by many users. If i do this: post.liked_by.remove(current_user) With this model structure: class Posts(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts") creation_date = models.DateTimeField(auto_now_add=True, blank=True) content = models.TextField(null=True) class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') likes = models.ManyToManyField(Posts, related_name='liked_by') pass As far as i know, the user object will be removed from the liked_by part of the relationship. But my question is: Will also the post object be removed from the likes part of the relationship? -
Form not showing on template
I've created a model form and it does not show on the page models.py class Newsletter(models.Model): email = models.EmailField(max_length=254) name = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email forms.py class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ['name', 'email'] views.py class HomeNewsletterFormView(FormView): template_name = 'home/base.html' form_class = NewsletterForm base.html <form method="POST" action=''> {% csrf_token %} {{ form.as_p }} <input type="submit"> Everytime I reload the page, I see browser popup mentioning "The page that you're looking for used information that you entered. Returning to that page might cause any action that you took to be repeated. Do you want to continue?" -
Django LoginView with custom email form
I am trying to create LoginView with a custom email form instead of a username, but having a hard time to manage it to work. Here is my code below urls.py ********** urlpatterns = [ path("login/", views.LoginView.as_view(), name="login"), path("logout/", views.log_out, name="logout"), ] forms.py class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "Email"})) password = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Password"}) ) def clean(self): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(email=email) if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError("Password is wrong")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("User does not exist")) views.py class LoginView(FormView): template_name = "users/login.html" form_class = forms.LoginForm success_url = reverse_lazy("core:home") def form_valid(self,form): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(username=email,password=password) if user is not None: login(self.request,user) return HttpResponse(request.user.is_authenticated) else: return HttpResponse("Login failed") return super().form_valid(form) def log_out(request): logout(request) return redirect(reverse("core:home")) html file <form method="POST" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button>Login</button> </form> In the code above i didn't copy paste from .. import .. things since i am sure thats is not what causing a problem. The error message i am getting is "Login Failed" in this line `if user is not None: login(self.request,user) return HttpResponse(request.user.is_authenticated) else: return HttpResponse("Login failed")` in setting.py i have this AUTH_USER_MODEL = "users.User" and my models.py … -
Command Error status 1 when I import an app in django
I'm working with Django Channels tutorial. When i'm trying to import app_name.routing i get this type of error: ERROR: Command errored out with exit status 1: command: 'd:\koronatime\djangopython\djangochannels\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppD ata\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"';f=ge tattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' instal l --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-8ado413q\install-record.txt' --single-version-externally-managed --compile --install-headers 'd:\koronatim e\djangopython\djangochannels\env\include\site\python3.8\numpy' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-1ws3h4ct\numpy\ Complete output (1795 lines): Running from numpy source directory. Note: if you need reliable uninstall behavior, then install with pip instead of using `setup.py install`: .... Hundred rows of mistake ... ERROR: Command errored out with exit status 1: 'd:\koronatime\djangopython\djangochannels\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv [0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1w s3h4ct\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, _ _file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-8ado413q\install-record.txt' --single-version-externally-managed --compil e --install-headers 'd:\koronatime\djangopython\djangochannels\env\include\site\python3.8\numpy' Check the logs for full command output. I've included it in INSTALLED_APPS. I am on OS Windows. P.S. When I've include app in settings and had installed some packages already, I always need to click on Install package app_Name, when i importing it on code, like it was with Channels. Why is it happening? -
Problems implementing django-babeljs in my project
I'm trying to implement django-babeljs 0.2 but I can't get it to work with my code, I'm not using react. I just want my js files to be transpiled with babel, they have an example of how to implement it correctly, I am reading the documentation of the library at https://pypi.org/project/django-babeljs/#description but it really is not very explicit. Could someone help me with this issue.