Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter items by query params if one param is None
I have get request GET /themes with query params: category_id: integer level: integer it's maybe GET /themes?category_id=1&level=1 or GET /themes?category_id=1 etc So I need get items by filter: def get(self, request): query = request.GET category_id = query.get('category_id') # return value or None level = query.get('level') # return value or None items = Theme.objects.all() qs = items.filter(category_id=category_id, level=level) But category_id and level can be None, and I need change code qs = items.filter(category_id=category_id, level=level) if params is None My code: if category_id and level: qs = items.filter(category_id=category_id, level=level) elif not category_id and level: qs = items.filter(level=level) elif category_id and not level: qs = items.filter(category_id=category_id) else: qs = items.filter() But I think it's a terrible code -
Django circular import error on views - any ideas?
I am trying to following the tutorial here: https://code.visualstudio.com/docs/python/tutorial-django. Once I get to point 6 in the above - I am getting the following error: Any ideas ? raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hello.urls' from '/Users/Desktop/djangosite/hello/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
Update a Model from another Model in REST
I want to update issold=True in the Apartment Model when a transaction is created. But I confused to do it in REST serializers.py: class ApartmentSerializer(serializers.HyperlinkedModelSerializer): seller = serializers.ReadOnlyField(source='seller.username') class Meta: model = Apartment fields = [ 'url','seller','address','arena','price','description','timestamp' ] class TransactionSerializer(serializers.HyperlinkedModelSerializer): buyer = serializers.ReadOnlyField(source='buyer.username') class Meta: model = Transaction fields = [ 'id','buyer','apartment','timestamp' ] views.py: class ApartmentViewset(viewsets.ModelViewSet): queryset = Apartment.objects.filter(issold=False).order_by('-timestamp') serializer_class = ApartmentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(seller=self.request.user) class TransactionViewset(viewsets.ModelViewSet): queryset = Transaction.objects.all().order_by('-timestamp') serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(buyer=self.request.user) -
How to change file type before save instance in django
i am implementing an app using Django, in my case user upload file and after validate it save that instance(file field in my model) i want to zip it and save zip file in my instance, how is it possible? thanks in advance -
How to assign values to pandas dataframe?
This is my code , I am uploading a file that file contains multiple columns status column have no data i am assign the data here but geeting error? def post(self, request, *args, **kwargs): modelname = request.data['modelname'] serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) dataset = Dataset() file = serializer.validated_data['file'] imported_data = dataset.load(file.read(), format='xlsx') field_headers = imported_data.headers for x in imported_data: ''' uploading xl file with particular data what user mentioned in xl we are looping the xl data and appending into the database with same fields ''' model = ModelSchema.objects.get(name=modelname).as_model() table_name = model._meta.db_table fields_list = field_headers fields = [f.name for f in model._meta.fields] list_difference = [element for element in fields_list if element not in fields] if list_difference: return Response({'headers is not same as DB': list_difference}) conn = psycopg2.connect(dbname=settings.DATABASES['default']['NAME'], user=settings.DATABASES['default']['USER'], password=settings.DATABASES['default']['PASSWORD'], port=settings.DATABASES['default']['PORT'], host=settings.DATABASES['default']['HOST'] ) cur = conn.cursor() df = pd.read_excel(file, engine='openpyxl') print(df,'kkkkkkkkkkkkkkkkkkkkkkkk') dff = df.assign(status='newtickets') print(dff,'sssssssssssssssssss') # dff.replace(np.NAN, inplace=True) temp_csv = StringIO() writer = csv.writer(temp_csv) writer.writerows(dff.values) temp_csv.seek(0) with conn.cursor() as c: c.copy_from( file=temp_csv, table=table_name, columns=fields_list, sep="," ) cur.commit() print(cur,'ppppppppppppppppppp') return Response({'sucessfully uploaded your file'}, status=status.HTTP_200_OK) -
In Django is it possible to Add blank row in table B if table A has duplicate values?
I have two tables in my Django project both displayed side by side. Currently those are comparing 1st columns of each and displaying matching values in front of each other along with the rest of the row. Is it possible to somehow create a blank tr (table row) in table B if in table A a value appears twice or in first column and in table B it is only once? The blank tr in table B should appear in front of the duplicate value in table A, so that all other rows in table B shift down and rest of the matching values be compared to each other. This picture shows what is currently happening and what i need. -
Django filter get latest records of each employee
I have a table named employee Employee empid name status created_datetime EMP001 NAMEA STATUS-B 2022-06-13 14:00:00 EMP001 NAMEA STATUS-A 2022-06-13 13:00:00 EMP002 NAMEB STATUS-B 2022-06-13 12:00:00 EMP003 NAMEC STATUS-A 2022-06-13 11:30:00 EMP001 NAMEA STATUS-C 2022-06-13 11:00:00 EMP001 NAMEA STATUS-D 2022-06-13 10:00:00 EMP003 NAMEC STATUS-B 2022-06-13 09:00:00 What i need to fetch is that the latest records of each employee. For example empid name status created_datetime EMP001 NAMEA STATUS-B 2022-06-13 14:00:00 EMP002 NAMEB STATUS-B 2022-06-13 12:00:00 EMP003 NAMEC STATUS-A 2022-06-13 11:30:00 these are the latest records of the employee EMP001,EM002 and EMP003 -
Django TypeError: QuerySet indices must be integers or slices, not str
enter image description here Please I am stick at this stage. I created a navbar html that I included in base.html. I having difficulty displaying it. The images shared show the error I am getting. I have all sort of methods to debug but I cant seem to get it. Please any help would be appreciated. enter image description here -
Django HttpResponse as Excel file
I am trying to send an excel with color coding in header for the client-side to download it. For some reason, I am not able to see any color in the header. response = HttpResponse(content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'attachment;filename="test.xlsx"' writer = pd.ExcelWriter(fname) with pd.ExcelWriter(fname) as writer: df_final.to_excel(writer, sheet_name='test', index=False) wb = openpyxl.load_workbook(fname) ws = wb['test'] # import openpyxl.utils.cell mand = [] for row in ws.iter_rows(): for cell in row: if cell.value == "Mandatory": alp = cell.column_letter mand.append(alp) for i in mand: c = str(i)+str(1) print(ws[c].value) ws[c].fill = PatternFill(fgColor="FC2C03", fill_type = "solid") ws.delete_rows(2) wb.save(response) This is the code I am using. Please help me with it. -
EmbedVideoField is not being imported
I am trying to implement video embedding functionality. I want to use 'django-embed-video'. So I download the package like: pip3 install django-embed-video Then I add 'embed_video' to my installed apps in the settings.py file However, then when I try to import 'EmbedVideoField' from 'embed_video.fields' in my models.py file, it is not being imported. I can't understand why this is the case? Am I missing something? -
Is there a way to get the number of students each teacher is teaching in this django model
I have three models class Courses(models.Model): name = models.CharField(max_length=100) class Student(models.Model): email = models.EmailField(max_length=200,null=False,blank=False) courses = models.ManyToManyField(Courses) class Teachers(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Courses) students = models.ManyToManyField(Student) How can I write a query to get the number of students each teacher is teaching -
Get request in views.py with id
I have a model Word. I need change method get in WordView class in views.py file so that it processes: GET /words/{id} request. Example response: { "id": 1, "name": "to ask out", "translation": "Пригласить на свидание", "transcription": "tuː ɑːsk aʊt", "example": "John has asked Mary out several times.", } My code in get method: from django.views import View from django.http import JsonResponse from models import Word class WordView(View): def get(self, request, id): # Maybe there shouldn't be `id` argument item = Word.objects.get(id=id) items_data = [{ 'id': item.id, 'word': item.word, 'transcription': item.transcription, 'translation': item.translation, 'example': item.example, }] return JsonResponse(items_data[0]) Question 1: how I need change ulrs.py (for request /words/{id}) urlpatterns = [ path('admin/', admin.site.urls), path('words/{id}', WordView.as_view()), ] Question 2: how I need change method get -
How to write unit test for this source code in Django?
My code: for customer_license in customer_licenses: users_in_this_license = customer_users.filter( licensetype=customer_license['licensetypeid'] ) users_to_invite = abs(users_in_this_license.count() - \ users_invitations.filter( user__in=users_in_this_license ).values('user').distinct().count()) if users_to_invite > 0 \ and users_to_invite + customer_license['number_of_active_accounts'] > \ customer_license['number_of_purchased_license']: raise InvitationException( _('msgErrorInviteAccountNumberOfLicensesWillExceed').format( str(customer_license['license']) ) ) My test: class InviteMultipleUsersTest(TransactionTestCase): """ Test module for inviting a multiple users """ reset_sequences = True def setUp(self): self._egateid = setup.egate_id_generator() self._url = 'invite-user' # Step 1. create a customer self._customer = setup.create_customer(self._egateid) # Step 2. create a group _group = setup.create_group(self._customer) # Step 3. create a policy setup.create_policy(self._customer, _group.policy) # Step 4. create license type _licensetype = setup.create_license_type() self.data1 = { 'customer': self._customer, 'group': _group, 'licensetype': _licensetype[0], 'name': 'Dummy User' + setup.name_generator(10), 'email': 'peter.parker@soliton.co.jp', 'note': 'note', 'licensekey': 'OVMUUSTJIJWXMYKNM5WTGM2PMNWTEST1', 'isdisabled': False, 'summary': '{}' } self.data2 = { 'customer': self._customer, 'group': _group, 'licensetype': _licensetype[0], 'name': 'Dummy User' + setup.name_generator(10), 'note': 'note', 'licensekey': 'OVMUUSTJIJWXMYKNM5WTGM2PMNWTEST2', 'isdisabled': False, 'summary': '{}' } self.user1 = User.objects.create(**self.data1) self.user2 = User.objects.create(**self.data2) self.ids = '{"data":[' + str(self.user1.id) + ',' self.ids += str(self.user2.id) + ']}' -
Django Authentication Form Customize, Doubles Field
The Goal is To Customize Form, Then Pass it to LoginView. I am using AuthenticationForm after Customizing it, but i see it repeats extra one input, I guess it is for username, i need only two inputs, E-Mail and Password. any advice. Forms: class AccountSignInForm(AuthenticationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'E-Mail..'}), label='E-Mail') password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password..'}), label='Password') class Meta: model = Account fields = ['email', 'password'] Views: class AccountLoginView(LoginView): template_name = 'accounts/login.html' form_class = AccountSignInForm success_url = 'HomePageView' URLS: app_name = 'accounts' urlpatterns = [ path('sign-in', views.AccountLoginView.as_view(), name='login'), ] HTML: <h1>Login Form</h1> <form method="POST"> {% csrf_token %} {% for field in form %} <div>{{ field.label }}</div> <div>{{ field }}</div> {% endfor %} <input type="submit" value="Login" /> </form> enter image description here Any Ideas,. -
Get url kwargs in class based views
I need to retrieve the value of the pk written in the url in my class based view : path('<int:pk>/data/', views.DataView.as_view(), name='data'), However, what I saw everywhere was the pk retrieved in the definition of methods like get or post. What I want is to be able to use it to define my class variables, because I need to do get the same value from this pk in every method inside my class, like below : class DataView(ContextMixin, UpdateView): pk = get_pk_from_url ... value = ... def get(self, request, *args, **kwargs): value = self.value # Do something with value def post(self, request, *args, **kwargs): value = self.value # Do something with value I got an idea while writing this question, which is to define a method that will do what I need, then calling this method in my other methods. class DataView(ContextMixin, UpdateView): def get_value(self): self.pk = self.kwargs['script_id'] ... self.value = ... def get(self, request, *args, **kwargs): self.get_value() value = self.value # Do something with value def post(self, request, *args, **kwargs): self.get_value() value = self.value # Do something with value However, I don't know if there's another way, which is why I still wanna ask my question. Hope this was … -
How to get id of ENUM object in views.py django
I'm writing first django project and I need create a view for my model. I try to write get method, and it should return me json, where there is the id of level field (not name and not value, I need id) from enum import Enum class Level(Enum): A1 = 'Beginner' A2 = 'Elementary' B1 = 'Intermediate' B2 = 'Upper-Intermediate' C1 = 'Advanced' C2 = 'Proficiency' class Theme(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) level = models.CharField(max_length=30, choices=[(lev.name, lev.value) for lev in Level], blank=True, null=True) How to get id of enum object in views.py: class ThemeView(View): def get(self, request): qs = Theme.objects.all() items_data = [] for item in qs: items_data.append({ 'id': item.id, 'category': item.category.id, 'level': item.level.id, # here I need id object, but it's doesn't work 'name': item.title, }) data = { 'items': items_data, } return JsonResponse(data) -
Displaying recently used apps in django
i have 10 applications and one project in django. every application name and description and url is stored in database now my task is to show recently used apps based on user basis is there any possibility to show recently used apps when user used particular application/s we need to get the history and diplay the names if need any change in models.py or suggesting to create new database is ok with me -
pyest does not detect fixtures in separate folder
I have a Django application and am writing tests using pytest and pytest fixtures. All the tests are in their respective Django apps but I wrote the fixtures in a different folder as a module. Project structure: Proj. | +apps: - core -tests -test_core.py - users -tests test_user.py | +fixtures: - __init__.py - core.py - users.py | +conftest.py I have the different fixtures in their separate files which correspond with the app names they are to be used. Am having problems with pytest detecting the fixtures I have tried creating a conftest.py file in the root of the project and importing the fixtures file as a plugin. conftest.py > pytest_plugins = [ "apps.fixtures",] I have also tried removing the coftest.py file and placing the fixtures file in the apps folder and still pytest does not detect the fixtures. Any help here would be helpful. -
how include links from main urls.py file to model urls.py file?
I am trying to include links from a 'Post/urls.py' file, to 'blog/urls.py' (admin file) but I get an error message Do you hope to help solve this problem? #Post/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.all_posts, name='all_posts'), url(r'^(?P<id>\d+)$',views.post, name='post'), ] blog/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('Post.urls', namespace ='blog')), ] Error msg: from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' (C:\xampp\htdocs\django\blog\lib\site-packages\django\conf\urls_init_.py) -
I have problem with Django + Docker + Celery
I am try to learn some deploy moments. I tried to deploy my django application on my linux debian server using Django+ Nginx + PGSQL + Celery, wrapping it all in Docker containers. But when I run django and celery separately (via build: .), I encounter the problem that celery stalks returns, for example, "no such column account_user" when accessing the database, although I have users. If you deploy django via "build: .", and specify "image: celery" to celery, then the problem arises that celery does not see django (it usually returns either "no module named "django" or "no module named "celery_app"). I don't know how clear my question is, but is there any way to deploy Django + Celery so that everything works and celery has access to the database and to the Django environment? docker-compose.yml version: "3.8" services: django: build: . restart: on-failure command: bash -c "python manage.py collectstatic --noinput && python manage.py migrate && gunicorn angelina.wsgi:application --bind 0.0.0.0:8000" volumes: - static:/home/web/home_page/static - .:/home/web/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db - redis db: image: postgres:13 restart: on-failure volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=dalorevacation - POSTGRES_PASSWORD=*UHBytr7 - POSTGRES_DB=db nginx: image: nginx restart: on-failure build: ./deploy/nginx ports: … -
share query results in django among logged in users
I have a table linked and getting data from Zapier. The records come 200rows per minute. Logged-in users are supposed to be picking these data and working on them. The problem is that there has been some confusion as to know which record has been worked on and which one has not been worked on. I have built a table to help show records which have been worked on by ticking the Treated tab Table structure. I hope I can divide the records equally amongst the logged-in Users so as not to underwhelm or overwhelm any of the users. -
Django Model become huge
In my project few models has many fields like more than 25. Like i have a model name PeriodOfStay. and it field like date_of_entry i94_number port_of_entry city ....etc (please check the image for all field) also it has many boolean fields . in one form user can multiple options. so i am confused should i put all the fields in one model. Is it best practice. I don't want split one model to more and use OneToOne Relation cause in that case i need to break up many models cause most of the models in my project are like this also i need to send all data at once in a single request. I just need to save data and show data to user. in some case i need to search by some field . Like in this form i need to search by i94_number. Is using JsonField is ok for this problem cause i need to search & filter in some case. I appreciate any help. Advance Thanks For Help. -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'snp.routing'
ASGI_APPLICATION = 'snp.routing.application' routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter ({ 'websocket': AuthMiddlewareStack( URLRouter ( chat.routing.websocket_urlpatterns ) ) }) i'm having this error while imporing ASGI_APPLICATION, how can i fix it raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'snp.routing' -
Mocking time.sleep will cause the test to fail
I wrote this test, but in order not to delay the test, I mock the time.sleep and the test will encounter an fail. from unittest.mock import patch @patch('time.sleep', return_value=None) def test_wait_for_db(self): """Test waiting for db""" with patch('django.utils.connection.BaseConnectionHandler.__getitem__') as gi: gi.side_effect = [OperationalError] * 5 + [True] call_command('wait_for_db') self.assertEqual(gi.call_count, 6) By commenting on this second line(@patch), the program will run properly. -
Django and and Nginx not adding all domain name
I have a project with Django running on a Linux machine. The project was working very well. but after we changed the domain name from "http://myservername:port/" to "https://myservername/projectname/", it doesn't work anymore. If I click on the URL, I am redirected to "https://myservername/" but not to "https://myservername/projectname/", which gives me a 404 error. And if add manually the "projectname" into the URL in the browser, it is working fine. my URLs in Django look like this: urlpatterns = [ path('', include('pages.urls')), path('dashboards/', include('dashboards.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), path('admin/', admin.site.urls), ] # and pages url: urlpatterns = [ path('', views.index, name='index-pages'), # re_path(r'^culture-crawler/$', views.index, name='home'), # # path('culture-crawler/register/', views.register_page, name='register'), re_path(r'^login/$', views.login_page, name='login'), re_path(r'^logout/$', views.logout_user, name='logout'), ] # and dashboards urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard') ] The Nginx file: upstream culture_crawler_app { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/webapps/culturecrawler/run/gunicorn.sock fail_timeout=0; } server { listen 127.0.0.1:100; server_name hammbwdsc02; client_max_body_size 4G; access_log /home/webapps/culturecrawler/logs/nginx-access.log; error_log /home/webapps/culturecrawler/logs/nginx-error.log; location /static/ { alias /home/webapps/culturecrawler/culture_crawler/static/; } location /media/ { alias /home/webapps/culturecrawler/culture_crawler/media/; } location / { # an HTTP header important enough to …