Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MySQL to PostgreSQL migration converted camelCase columns to simple format. Leading to Column does not exist error in Django ORM
I migrated MySQL database to PostgreSQL using pgloader. I am using Django ORM to execute the queries. The database fields are defined in camel case but after the migration the postgres columns are replaced to normal format. e.g brochureName is changed to brochurename. This is causing "Column does not exist" error in the application. What is the best way to handle this issue? I have lots of columns and queries already defined at many instances. -
Django: AttributeError: 'function' object has no attribute 'as_view' showing in urls.py
i have written alot of class based views, and also configured it's urls but this particluar view is showing this error AttributeError: 'function' object has no attribute 'as_view' i cannot tell what is going on with the view urls.py path('<slug:course_slug>/<slug:quiz_slug>/results/', views.QuizResultsView.as_view(), name="quiz_results"), views.py @method_decorator([login_required, teacher_required], name='dispatch') class QuizResultsView(DetailView): model = Quiz context_object_name = 'quiz' template_name = 'classroom/teachers/quiz_results.html' def get_context_data(self, **kwargs): quiz = self.get_object() course = Course.objects.get(slug=course_slug) quiz = Quiz.objects.get(slug=quiz_slug, course=course) taken_quizzes = quiz.taken_quizzes.select_related('student__user').order_by('-date') total_taken_quizzes = taken_quizzes.count() quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score')) extra_context = { 'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'total_questions':quiz.questions.count() } kwargs.update(extra_context) return super().get_context_data(**kwargs) def get_queryset(self): self.kwargs['course_slug'] self.kwargs['quiz_slug'] return self.request.user.quizzes.all() -
Making an integerfield into selectable dropdown numbers from 0 to the value of the integerfield in django
I have been trying to make the value of an integerfield show up as a dropdown list with numbers ranging from 1 to the valueof the integer field for example 47 , the numbers between 1 and 47 will show up as a dropdown menu. i managed to get this code working: HTML PAGE that's resposible for fetching the integerfield ID since i am displaying it in another model as a foreignkey, this is where i am also trying to make the dropdown list of numbers show up {% for i in rayons %} <option id="empla"value="{{ i.pk }}">{{ i.Nombre_des_Emplacments }}</option> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var n = {{ i.Nombre_des_Emplacments }}; for (var i = 0; i < n+1; i++) { //creates option tag jQuery('<option/>', { value: i, html: i }).appendTo('#empla'); } </script> {% endfor %}[![enter image description here][1]][1] Result : note that the Num field is what i am talking about and it's dependent on the previous field so when something other than A1 is selected the Num field will change -
Why am I getting an NameError error when I use "if any" on Django [duplicate]
I’m on Django and I try to get subject of mail and check if a certain word are in the subject. For that I do : Firstly I declare a list of word which I will then look for. lst_RAS = [ "ras", "RAS", "réussi ", "terminée", "terminé" ] Then I retrieve the subjects of mail that I receive but it is not important I think since I make sure to retrieve or transform them in string. temp_dict = {} s = mail["Subject"] temp_dict['Subject'] = decode_str(s) Currently I know it's worth a string without worry On the other hand, I am now trying to check if the words on my list are part of my subject. After looking at a lot of advice here it seems the best way to go is this. if any(word in temp_dict['Subject'] for word in lst_RAS): But I get the following error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\pheni\Documents\Projets Django\mail_manager\venv\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( … -
{detail: 'CSRF Failed: CSRF token missing.'} Django and React
even though csrf is provided, it just does not recognize it at all in frontend side (note it works perfect on backend host, but not frontend) views.py: class CheckAuthenticated(views.APIView): def get(self, request): if request.user.is_authenticated: return Response("Authenticated") else: return Response("Not Authenticated",status=401) class PostView(viewsets.ModelViewSet): serializer_class = serializer.PostSerializer def get_queryset(self): queryset = models.Post.objects.all() return queryset @method_decorator(ensure_csrf_cookie,csrf_protect) def create(self,request): authentication_classes = [SessionAuthentication] permissions_classes = [IsAuthenticated] post = serializer.PostSerializer(data=request.data) if post.is_valid(): title = post.data['title'] description = post.data['description'] models.Post.objects.create(title=title,description=description,user=User.objects.first()) return Response("post created successfully.") return Response("post creation failed.") i have also a resource that receive csrf token: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return Response("Success") in urls.py: urlpatterns = [ path('csrf/',views.GetCSRFToken.as_view(),name='csrf'), path('isauthenticated/',views.CheckAuthenticated.as_view(),name='authenticated'), ] now in frontend: let handleSubmit = (e)=>{ e.preventDefault() console.log(Cookies.get('csrftoken')) axios.post('http://127.0.0.1:8000/posts/',post,{withCredentials:true},{headers:{'X-CSRFToken':Cookies.get('csrftoken')}}).then((res)=>{ console.log(res.data) }).catch((e)=>{ console.log(e.response.data) console.log(Cookies.get('csrftoken')) }) } useEffect(()=>{ axios.get('http://127.0.0.1:8000/posts/').then((res)=>{ setPostList(res.data) }) axios.get('http://127.0.0.1:8000/csrf/',{headers:{Authorization:null},withCredentials:true}) },[]) the csrf is being printed in the dev console any idea? -
Terminate an endpoint from within a function Django
Is there a way to end an endpoint from inside a function? I know I can make the function to return True or False, then evaluate that answer and return, but it would be a lot cleaner if I can do something like this: def custom_endpoint(self, request): check_something(request) return Response("ok") check_something(request) should check variables and then end the execution of the endpoint if one of the variables is not correct. Thanks!! -
django-grappelli installed but not showing in lib/site-packages of my venv and not found by django itself
I have activated a virtual environment to a django project. I have installed django-grappelli using pip into that virtual environment. pip install django-grappelli When calling 'pip list', I can see it's installed. Package Version ---------------- ------- asgiref 3.5.2 Django 4.0.5 django-grappelli 3.0.3 pip 22.1.2 psycopg2 2.9.3 setuptools 58.1.0 sqlparse 0.4.2 tzdata 2022.1 In my project setting I added grappelli app above django contrib as instructed by grappelli docs: INSTALLED_APPS = ( 'grappelli', 'django.contrib.admin', ) Then I added the url confs accordingly as instructed by grappelli docs: from django.conf.urls import include urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS path('admin/', admin.site.urls), # admin site ] When checking if it is all good calling py manage.py check I get a ModuleNotFoundError: No module named 'grappelli' error. I looked at lib/site-packages and in fact, django-grappelli isn't showing there (see picture). I tested in a python shell importing for 'grappelli' and 'django-grappelli' but python says no module found for each of these. Essentially pip shows it's installed, but python, hence django, think otherwise. Tested grappelli in another simpler project and did not run into this problem. There is obviously something I am missing here and it is probably right under my nose, but thus … -
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) + ']}'