Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zoho CRM API: Python request-based POST or GET authentication + insertion of contacts
The Task## A django application that allows users to sign up and once the user clicks on the account activation link, Zoho CRM is receiving the data and a contact is created in the CRM section. The Problem I am currently working on an absolute masterpiece - the ZOHO API. I am struggling to set up the native Python code that uses POST/GET requests. Regarding the zcrmsdk 3.0.0, I have completely given up on this solution unless somebody can provide a fully functional example. The support simply blames my code. The documentation I consulted: https://www.zoho.com/crm/developer/docs/api/v2/access-refresh.html, https://www.zoho.com/crm/developer/docs/api/v2/insert-records.html Since the post request in postman API works fine I do not understand why it does not work in python code My approach Generate an self-client API code on: https://api-console.zoho.com/ Insert that code on Postman and retrieve the access or refresh token Use this access token in an add_user_contact function that is defined in the documentation It works! Response is success and it is in Zoho CRM The permsissions scope I am using is: ZohoCRM.modules.contacts.ALL, ZohoCRM.users.ALL, ZohoCRM.modules.deals.ALL, ZohoCRM.modules.attachments.ALL, ZohoCRM.settings.ALL, AAAserver.profile.ALL Picture of Post Man POST REQUEST My own Code def authenticate_crm(): """ access to response object id: response_object.get('data')[0].get('details').get('id') """ url = 'https://accounts.zoho.com/oauth/v2/token' headers = … -
How to access media files inside Javascript in Django project?
I am relatively new to Django. I have a Djano project in which I am trying to render a list of video files that are present inside the media directory in Django. I have followed all the Media URL related requisites and I am able to render the video files in a template inside an application like this: {% block content %} <video width="320" height="240" controls> <source src="{{ MEDIA_URL }}sample_video_file.mp4" type="video/mp4"> Your browser does not support the video tag. </video> {% endblock content %} and it works like a charm. However, I want to display a list of such video files that are returned from a model programmatically using JavaScript. This is my views class:- def video_quiz_data_view(request, pk): videoquiz = VideoQuiz.objects.get(pk=pk) questions = list() for q in videoquiz.get_questions(): answers = list() for a in q.get_answers(): answers.append(a.text) #questions.append({str(q.pk) + " " + q.text : answers}) print(f"Video path: {q.video_path}") questions.append({q.video_path : answers}) return JsonResponse({ 'data': questions, 'time': videoquiz.time, }) I am able to console log the response in the .js file corresponding to the .html file above. I have written an ajax function that calls the view which returns a list of video urls like sample_video_file.mp4 present inside the media directory. $.ajax({ … -
How do I use a Python utility (PyGaze) in my React Native app?
I'm a new developer working with a team developing a React Native app using Expo. We are currently using AWS to host our Django backend. The problem: Implement real time eye tracking software for users to interact with throughout the app. Is there a way to use the PyGaze utility on smartphones? Ideally with both Android and iOS. What we've tried: We worked out the old code from here http://www.pygaze.org/ and got the main GUI working (on my PC) to isolate the pupil like in the example given from YouTube: https://www.youtube.com/watch?v=KM_ruTFY8pY The issue: I haven't figured out how I would work this into our current project. My plan was to show this example window after a button press so the user can calibrate the contrast to isolate the pupil. This would fully depend on the lighting in the room, time of day, screen brightness, etc. The intention is to call the GUItest.py on that button press. Any suggestions would be greatly appreciated! Thanks, Mike -
'RegisterForm' object has no attribute 'is_valid'
This Is models.py from django.db import models class RegisterForm(models.Model): fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) pno = models.CharField(max_length=100) email = models.EmailField(max_length=200) pass1 = models.CharField(max_length=100) pass2 = models.CharField(max_length=100) This is my Views.py from django.shortcuts import render from .models import RegisterForm # Create your views here. def registerView(request): if request.method=='POST': fm = RegisterForm(request.POST) if fm.is_valid(): fname = fm.cleaned_data['fname'] lname = fm.cleaned_data['lanme'] pno = fm.cleaned_data['pno'] email = fm.cleaned_data['email'] pass1 = fm.cleaned_data['pass1'] pass2 = fm.cleaned_data['pass2'] reg = RegisterForm.save(fname = fname,lname=lname,pno=pno,email=email,pass1=pass1,pass2=pass2) reg.save() fm = RegisterForm() else: fm = RegisterForm() return render(request, 'register.html', {}) Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: AttributeError Exception Value: 'RegisterForm' object has no attribute 'is_valid' Exception Location: H:\Django\authetication\users\views.py, line 7, in registerView -
Django Admin: How to dynamically set list_per_page
I have run into the case where I am managing the codebase for a project that utilizes the django-admin portion of a site. All of the functionality of the django admin exists in normal views as well, but for some reason the client prefers to work on the admin views as opposed to the function based views... Normally, adding in a dropdown and adjusting the pagination/filter would be easy in a function based view, but the only way I can see to modify this is with list_per_page How do I add a dropdown to the admin page (preferably with the pagination buttons) and then how do I retrieve the results on the server side to alter the list_per_page value dynamically based on what the user has selected? Would adding a form to the template and retrieving a POST in the admin work? -
How to avoid creating image thumbnail every model.save() call?
I'm creating a news blog, so I decided to add a profile image. I was thinking, how to create image thumbnail better and decide to use percent resizing. def save(self, *args, **kwargs): image = Image.open(self.image) # Открываем картинку width, height = image.size # Получаем размеры картинки new_image = BytesIO() # Создаем байтовое представление resize = (width * (height // 10 * 5) // height, height // 10 * 5) # Изменение по высоте if width > height: # Если горизонтальная картинка resize = (width // 10 * 5, height * (width // 10 * 5) // width) # Изменение по ширине image.thumbnail(resize, resample=Image.ANTIALIAS) # Делаем миниатюру картинки image = image.convert('RGB') # Убираем все лишние каналы image.save(new_image, format='JPEG', quality=90) # Конвертируем в JPEG, ибо мало весит new_image.seek(0) # Возвращение в начало файла name = f'{self.image.name.split(".")[0]}.jpeg' # Имя файла # Перезапись файла в базе данных self.image = InMemoryUploadedFile( new_image, 'ImageField', # Картинка, поля сохранения name, 'image/jpeg', # Имя картинки, содержание getsizeof(new_image), None # Размер, доп инфа ) # Сохранение через другой save класса super(KvantUser, self).save(*args, **kwargs) So, as you can see, I take only a half of the image size. It helps to keep good quality of the picture and reduce its … -
Django - Troubleshooting thread locals & middleware issue with DRF ViewSets in Production
Anyone have a recommendation for approaching this challenging problem? Not sure how to troubleshoot this further. I am setting a value in thread locals in middleware using the following: from threading import local ORG_ATTR_NAME = getattr(settings, "LOCAL_ORG_ATTR_NAME", "_current_org") _thread_locals = local() def _do_set_current_variable(variable_fun, attr_name): setattr(_thread_locals, attr_name, variable_fun.__get__(variable_fun, local)) def thread_local_middleware(get_response): def middleware(request): organization = Organization.objects.get_current(request) _do_set_current_variable(lambda self: organization, ORG_ATTR_NAME) response = get_response(request) return response return middleware def get_current_variable(attr_name: str): """Given an attr_name, returns the object or callable if it exists in the local thread""" current_variable = getattr(_thread_locals, attr_name, None) if callable(current_variable): return current_variable() return current_variable I have a Manager class that all models which contain an organization FK field make use of: class OrganizationAwareManager(models.Manager): def get_queryset(self): logger.debug(f"_thread_locals attributes in manager: {_thread_locals.__dict__}") organization = get_current_variable(ORG_ATTR_NAME) queryset = super().get_queryset().filter(organization=organization) logger.debug(f"OrganizationAwareManager queryset: {queryset.query}") return queryset This all works like a charm in dev, and also works great on nearly everything in production - except in DRF ViewSets that query models with the OrganizationAwareManager. Other ViewSets work as expected, and normal django views that refer to models with the OrganizationAwareManager in view context also work fine. Literally just DRF Viewsets with OrganizationAwareManager in Production are the only issue. As you can see, I added … -
Django restful framework "The serializer field might be named incorrectly"
Hello dear stack overflowers, I've set up a Django project with restful framework and I use JSON response in order to retrieve data from the server in a structured manner. The problematic code: class ContentView(RetrieveAPIView): queryset = Container.objects.all() serializer_class = ContainerSerializer def get_object(self): queryset = self.get_queryset() serializer = ContainerSerializer(queryset,many=True) return JsonResponse(serializer.data , safe=False) Gives the following error when being executed: AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `ContainerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `JsonResponse` instance. Original exception text was: 'JsonResponse' object has no attribute 'title'. [21/May/2021 17:27:13] "GET /content/ HTTP/1.1" 500 18789 To be as clear as possible I'll attach the serializer's code: class ContainerSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=True, allow_blank=False, max_length=100) content = serializers.CharField() def create(self, validated_data): return Container.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.content = validated_data.get('content', instance.content) instance.save() return instance Before switching to RetrieveAPIView, everything worked well with the test server. The error arised while switching to this new-for-me method of making requests. Any help will be appreciated! -
Can someone help me here. I'm trying to assign more than one rule to a single user based on role's names in django DRF
Here in my model I have multiple roles for users like HR, IT, ADMIN, FINANCE, EMPLOYEE and PROJECT_MANAGER. Purpose is to assign roles to user more than one based on role names. But I'm unable to get there. Here are the models: class UserRole(HRMBaseModel): HR = 'HR' IT = 'IT' ADMIN = 'ADMIN' FINANCE = 'FINANCE' EMPLOYEE = 'EMPLOYEE' PROJECT_MANAGER = 'PROJECT MANAGER' ROLE_CHOICES = ( (HR, 'hr'), (IT, 'it'), (ADMIN, 'admin'), (FINANCE, 'finance'), (EMPLOYEE, 'employee'), (SUPER_ADMIN, 'super admin'), (PROJECT_MANAGER, 'project manager'), ) role_name = models.CharField(max_length=255, choices=ROLE_CHOICES) def __str__(self): return self.role_name class User(AbstractUser, HRMBaseModel): username = models.CharField(max_length=50, unique=True) email = models.EmailField(_('email address')) role = models.ManyToManyField(UserRole) Here is serializers.py to create user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'role', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): role_data = validated_data.pop('role') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() profile_data = { "display_name": validated_data['first_name'], "fullname": f"{validated_data['first_name']} {validated_data['last_name']}", "dob": None, "address": None, "country": None, "city": None, "state": None, "zip_code": None, "profile_avatar": None } UserProfile.objects.create(user=user, **profile_data) user.role.add(UserRole.objects.get(role_name=role_data[0])) return user Here is how I'm creating user { "email": "test_99@admin.com", "first_name": "test_99", "last_name": "test_99", "username": "test_99", "password": "test_99", "role": [3] } But this is how I want to … -
Django Error ''Field 'id' expected a number but got <Transfernews: Transfernews object (1)>.''
I am getting this error when trying to submit comments. Can anyone please tell me how to fix this? My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() news = request.POST.get("transfer_id", None) form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = User.objects.get(id=request.user.id) new_comment.transfernews_id = Transfernews.objects.get(id=news) new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My html file: {% for transfer in transfernews %} <div>Comment and let us know your thoughts</div> <form method="POST"> {% csrf_token %} <input type="hidden" name="transfer_id" value="{{ transfer.id}}"> <div class="bg-alert p-2"> <div class="d-flex flex-row align-items-start"> </div> <div class="mt-2 text-right"> {{ form|crispy }} <br> <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> <button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button> </div> </div> </form> {% endfor %} -
why am i having error whenever i tried to add image to my django project?
the idea of the base.html is not to be repeating some codes that i will need in almost all of the pages... i can easily {% extends 'homepage/base.html' %}. on every page i need it. checkout my base.html below! 1. (base.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--fonts--> <link href="https://fonts.googleapis.com/css2? family=Comfortaa:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Niconne&family=Satisfy&display=swap" rel="stylesheet"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- +0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'homepage/css/styles.css' %}"> {% if title %} <title>Amal Restaurant - {{ title }}</title> {% else %} <title>Amal Restaurant</title> {% endif %} </head> <body> {% block content %} {% endblock content %} <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> --> <!--jquery cdn--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> <!--local js files--> <script src="{% static 'homepage/js/jquery.js' %}"></script> <script src="{% static 'homepage/js/main.js' %}"></script> </body> </html> this is the index.html where i {% extends 'homepage/base.html' %}. every other thing is working well but my images. checkout my index.html below! 2. (index.html) {% extends 'homepage/base.html' %} {% block content %} <header … -
Django Docker problems
I have some problems while creating my docker container for my django application. I have my Dockerfile FROM python:3.8.6 ENV PYTHONUNBUFFERED 1 USER root RUN apt-get -y update && \ apt -y install python3-pip && \ pip3 install setuptools gitpython && \ pip install django && \ pip install stripe && \ pip install django-extensions RUN git clone https://github.com/***/*** WORKDIR /tfg/MiTfg EXPOSE 8000/tcp CMD python3 manage.py makemigrations CMD python3 manage.py migrate CMD python3 manage.py runserver localhost:8000 It works perfectly, now I run docker run --network host -p 8000:8000 1fbe And the output prints: WARNING: Published ports are discarded when using host network mode System check identified some issues: WARNINGS: Tienda.Categoria: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TiendaConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Tienda.Cliente: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the TiendaConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Tienda.CodigoDescuento: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the … -
How to annotate Django query with days calculation?
How do you annotate a Django query of a table with the calculation of days since the record was created? I want to order a table based on a combined metric of priority multiplied by days since the record was created. To get the days annotation, I'm trying to do: qs = qs.annotate(days=(ExtractDay(Now()-F('created_datetime')))) However, this is throwing the error: django.db.utils.ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist LINE 1: ...EMENT_TIMESTAMP() - "myapp_mymodel"."created_timestamp") AT TIME ZO... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. What am I doing wrong? It looks like both the value returned by Django's Now() and my timestamp field are timezone-aware timestamps, so why is the database complaining about incompatible types? My database backend is PostgreSQL. -
How can i manipulate pandas python, excel file, postgresql in web app?
I have to create a software or web application that will allow me to handle Pandas, make basic crud with pandas, crosstabs and sent the results then obtained in PostgreSQL. Do you have tracks? Or suggestions? thank you, I look and saw pandasgui pandastable but I do not know if they can meet my needs -
How to use array from python to javascript? Django
Before you say its duplicate !! I know how to parse by using dump() in views, but right now I want to receive an array of dictionaries from a custom template tag to JavaScript. This is in my custom_template.py @register.simple_tag(takes_context = True) def messageRequest(context): request = context['request'] messageData = Message.objects.all() jsMessageData = [] if 'user' in request.COOKIES: currentUser = request.COOKIES.get('user') i = 0 for i in range(messageData): if messageData[i].receiver == currentUser: jsMessageData.append(messageData[i]) if messageData[i].sender == currentUser: jsMessageData.append(messageData[i]) i += 1 print(jsMessageData) return dumps(jsMessageData) For my template index.html I want to use it in JavaScript to display the messages- I tried this messageData = Json.parse("{% messageRequest %}"); // i want to store it as array // throws error "'QuerySet' object cannot be interpreted as an integer" when looping through it also, messageData = Json.parse("{% messageRequest|escapejs %}"); // i read this somewhere and it works fine when array is passed through render request but here it gives error as it considers escapejs as part of block tag. Any help is appreciated, I am sort of beginner so please try to give comprehensive explanation an example will be really helpful. -
How to return form field errors to template rendered in a different django view
I have a django bootstrap 4 template (wordcloud.html) that contains a form. The form was originally created as raw html within wordcloud.html, and the view for that template populates the fields. The form (create_wordcloud_form) uses post to send the data to a different view (create_wordcloud_view.py). The original developer didn't use django's built in template/form/view structure, so there is no form.py nor a form template. The issue I need to address is validating the form. It has to be server-side validation, as one of the fields needs to be tested against one of the databases to prevent duplicate fields. Do I need to refactor the whole mess into the standard django template/form/view idiom using crispy-forms, or is there a way to use what I already have and return some error messages from the view that processes the form data? The code for validating the fields is easy. I am not sure how to structure the return statement in the event there are field errors, since wordcloud.html is rendered in a different view. create_wordcloud_view: @method_decorator(login_required, name='post') class CreateWordCloud(View): def post(self, request): logger.debug("CreateWordCloud START") q_dict = request.POST logger.debug("q_dict=%s" % q_dict) sources = [] filters = {} cloud_name = None for key in q_dict: … -
Run a Scrapy spider in a Huey Task (django project)
I want create periodic task in Django to run Scrapy process, but the task in log seems doesn't end, i believe that i need connect the crawler signal with Huey task, i'm lost with this, any idea? INFO 2021-05-20 19:34:36,500 consumer.start :: Huey consumer started with 1 thread, PID 4000 at 2021-05-20 19:34:36.500022 INFO 2021-05-20 19:34:36,500 consumer.start :: Scheduler runs every 1 second(s). INFO 2021-05-20 19:34:36,500 consumer.start :: Periodic tasks are enabled. INFO 2021-05-20 19:34:36,500 consumer.start :: The following commands are available: + app.tasks.run_spider [2021-05-20 19:34:48,260] INFO:huey:Worker-1:Executing app.tasks.run_spider: 1e843422-2ab6-48fa-bf8b-6b7fe25266f8 INFO 2021-05-20 19:40:07,864 consumer.run :: Received SIGINT INFO 2021-05-20 19:40:07,865 consumer.stop :: Shutting down gracefully... [2021-05-20 19:40:07,868] INFO:huey:Worker-1:app.tasks.run_spider: 1e843422-2ab6-48fa-bf8b-6b7fe25266f8 executed in 319.608s INFO 2021-05-20 19:40:07,869 consumer.stop :: All workers have stopped. INFO 2021-05-20 19:40:07,869 consumer.run :: Consumer exiting. from multiprocessing import Process from scrapy import signals from scrapy.crawler import Crawler from twisted.internet import reactor def run_script(): crawler = Crawler(MySpider, settings=settings.SCRAPY_SETTINGS) crawler.signals.connect(reactor.stop, signal=signals.spider_closed) reactor.run() @db_task() def run_spider(): process = Process(target=run_script) process.start() process.join() huey==2.3.2 django==3.2.3 -
Django order_by() is not working along with distinct()
How can i use order_by() in combination with distinct() ? I am having multiple same run_id with different end_time data = list(table_name.objects.filter(experience=experience)\ .values('run_id', 'end_time').distinct('run_id').order_by('-end_time')) Following is the error :- django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions Also, the following ORM works fine without order_by but I want the latest end_time data = list(table_name.objects.filter(experience=experience).values('run_id', 'end_time').distinct('run_id')) -
Flutter authentication with Django on the back
If I want to add login/logout and signup functionality in flutter with Django on the back authenticating my flutter app users, how would I go about doing it? -
Emacs. Is possible to use Flycheck and pylint django?
I use lsp-mode and flycheck My .pylintrc config: [MASTER] load-plugins=pylint_django What do I need to configure? -
how to create one-to-one related user roles with djoser
I have a Custom user model and 4 role models class User(models.Model): is_student = True is_teacher = True is_staff= True is_admin = True Class Student(models.Model): user = models.Foreignkey(User) Class Teacher(models.Model): user = models.Foreignkey(User) Class Admin(models.Model): user = models.Foreignkey(User) Class Staff(models.Model): user = models.Foreignkey(User) I'm using djoser for User authentication. Now what I want is when somebody POST to 'api/v1/{role name}/register' User is created automatically and so is the role model's object. Currently I know that only POST request to '/users' will create the user in djoser and I have to use post_save signal when is_{role} field in user model is true, to save any role model object. I'm trying to use a nested serializer but that is not compatible with djoser. -
Django Template Autor-reload
How can i disable Django 3.2 from reloading the server whenever i edit template files in development. This is actually making my productivity slow because it takes 1-4 secs to reload. -
How to force field mappings with a ManyToMany relationship on same model
I have a fairly simple model representing users: class Person(AbstractUser): students = models.ManyToManyField("web.Person", through="Supervision") ... with a many-to-many relationship to itself... class Supervision(models.Model): student = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="supervisor") supervisor = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="student") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: unique_together = [['student', 'supervisor']] def __str__(self): return "{supervisor} supervises {student} ({id})".format( supervisor=self.supervisor, student=self.student, id=self.pk ) The problem comes when I create a relation between 2 persons: >>> prof = Person.objects.get(last_name="prof") >>> student = Person.objects.get(last_name="student") >>> prof.students.add(student) >>> prof.save() >>> Supervision.objects.all() <QuerySet [<Supervision: student, student (1130) supervises prof, prof (97) (2)>]> It seems that Django swaps the relation by default. I tried to swap the related names in the class definition of the Supervision: class Supervision(models.Model): student = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="student") supervisor = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="supervisor") But it does not help. How can I get Django to put the fields in the correct order? -
get() keywords must be strings
I can't tell what is the problem, and where the problem is. I was able to upload files through django import export but now I am not able to do so. Here is my Traceback. Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\import_export_views.py", line 227, in post result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 741, in import_data return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 788, in import_data_inner raise row_result.errors[-1].error File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 635, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 330, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 323, in get_instance return instance_loader.get_instance(row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance return self.get_queryset().get(**params) TypeError: get() keywords must be strings This si the resource file class ImportBooksResource(resources.ModelResource): def __init__(self, school_id,*args,**kwargs): super(ImportBooksResource,self).__init__() self.school_id = school_id self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id')) self.fields['department'] = fields.Field(widget=ForeignKeyWidget(Departments, 'name')) … -
Django configuration LDAP using Django-auth-ldap
I am trying to configure LDAP authentication on my django project. Before get into django, I have tested following shell command can return successfully. ldapsearch -H ldap://172.16.34.4 -b "dc=corp,dc=rate,dc=com" -D corp\\peter -W sAMAccountName=peter result: ... # search result search: 2 result: 0 Success # numResponses: 3 # numEntries: 1 # numReferences: 1 But when comes to django settings.py, You know there are many items to set. And I tried many combinations but with no lucky. AUTH_LDAP_SERVER_URI = 'ldap://172.16.34.4' AUTH_LDAP_USER_SEARCH = LDAPSearch( "DC=corp,dc=rate,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "name": "cn", "email": "mail", "first_name": "displayName", "last_name": "sn" } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ) And I create a API to login: from rest_framework.views import APIView class LoginAuth(APIView): def post(self, request, *args, **kwargs): user_loggedin = 'guest' display_name = 'guest' username = self.request.data.get('username') password = self.request.data.get('password') usergo = authenticate(username=username, password=password) # usergo always returns None print('authuser', usergo) if usergo is not None: auth_login(self.request, usergo) user_loggedin = usergo.username display_name = usergo.first_name context = { 'username': user_loggedin, 'displayName': display_name, 'state': False } return Response(context, status=status.HTTP_200_OK) return Response( f'Failed to authenticate with {username} / {password}', status=status.HTTP_400_BAD_REQUEST ) When access the endpoint with post data, I got error as the following (usergo always returns None): …