Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test views in Django?
I try to create test to my views in django app, in my setUp method i want to create new object and then pass id of this object to reverse('edit') to test passing an id like I have in my urls, here is code: test_views.py def setUp(self): self.client = Client() self.edit = reverse('edit', args=['id']) self.id = Employee.objects.create( econtact='testContact', eemail='test@tset.pl', ename='testName' ).id urls urlpatterns = [ path('edit/<int:id>', views.edit, name="edit"), ] model class Employee(models.Model): ename = models.CharField(max_length=100) eemail = models.EmailField() econtact = models.CharField(max_length=15) can somone tell me why, after run this test case, my console throw me: django.urls.exceptions.NoReverseMatch: Reverse for 'edit' with arguments '('id',)' not found. 1 pattern(s) tried: ['edit/(?P<id>[0-9]+)$'] thanks for any help! -
API Fetch from HTTPS to HTTPS
I'm building an application with it's frontend build in React and deployed using netlify. Backend build in django and django rest framework and deployed using heroku. Now the issue is when my project is on localhost i.e :8000(backend) and :3000(frontend) the fetch api calls runs fine as both are HTTP. But as soon as i switch to HTTPS my application stopped working. I have byfar tried to resolved all possible CORS issues yet nothing seems working. Can Anyone help me with how to make api calls from a HTTPS server(heroku hosted) to HTTPS client (netlify hosted / or i'll host it on heroku if that helps). -
Invalid block tag: 'endblock'. Did you forget to register or load this tag?
Given is my folder structure. In 'home.html': {% extends 'job_main/base.html' %} {% block title %}Home{% endblock title %} {% block content %} <h1>Home Page</h1> {% endblock content %} In 'base.html': . . . <title>{% block title %}{% endblock title %} | Jobs Portal</title> <body> . . {% block content %} {% endblock content %} </body> -
How to run Cron jobs in app engine using django
I am using django 2.2.0 and I have deployed it on appengine standard environment. I want to run some cron jobs on server. Any idea, how can it be done? -
How to customize 404 page in django?
In my django app I want to show a custom not found 404 page. But after reading the documentation and coding I am still getting the default 404 Not found page. I am working with Django 2.2.8 I also set DEBUG=False Here is my code: in setting.py I have defined: handler404 = 'riesgo.views.views.error_404' Definition in riesgo/views/views.py def error_404(request, exception): return render(request,'404.html') -
What's the best way or tool to work with data and database?
I'm currently working for the accounts department of a hospital. I have been given an assignment outside of my job profile, to create a web application to track and maintain patients' data and prepare bills and reports for subsequent analysis. The data will not be huge in amount but might be enough to overwhelm us sometimes. We have several joint ventures with several hospitals in several cities where we provide our services. So I'm allowed to take my own time to get it done, but it should happen in this year itself. I have plenty of time to learn and practice and develop a well functioning application. I already know Python, Django, HTML, CSS, SQL, JS. I'm going to make the application with Django. My question is that what tools I should use to work with Data and Database? We should be able to enter data, use it to generate few other databases and tables and subsequently generate reports and charts with the options to export them to presentable Excel, PDF or PowerPoint files as the requirement arrives. Can I achieve this using just the ORM of Django, Charts.js and openpyxl or I need to learn something more? Any suggestions? … -
Select database before entering admin site in Django
I have a Django app configured for multiple databases. My issue is I want the admin user to be able to select the what database to use before they get to the admin menu. The reason is there's a sandbox, dev, prod all with the same tables just different data. What I've tried so far was to have a view to set the session to the database they chose and then I tried to get that session in admin.py but I can't use request to get that without and error. Side info(I'm using oracle as my db) s = SessionStore() d = s['database'] #for example it gets back-> dev using = 'f{d}' Any ideas how to get this done/if I'm attacking it the completely wrong way. -
'RedisCache' object has no attribute 'keys'
my keys in cache are like this /notifications/api/v1/faq every key in cache are start with / from django.core.cache import cache print("keys",cache.keys("/*")) when i try to print keys I'm getting this error 'RedisCache' object has no attribute 'keys' -
Django urls.py issue, not sure what to put in 'urlpatterns'
I've been following this tutorial (Django Tutorial Part 3) and I've stumbled across what I'm assuming is a syntax issue between the time this tutorial was written and the new Django releases. My admin page loads just fine. Code Block in Question So in the picture linked, that is the area that I am having trouble with from the tutorial. I think my "mysite/urls.py" file is fine, but the "polls/urls.py" file is where I'm not sure what to put. Below is what mysite/urls.py looks like: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), And here is what my polls/urls.py looks like: from django.urls import path from . import views urlpatterns = [ path(**??? not sure what to put here**, views.index, name='index'), ] -
Why do I get this error when I pip install django and django-rest-framework?
WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Collecting django Using cached Django-3.2.4-py3-none-any.whl (7.9 MB) Collecting djangorestframework Using cached djangorestframework-3.12.4-py3-none-any.whl (957 kB) Requirement already satisfied: asgiref<4,>=3.3.2 in c:\python39\lib\site-packages (from django) (3.3.4) Requirement already satisfied: sqlparse>=0.2.2 in c:\python39\lib\site-packages (from django) (0.4.1) Requirement already satisfied: pytz in c:\python39\lib\site-packages (from django) (2021.1) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Installing collected packages: django, djangorestframework ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: 'c:\python39\Scripts\django-admin.py' Consider using the --user option or check the permissions. WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: You are using pip version 21.1.1; however, version 21.1.2 is available. You should consider upgrading via the 'c:\python39\python.exe -m pip install --upgrade pip' command. -
How to read html input \t as a tab instead of as \\t
Okay, so I tried to look for a solution for about one hour and couldn't find anything that works. Let me describe the problem. I have a simple html form where the user uploads a file (.csv) and then also gives a delimiter for that file that I will be using to read it. The problem arises when the user submits a tab delimiter \t. When I try to access it in django delimiter = request.POST['delimiter'] I get a string \\t which just corresponds to a string \t (not a tab). Is there a way to read the input as a tab or somehow convert anything with the escape character to the right form. The only way I figured out would be to do delimiter.replace('\\t', '\t') But then I would have to do this for \n etc. so there has to be a better way. -
Dynamically assign names to variables in Python for loop
In my project, I want to be able to create a list of Querysets, where each Queryset is named after the category of their respective items. I am familiar with dynamically naming variables in the context of system paths/directories (where I use f'{}), but I'm unsure how to utilize any aspect of this in my current problem. I intended for my function to look something like this: def productsfromcategory(categories): productcontext = [] for category in categories: {dynamicallynamedvariable} = Product.objects.prefetch_related("product_image").filter(category=category)[15] print(dynamicallynamedvariable) biglist.append(dynamicallynamedvariable) In this, I meant for dynamicallynamedvariable to be the name of the current category being looped through but I'm unsure as to how to implement this. Any advice on how to tackle this problem would be much appreciated. -
How to get a list of all the Product Attributes associated with the Products displayed on a Product Category Page?
On the Product Category pages a set of Products are displayed using a HTML template with context from the view.py. In the sidebar of the HTML page, I want to display all the Product Attributes associated with the available Products on the page (here's an example). In other words, I want to access the Product Attributes in the template file of the Product Categories. The Product Attributes have the Product Categories as foreign keys, as seen in the code below. # views.py # class ProductCategoryListView(ListView): template_name = "products/product_categories.html" # Default fetch template location: <blog>/<modelname>_list.html #queryset = Product.objects.filter(categories_id = ) # e.g. id=1 def get_queryset(self): self.category = get_object_or_404(ProductCategory, slug=self.kwargs["slug"]) #id=self.kwargs["id"] return Product.objects.filter(categories=self.category) # categories_id=self.category.id #return Product.objects.filter(categories__contains = self.category.get_descendants(include_self=True)) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Context of Product Category context['full_name'] = self.category.full_name context['ancestors'] = self.category.get_ancestors context['category'] = self.category context['descendant_count'] = self.category.get_descendant_count context['descendants'] = self.category.get_descendants(include_self=False) context['siblings'] = self.category.get_siblings(include_self=False) context['filter'] = ProductFilter(self.request.GET, queryset=self.get_queryset()) attributes = [] for product in Product.objects.filter(categories=self.category): attributes.append(...) context['attributes'] = attributes # Get attributes of the category return context # models.py # class ProductAttributes(models.Model): """ The Product Attributes Table contains product attributes or features for the product category. """ product_category … -
REST api for system admin
i am trying to understand what is special in REST api. I am from a infra admin background and for me a HTTP server handling GET, PUT and POST looks like a REST end point. is this magic lies in the word "framework". which define some standards for communication over HTTP. other than that it just like a webserver. example: GET /users is REST GET /users?id=user1 is not REST why the 2nd one is not REST? django vs django rest framework DRF? if i read a django code -- in urls.py urlpatterns = [ path('/users', views.get_user), ] -- in views.py def users(request): if request.method == "GET": return JsonResponse({'users':'all_users'}) if request.method == "POST": ## add user return JsonResponse({'success':'OK'}) is this /users endpoint is not REST? what will be the difference with DRF can anyone please explain this in a layman term people other than development background can understand? -
Issue Creating Django Models
I'm trying to create some new tables, through Django Models, but, everytime I try to Migrate the changes, appears the following error. It says it is a syntax error, though I can't detected. What I'm doing wrong? Operations to perform: Apply all migrations: RegistrarProyecto, admin, auth, contenttypes, sessions, vuelos Running migrations: Applying RegistrarProyecto.0008_auto_20210621_1223...Traceback (most recent call last): File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error models.py from django.db import models from django.db.models.fields import CharField from django.db.models.fields import IntegerField # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" views.py from django.http.response import HttpResponse from django.shortcuts import render from django.shortcuts import redirect from .models import Proyecto # Create your views here. def index (request): return render (request, "RegistrarProyecto/index.html", { "Proyecto": Proyecto.objects.all() }) def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto,ResponsableProyecto=ResponsableProyecto,DescripcionProyecto=DescripcionProyecto) return redirect("/RegistrarProyecto") return render(request, 'RegistrarProyecto/Registro.html') def financiamiento(request): return render(request,"RegistrarProyecto/financiamiento.html") -
Field '_id' expected a number but got 'top' in Django Rest Framework
I already seen this type of questions here but I am not able to reproduce the solution. I'm trying to get Top BlogPosts from my model in relation with their rating. #models.py class BlogPost(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png' ) description = models.TextField(null=True, blank=True, help_text="Description Here ") rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.createdAt) class BlogPostReview(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) Serializer #serializers.py class BlogPostReviewSerializer(serializers.ModelSerializer): class Meta: model = BlogPostReview fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): reviews = BlogPostReviewSerializer( many=True, read_only=True) class Meta: model = BlogPost fields = '__all__' def get_reviews(self, obj): reviews = obj.blogpostreview_set.all() serializer = BlogPostReviewSerializer(reviews, many=True) return serializer.data Now comes to Views ... Problematic one @api_view(['GET']) def getTopBlogPosts(request): blogposts = BlogPost.objects.filter(rating__gte=4).order_by('-rating')[0:10] serializer = BlogPostSerializer(blogposts, many=True) return Response(serializer.data) URLs #urls.py path('top/', views.getTopBlogPosts, name='top-blogposts'), When I try to load top posts this error comes ValueError: invalid literal for int() with base 10: 'top' ValueError: … -
How to generate a choices tuple for django models field to use in a form
Trying to create a choice field based on another model I want my choices to be mapped like username: first_name + last_name I tried doing something like this(Note, I am adding on user_choices and choices=user_choices. The model already existed before me making these changes.) Here's what my models.py looks like: from django.contrib.auth.models import User owner_choices = [ tuple(User.objects.values_list('username', 'first_name' + 'last_name')) ] class ErrorEvent(models.Model): """Error Event Submissions""" event_id = models.BigAutoField(primary_key=True) owner = models.IntegerField(verbose_name="Owner", blank=True, choices=owner_choices) and here's my forms.py from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = ErrorEvent # fields = exclude = ['event_id'] widgets = { 'owner': forms.Select(), } Currently the owner_choices doesn't work, I get an error that says: ERRORS: app.ErrorEvent.owner: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Any recommendations on what else I can try, or how would I go about fixing my problem? Thank you in advance! -
How to store the default value for a Django form in the database?
I have a page with bookmarks and I want to implement several types of sorting for them. The user chooses the type of sorting and it's stored in the database. He/she sees the chosen type of sorting as the default value for the select-menu. I wrote this: class BookmarksSortingForm(forms.Form): SORTING_CHOICES = [(1, "новым"), (2, "имени"), (3, "звёздам -"), (4, "звёздам +")] bm_sorting = forms.ChoiceField(SORTING_CHOICES) # https://stackoverflow.com/questions/6325681/passing-a-user-request-to-forms # In your view: form = MyForm(..., request=request) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super().__init__(*args, **kwargs) self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1][1] def get_current_sorting(self): user = User.objects.get(username=self.request.user) return user.profile.bookmarks_sorting # small integer, default = 1 But I get "TypeError: init() takes 1 positional argument but 2 were given" at the line with bm_sorting. How could I fix this? Django version is 3.2.4. -
Django URL not rendering templates
Instead of directing me to the page django is simply returning the following error: “C:\Users\RodrigoPinto\Desktop\Insider\users\register” does not exist This is my url; from django.urls import path from users import employee_views from users import views as auth_views from django.contrib.auth.views import LoginView, LogoutView app_name = 'users' urlpatterns = [ path('login/', LoginView.as_view(template_name='users/login.html')), path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('register/', auth_views.Register.as_view, name='register'), path('profile/', auth_views.Profile.as_view, name='profile'), path('listView/', employee_views.AccountsListView.as_view, name='listView'), path('update/<pk>/', employee_views.AccountsUpdate.as_view, name='updateView'), path('password_update/<pk>/', employee_views.update_password, name='password_update'), path('delete/<pk>/', employee_views.AccountsDelete.as_view, name='deleteView'), ] and on the main app i have this inside the URL; from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import urls as user_urls app_name = "inside" urlpatterns = [ path('admin/', admin.site.urls), path('', include('inside.urls')), path('users/', include(user_urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've been over this code for the last two hours and I cant understand what I'm doing wrong. Maybe someone can see something that I'm missing. Also my template directory in settings is configured like this; template_dir = [ os.path.join(BASE_DIR, 'users', 'templates'), os.path.join(BASE_DIR, 'forums', 'templates'), ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': template_dir, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django app engine can not connect to db No such file or directory Is the server running locally and accepting connections on Unix domain socket
I have a Django app that I built, I am trying to upload the app into the app engine, but for some reason, I am getting the error could not connect to server: No such file or directory. Is the server running locally and accepting connections on Unix domain socket I already upload another Django app to GCP using the app engine, but this time is different; my guess is something about PostgreSQL. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'main', 'USER': os.getenv('USERNAME'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv("HOST"), 'PORT': '5432' } } I tried removing the port, change it, etc.. locally. The app is running and can connect to the proxy; when I deploy the app, it can not connect. And I made sure I close the local connection before I deploy the app just in case. My old app is running with the same configuration except for engine 'django.db.backends.postgresql_psycopg2' The reason I change the engine here was that django postgresql -
NOT NULL constraint failed: users_profile.user_id django
I am trying to update the profile of a particular user and I have to update 2 different models and forms.. The User model and custom Profile model.. I also have 2 different forms, the UserUpdateForm and ProfileUpdateForm I am using class based views models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.urls import reverse User._meta.get_field('email')._unique = True class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='images/no_picture.jpg', upload_to = 'profile_pics') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.user.username} Profile' def save(self,*args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.avatar.path) def get_absolute_url(self): return reverse('profile', kwargs={'username': self.user}) views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] second_form_class = ProfileUpdateForm def get_success_url(self): user = User.objects.get(username=self.request.user) return reverse_lazy("profile", kwargs={self.slug_url_kwarg:user}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form2"] = ProfileUpdateForm(self.request.POST, self.request.FILES, instance = self.request.user.profile) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form2 = self.second_form_class(request.POST, request.FILES) if form2.is_valid(): form2.save() What is this error that I am getting and how to solve it? I have to … -
function .load() doesn't return data after submit form django
I've got a problem with the function .load() without refresh doesn't return data after submit form django.. I'm new in JS and Django. my view : def accueil(request): if request.method == 'POST': form_plot_one_way = plot_onewayForm(request.POST) if request.POST.get('Plot_one_way_analysis'): if form_plot_one_way.is_valid(): request.session['Key_plot_oneway_coverage'] = form_plot_one_way['Key_plot_oneway_coverage'].value() request.session['Key_plot_oneway_nb_interval']=form_plot_one_way['Key_plot_oneway_nb_interval'].value() listbox_values = [key for key in fig_dict.keys()] print("listbox values : " ) print(listbox_values) my html : <form action="{% url 'accueil' %}" id='form-Plot_one_way_analysis' method="POST" enctype="multipart/form-data" class="norefresh_load"> {% csrf_token %} <button type="submit" name="Plot_one_way_analysis" class="btn btn-primary" id="Plot_one_way_analysis" value="Plot_one_way_analysis" onClick="ModalWindows(this.id)">Plot One-way analysis </button> with the following size : {{ form_plot_one_way.Key_plot_oneway_coverage }} Maximal number of modalities for one variable : {{ form_plot_one_way.Key_plot_oneway_nb_interval }} </form> {{ listbox_values }} // i can't display it <div id="myModal-Plot_one_way_analysis" class="modal"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>One way analysis</h2> </div> <div class="modal-body"> <p>Features</p> {{ listbox_values }} // also here i can't display it </div> <div class="modal-footer"> <h3>Export</h3> </div> </div> </div> my js : $('.norefresh_load').submit(function(e){ e.preventDefault(); // avoid to execute the actual submit of the form. console.log(e); let button_i = null; for(let i = 0; i < e.target.length; i++) { if(e.target[i].type == "submit") { button_i = i; break; } } if(button_i != null) { var button = $(e.target[button_i]); console.log(button.parents('form')); var id = $(this)[0].id; console.log(id); … -
How to check for `--keepdb` flag in Django
I've created an AppConfig that uses the post_migrate signal to run some extra SQL every time I do a migration. In my tests sometimes I use --keepdb to speed up running the tests but it's still triggering the post_migrate signal. How can I check to see if the --keepdb flag was used so I can skip running my extra SQL commands? I've looked in the Django documentation and the source code and I can't seem to find any way to do that. -
Static json file in Django project loads fine with python manage.py runserver but not with apache
I have a django rest framework project with a folder called data inside root directory. Inside data folder there is a json file used to store and read some internal app data, so this file is not sent to apps users. So, this file can be accessed from app when is run with python manage.py runserver, but when I use apache server a File not found error is thrown. What can I do about it? Thanks in advance. This is the project structure django_project └── venv ├── data ├── file.json └── django_project ├── init.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py And this is the apache config file for static files Alias /static /home/mach/django_project/data <Directory /home/mach/django_project/data> Require all granted </Directory> -
Django Request Session Value changes when accessed from another dev server port
I'm currently hosting two development servers on two different ports for the same Django App. I thought that by running the app on two different ports it would isolate the variables and make the two servers run independently. However, when I change a request.session variable on one of the ports, it also changes the value on the other port. Why does this happen?