Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload many images django rest framework
I try to upload many images to one post. I try to achive this: When I post data i get this: What is wrong with my code ? -
Django app does not work after Deploy when I used Pandas
I have a project and it works well when I run the project in pycharm But when I deploy this project on the server, it has a problem The problem is using pandas toolkits It works well when I remove "import pandas as pd" from the files on the server, but when I use this toolkit, the project does not work It should be noted that after Deploy, when this package is used in one of the files, the whole project does not work I use Apache The version of packages on the server and local is the same Pandas version is 1.1.2 -
Error while configuring postgressql for django
I have implemented full text search in my django app using postgresql. But, when I press the search button, I get an error: ProgrammingError at /blog/search/ function similarity(character varying, unknown) does not exist LINE 1: SELECT COUNT(*) FROM (SELECT SIMILARITY("blog_post"."title",... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I don't know where the error is, so if you need any files, I will edit this question. Please help me -
How to embed a filter in the other side of a foreign key relationship in django
I have the following structure: class Room(models.Model): doors: BaseManager class Door(models.Model): deleted = models.BooleanField(default=False) room = models.ForeignKey(to=Room, related_name='doors' ) Now after I've saved a room and saved some doors which reference that room I can load a room and get all the doors in the room... However, when I do a room.doors.all() I actually want to receive only those doors that are not deleted (that have deleted as false). How would you do this with django? -
How to pass value from one method to another and edit value in a model?
I am trying to do OTP-based authentication in Django during user signup but I am not getting how to pass email from signup page to otp page and edit value in model. The signup method is working fine but I am not getting how to update user_status to 'v' i.e. verified for a particular email who is signing up after otp verification. views.py def signup(request): if request.method == 'GET': return render(request,'registration/signup.html') else: postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') email = postData.get('email') username = postData.get('username') phone = postData.get('phone') password = postData.get('password') #validation value = {'first_name':first_name,'last_name':last_name,'email':email,'username':username,'phone':phone} error_message = None if(not first_name): error_message="First Name Required" elif(not last_name): error_message="Last Name Required" elif(not email): error_message="Email is Required" elif(not username): error_message="Username is Required" elif(not phone): error_message="Phone Number is Required" elif len(phone) is not 10: error_message="Mobile Number is Invalid" elif(not password): error_message="Password is Required" elif len(password) < 6: error_message = 'Password must be 6 char long' #saving if not error_message: print(first_name,last_name,email,username,phone,password) customer = Customer(first_name=first_name,last_name=last_name,email=email,username=username,password=password,phone=phone) customer.register() return render(request,'index.html') else: data = { 'error' : error_message, 'values' : value } return render(request,'registration/signup.html',data) def otp(request): if request.method == 'GET': return render(request,'registration/otp.html') else: otp_gen = None postData = request.POST otp_enter = postData.get(otp_enter) otp_gen = random.randint(10000,99999) print(otp_gen) otp_message = … -
Django admin page loads nothing
I am working on a Django project where I ran makemigrations and migrate. seemed to work fine its been a few days since I did that and now my admin page doesn't render anything it shows blank All the other pages work fine when I go to localhost:8000/admin it just shows nothing and the terminal shows this [06/Nov/2020 09:19:26] "GET /admin/ HTTP/1.1" 302 0 [06/Nov/2020 09:19:26] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 0 -
Django: Cache needs to de deleted to see new design changes
I have a Django applciation running in kubernetes environment behind an nginx ingress controller. Often when I redeploy the app with new design changes, the browser history/cache needs to be deleted in order to see the changes. How to automate this process so the user does not need to delete the browser cache to see the latest changes? -
how to fix video displaying error in Django?
So basically I was following a tutorial (https://www.youtube.com/watch?v=aR_JzBGdGvM) on how to upload videos to django but I'm having trouble at the html because the video tag won't play the video, it'll only play the sound. Here is my code <div class="container"> {% for vid in videos %} <h3 class="text-center mt-2 mb-2">{{ vid.caption }}</h3> <video class="embed-responsive embed-responsive-4by3" controls="controls"> <source class="embed-responsive-item" src="{{ vid.video.url }}" type="video/mp4" /> </video> {% endfor %} </div> The for loop and everything is working its just that the video itself won't play. The audio will play but the video won't. I am on a mac if that makes any difference because the video file is a .MOV but even when I try bootstrap's way <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="{{ vid.video.url }}" allowfullscreen></iframe> </div> the video doesn't play it just downloads it. How can I fix this? Please Help! Thank You! -
DJANGO: how to use "core" URL in template
I'm trying to use a "core" url in my template but I don't know what is happening, It won't let me. My url is declared here: url.py: (the djangorestframework is the important one) urlpatterns = [ path('admin/', admin.site.urls), path('consumos/', include('consumptions.urls', namespace='consumptions')), path('registros/', include('logs.urls', namespace='logs')), path('reglas/', include('rules.urls', namespace='rules')), path('djangorestframework/', include(router.urls), name="drf"), path("", include("authentication.urls")), path("", include("dashboard.urls")), ] But when I'm trying to use it in my sidebar I have to sidebar.html: <li class="mt-3 nav-item"> <!-- FIXME: Esta url tiene que haber otra manera de llamarla --> <a target="_blank" class="nav-link" href="/djangorestframework"> <i class="fas fa-cloud"></i> <p> API </p> </a> </li> because it won't let me use it like this: <li class="mt-3 nav-item"> <!-- FIXME: Esta url tiene que haber otra manera de llamarla --> <a target="_blank" class="nav-link" href="{% url 'drf' %}"> <i class="fas fa-user-cog"></i> <p> API </p> </a> </li> It says: Reverse for 'drf' not found. 'drf' is not a valid view function or pattern name. Why I can not use the name of my url? why do I have to use a relative path? Thank you! -
Error "Unknown field(s) (student_id) specified for User" for django-registration two step account activation with custom user
I'm using the two step account activation in django-registration and I get this error when I run the server. I'm also using a custom user created from AbstractBaseUser. The user model automatically sets the email field by student_id. forms.py from django_registration.forms import RegistrationForm from .models import StudentUser class StudentUserRegisterForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = StudentUser in models.py class StudentUserManager(BaseUserManager): def create_user(self, student_id, name, password): user = self.model(student_id=student_id, name=name, email=f'{student_id}@ksa.hs.kr') user.set_password(password) user.save() return user def create_superuser(self, student_id, name, password): user = self.create_user(student_id, name, password) user.is_active = True user.is_superuser = True user.is_staff = True user.save() return user class StudentUser(AbstractBaseUser, PermissionsMixin): object = StudentUserManager() student_id = models.CharField(max_length=10, verbose_name='학번', help_text='00-000', unique=True) name = models.CharField(max_length=100, verbose_name='이름') email = models.EmailField(default=f'{student_id}@ksa.hs.kr') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'student_id' REQUIRED_FIELDS = ['name'] part of urlpatterns in urls.py path('accounts/register/', RegistrationView.as_view(form_class=StudentUserRegisterForm), name='django_registration_register'), path('accounts/', include('django_registration.backends.activation.urls')), in setting.py INSTALLED_APPS = [ 'ksa_books_app', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_registration', ] AUTH_USER_MODEL = 'ksa_books_app.StudentUser' -
Change label of ManyToMany Field django?
class PermissionForm(forms.ModelForm): class Meta: model = Group fields = ['permissions'] widgets = { 'permissions': forms.CheckboxSelectMultiple, } If I render the above form I get the output as: I need to show only the marked area(red color) as label.And one more for example,in the below image there is a accordion,I want to show permission of Group model under role tab and permission of organization model under organization tab.I don't have any idea how to start with -
No module named 'usersdjango', Could someone help me out?
I'm working with Django and I have a problem in running local server because of this error: No module named 'usersdjango' here's the $tree: [ |-- = folder ] learning_logs folder: |--django_venv |--learning_logs |--llog |--users manage.py urls.py in users folder: from django.urls import path,include app_name = 'users' urlpatterns = [ path('', include('django.contrib.auth.urls')), ] login.html in users folder: {% extends 'learning_logs/base.html' %} {% block content %} {% if form.errors %} <p> Your username and password diden't match. </p> {% endif %} <form action="{% url 'users:login'%}" method='post'> {% csrf_token %} {{form.as_p}} <button name='submit'>Log in</button> <input type='hidden' name='next' value="{% url 'learning_logs:index'%}" /> </form> {% endblock %} base.html in learning_logs(templates) folder: <p> <a href="{% url 'learning_logs:index' %}"> Learning_log </a> - <a href="{% url 'learning_logs:topics' %}"> Topics </a> - {% if user.is_authenticated%} Hello, {{user.username}} {% else %} <a href="{% url 'users:login'%}">Log in </a> {% endif %} </p> {% block content %}{% endblock %} -
FieldError: Cannot resolve keyword 'shopfavorite' into field
I'm using reverse foreignkey using django predefine function prefetch_related. but i'm getting the error: FieldError: Cannot resolve keyword 'shopfavorite' into field. . What is the exact issue? Any helpful, would be much appreciated. thank you so much in advance. models : class ShopOwnerShopDetails(models.Model): shop_name = models.CharField(max_length=80, blank=True, null=True) shop_location = models.CharField(max_length=200) class ShopFavorite(models.Model): shop_id = models.ForeignKey(ShopOwnerShopDetails, on_delete=models.CASCADE, related_name='favorite_shop_id') favorited_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_favorite_shop') views : queryset = ShopOwnerShopDetails.objects.filter(shopfavorite__favorited_by=user).prefetch_related('shopfavorite_set',) serializer = ShopOwnerShopDetailsSerializer(queryset, many=True, context={'request': request}) data = serializer.data -
Django does not filter by non english letters
In my database I have objects with slavic letters (śćę etc.). It is displayed correctly in my database, admin panel and even when I call my object in template. User can search for this object by providing what he wants in text input box: template.html <input type="text" class="form-control" placeholder="Model" name="searched_model" id="searched_model" value=""> Hovewer when I filter the objects database in my view: views.py found_products = ProductBase.objects.filter(Q(model__contains=searched_model).order_by('model') It filters and displays correctly until slavic letter is provided. For example, user wants object with model property as: ObjectŚĆobject If he writes in my search field object it will find and display ObjectŚĆobject. But if he writes objectŚ or even Ś only it will not show anything. My view returns found_products to template and displays it in table: template.html {% for item in found_products %} ... <td> {{item.model}} </td> I don't know where lies the problem. In settings.py I have correct LANGUAGE_CODE = 'pl-pl'. -
Access Multiple FIles Upload in Django
I am new to Django and I had created a form for uploading multiple files as well as some text values. Here are my files: forms.py class UploadFileForm(forms.Form): report_file = forms.FileField() data1_file = forms.FileField() data2_file = forms.FileField() year = forms.IntegerField() Name = forms.CharField(max_length=50) views.py def uploads(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) process_data(<parameters>) # will accept all the form parameters but don't know how access the files individually. messages.info(request, "Success!" ) return HttpResponseRedirect('') else: form = UploadFileForm() return render(request, 'app/home.html', {'form': form}) I want to access all those files and file names along with the name and year from the view and pass it on to another function for data processing. Can you suggest ideas on how to achieve that? -
Docker + Django + Vue.js + Webpack how to properly configure nginx?
At the moment I have the following configuration, in which I get an error: Failed to load resource: the server responded with a status of 404 (Not Found) As I understand it, I entered the path incorrectly and nginx cannot give the build.js file, which is missing from this path. How can I properly configure nginx so that it serves this file. Config nginx: upstream music { server web:8000; } server { listen 80; server_name ***; access_log /var/log/nginx/logs.log; location /vue-frontend/ { root /home/app/web/vue-frontend/dist; } location / { proxy_pass http://music; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { root /home/app/web; } location /media/ { root /home/app/web; } } The entire vue js project lies in the django project folder. Vue is embedded in the django template along the templates / base.html path {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% load render_bundle from webpack_loader %} </head> <body> <div class="main_content"> <div id="app"></div> {% render_bundle 'main' %} </div> </body> </html> file docker-compose.prod.yml: version: "3.8" services: web: build: context: ./ dockerfile: Dockerfile.prod command: gunicorn music.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.prod depends_on: - db vue: build: context: ./vue-frontend dockerfile: Dockerfile.prod volumes: … -
Reverse for 'program-details' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['program\\-details/(?P<slug>[^/]+)/$']
What's wrong with my code i got this error enter image description here urls.py enter image description here views.py enter image description here program.html (template) enter image description here models.py enter image description here -
Calling an External API That Fails Randomly
I am using Django server to call a Korean government's weather API to retrieve weather data for around 1800 locations. However, this weather API results in time out most of the time. I tried giving resting periods. For example, for every request, it will sleep for 0.8 seconds and after every 30 requests, it will sleep for 30 seconds. But this does not really work well for 1800 requests. At one point, it was successful. All other times, it ended up with fail. In this kind of situation, what else should I do to make sure that 1800 requests are completed within one hour? Is there any way for this to restart the request sequence from the exact point it failed previously? For someone who is curious about what this code looks like, I am posting it below: class WeatherCreate(View): def get(self, request): today = date.today().strftime("%Y%m%d") today = str(today) current_time = datetime.now(pytz.timezone('Asia/Seoul')).strftime('%H') current_time = str(current_time) + "00" current_time = "1100" print(current_time) if current_time not in ("0200", "0500", "0800", "1100", "1400", "1700", "2000", "2300"): return JsonResponse(data={"message": "DATA IS NOT AVAILABLE AT THIS TIME. TRY AGAIN LATER."}, status=406) # Call every single distinct address addresses = Address.objects.all() locations = [address.location for address … -
Migrate Laravel User and Password table to Django
I just want to know how can i migrate the users and passwords that is made with laravel 5.8 to a fresh django application. i searched for some answers how to decrpyt the password back to plain text so i can encrypt/hash the password to the technology that django uses. if you have different approach just reply to the thread. Thank you. -
How safe is a deployed Django app (with login only)?
I am about to deploy my first Django app. The plan is to push the locally running Docker container somehow to Google Cloud Run and now I wonder how safe my data will be then. I am aware of the Deployment checklist and I read the Security chapter in Django for Professionals. In my case, the whole app is accessible for logged in users only and, for the beginning, only a couple of trustworthy people will have an account. My assumption is, that – even if inside the app something should be not perfectly secure yet (let's say I forgot a csrf_token) – only logged in users could do any harm. Is this assumption too naive? So I have to make sure that everybody has a strong password and I should install some protection against fraudulent login by brute force password guessing, right? Is there anything else I have to consider? -
UnreadablePostError, partial results are valid but processing is incomplete
I'm getting this error continuously (in my server) and the server is getting down at the time of this. Please advise solving the issue. I've seen some suggestions like 'it is due to an incomplete request to the server', but no one suggested a real solution for this. -
gettin bad request on tests using django rest framework
I'm learning django rest framework and I'm trying and a test get me a bit nervous, so if someone can help me I would appreciate my tests.py file: def test_post_method(self): url = '/arvores/' self.especie = Especies.objects.create(descricao='Citrus aurantium') data = {'descricao':'Laranjeira', 'especie':self.especie.id, 'idade':12} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) my views.py file: class EspeciesViewSet(viewsets.ModelViewSet): queryset = Especies.objects.all() serializer_class = EspeciesSerializer class ArvoresViewSet(viewsets.ModelViewSet): queryset = Arvores.objects.all() serializer_class = ArvoresSerializer serializer.py file: class EspeciesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Especies fields = ['id', 'descricao'] class ArvoresSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Arvores fields = ['id','especies', 'descricao', 'idade'] and models.py : class Especies(models.Model): descricao = models.CharField(verbose_name='Descrição', max_length=255) class Arvores(models.Model): especies = models.ForeignKey(Especies, on_delete=models.CASCADE) descricao = models.CharField(verbose_name='Descrição', max_length=255) idade = models.PositiveSmallIntegerField() -
ModuleNotFoundError: No module named 'mysite' when try to call django-admin
when I run the command django-admin collectstatic in terminal this error is appear! ModuleNotFoundError: No module named 'mysite' The folders structure myProject | +----mysite | | | +----settings.py | +----wsgi.py | +----urls.py | | +----todo (app) | +----accounts(app) | +----myvenv setting.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) WSGI_APPLICATION = 'mysite.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() even when I run '''django-admin''' the error of No module named 'mysite' appears at the end of the list django-admin commands help Type 'django-admin help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver Note that only Django core commands are listed as settings are not properly configured (error: No module named 'mysite'). -
Problems while adding images with Django summenote
I succesfully added summernote to my admin site for a blog, however, when I add an image to a post directly via Image URL address it occupies the "Read more" button. (Picture related: Error when trying to render the page.) However this does not happen when uploading the picture directly from my computer. I'm sure it has something to do with the HTML autoescaping, but I relatively new at this and I dont know how to debug it. The HTML I used is the following: <div class="col-md-8 mt-3 left"> {% for post in post_list %} {% autoescape off %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p class="card-text">{{post.content|slice:":200" }}</p> {% endautoescape %} <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read more &rarr;</a> </div> </div> {% endfor %} </div> -
Python-Django Trying to Add Users to my Database
I'm new to Django and I'm trying to create a page that allows users to register to my website. But I keep getting a page not found error. Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order: 1. admin/ 2. home [name='home'] 3. account/ register/ [name='register'] The current path, account/register/register, didn't match any of these. Here's the code inside my html file 'register.html': <form action = 'register' method = "POST"> {% csrf_token %} <input type='text' name='first_name' placeholder = "First Name"><br> <input type='text' name='last_name' placeholder = "Last Name"><br> <input type='text' name='username' placeholder = "Username"><br> <input type='password' name='password' placeholder = "Password"><br> <input type='Submit' placeholder='Submit'> </form> And here's the code inside 'myapp.views': from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth def register(request): if request.method == 'POST': first = request.POST['first_name'] last = request.POST['last_name'] usern = request.POST['username'] passw = request.POST['password'] user = User.objects.create_user(first_name = first, last_name = last, username = usern, password = passw) user.save() return redirect('/home') else: return render(request, 'register.html') Why doesn't it create a new user in my database and redirect to '/home', and instead go to 'account/register/register'? Thanks in advance.