Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Extension Management job
I'm trying to implement django extension management job. I would like to know how could I fire the job inside django in order to run the code daily and specify exact time like 4:00 am in django extension management job. so far code given below: from django_extensions.management.jobs import DailyJob class Job(DailyJob): help = "Send notification On Instruction Instances" def execute(self): print("job executed at 4:00 Am") Many thanks -
Multiple users can login to same account using their own credentials in django platform
Suppose there is User-A : userA@gmail.com from the organization XYZ. User-A can login using his credentials (username and password). After this, OTP is sent to his username (username is same as email) and once OTP is verified, he can login to the platform. Now suppose User-A works in team of 3 people (User-B, User-C and User-D) and he wants his teammates to login to the platform but using there own credential but on the same platform containing information of User-A. In this way, User-A does not have to give OTP again and again to his teammates and other user can access the platform using their email and OTP. Example: User-B logins to the platform using userB@gmail.com (OTP sent). After OTP verification, logged into userA@gmail.com without asking OTP from user-A. How can I implement this? Below is the model.py class Customer(models.Model): user = models.OneToOneField(User, null=True, blank =True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) name = models.CharField(max_length=200, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, unique=True) phone = models.CharField(max_length=200, null=True) platformLogo= models.ImageField(upload_to=upload_path, default='logo.png', null=True, blank=False) Here is my forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Customer from django import forms … -
Elastic search django framework
I am new to elastic search. Can someone please let me know how can I extract data from an elastic search using the Django REST framework? Most of the tutorial available is creating the elastic search index. In my case, I already have the indexes available in the elasticsearch and need to just write code to extract the data. Can you please also let me know how can I get the data of keyword and nested data types? I will be very thankful to you. -
Not specifying volumes within service docker-compose.yml
Docker version 20.10.17, build 100c701 I have a vite, vue 3 frontend and django backend with postgres database, celery and redis. When I do not include volumes for api and celery service docker compose up is successful. If I add volumes to api and celery (./api:/api) api: build: context: ./backend/backend dockerfile: Dockerfile ports: - "8000:8000" command: > sh -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py wait_for_db && python3 manage.py runserver 0.0.0.0:8000" volumes: - ./api:/api/ environment: - DB_HOST=db - DB_NAME=${DATABASE_NAME} - DB_USER=${DATABASE_USER} - DB_PASS=${DATABASE_PASSWORD} depends_on: - db celery: restart: always build: context: ./backend/backend command: celery -A backend worker -l info volumes: - ./api:/api/ environment: - DB_HOST=db - DB_NAME=api - DB_USER=${DATABASE_USER} - DB_PASS=${DATABASE_PASSWORD} depends_on: - db - redis - api then I get the following error: Error: Invalid value for '-A' / '--app': Unable to load celery application. The module backend was not found. which tells me that the path for the volume is not correct - though I am not sure what I should set it as. Is there any harm in not specifying volumes for these services? folder structure . ├── backend │ ├── backend │ │ ├── backend │ │ ├── core │ │ ├── … -
populating many form rows with model instances in django not working
Hy guys, am new to django and am trying to build a post and comment system with django. I want whenever an individual post is clicked to be commented on, the post be already populated and also, the request.user be already populated, so that the commenter wont have to select which post he's commenting on or selecting who the commenter is. I actually achieved this when a user wants to make a post, his name will populate the author filed. @login_required(login_url="login") def make_tweet_view(request): author = request.user form = make_tweet_form(initial={"author": author}) if request.method == "POST": form = make_tweet_form(request.POST or None) if form.is_valid(): form.save() context= {'forms': form} return render(request, "hometweet/make-tweet.html", context) But somehow trying this doesnt work for my comment view mycomment view. def comment_view(request, id): posts = Post.objects.get(id = id) user = request.user forms= comment_form(initial={"user": user, "posts":posts}) if request.method == "POST": forms= comment_form(request.POST or None) if forms.is_valid(): forms.save() context = {"forms": forms} return render(request, "hometweet/comment.html", context) my models and thier relationships class Post(models.Model): content = models.TextField() pics = models.ImageField(null= True, blank= True, upload_to= 'images/') date_created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name= "post_author") def __str__(self): return f"{self.content}" class Coment(models.Model): comment_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name= "post_comments") comment_author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name= "comment_author") … -
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 -
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) -
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. -
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: …