Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django authentication password returning False
I'm trying to create an authentication system using Django with a custom backend and user class, but every time I try to authenticate with an existing user and password in my Postgresql database the check_password() function always returns False and I can't proceed. Here's the code for the UserBackend on backends.py from django.contrib.auth.backends import ModelBackend from .models import user class UserBackend(ModelBackend): def authenticate(self, **kwargs): username = kwargs['username'] password = kwargs['password'] print('user: ', username) print('pass: ', password) #try: user_ = user.objects.get(username=username) try: print(user_.check_password(password)) if user_.check_password(password) is True: #Here check_password() is always false return user_ except user.DoesNotExist: pass def get_user(self, user_id): try: return user.objects.get(pk=user_id) except user.DoesNotExist: return None views.py def signin(request): now = datetime.now() if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = UserBackend.authenticate(ModelBackend(),username=username, password=password) if user is not None: #auth.login(request, user) return redirect('/index') else: messages.info(request, 'invalid username or password') return redirect("/signin") else: return render(request,'signin.html') return render(request, 'signin.html') models.py class user(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.TextField() real_name = models.TextField() email = models.TextField() password = models.TextField() description = models.TextField() last_login = models.DateField() created_at = models.DateField() class Meta: managed = False db_table = 'user' def __str__(self) -> str: return self.username what am I doing wrong? -
How to search inside json file with redis?
Here I set a json object inside a key in a redis. Later I want to perform search on the json file stored in the redis. My search key will always be a json string like in the example below and i want to match this inside the stored json file. Currently here i am doing this by iterating and comparing but instead i want to do it with redis. How can I do it ? rd = redis.StrictRedis(host="localhost",port=6379, db=0) if not rd.get("mykey"): with open(os.path.join(BASE_DIR, "my_file.josn")) as fl: data = json.load(fl) rd.set("mykey", json.dumps(data)) else: key_values = json.loads(rd.get("mykey")) search_json_key = { "key":"value", "key2": { "key": "val" } } # here i am searching by iterating and comparing instead i want to do it with redis for i in key_values['all_data']: if json.dumps(i) == json.dumps(search_json_key): # return # mykey format looks like this: { "all_data": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } -
i have a basic register api,however, it seems to be throwing this error, HTTP_201_CREATED' not found
i am getting this error ,i tried to convert fields variable in serializers.py to my_fields but it cannot be changed,also i tried to convert values of fields variable in list but of no use**.it was working at first but i dont know what seems to be the problem Internal Server Error: /api/auth/signup Traceback (most recent call last): File "/home/technogetic/Documents/Django Rest Framework/VPAProject/firstapp/views.py", line 97, in post return Response[{'msg':'Registration Successfull, A Verification code has been send to your Email'}, status.HTTP_201_CREATED] AttributeError: 'tuple' object has no attribute 'HTTP_201_CREATED' views.py class UserRegistrationView(GenericAPIView): serializer_class = UserRegistrationSerializer renderer_classes = [UserRenderer] def post(self, request, format=None): confirm_password = request.data.get('password1') #Request the Email from the user) # confirm_password = request.data.get('password1') #Request the Email from the user email = request.data.get('email') #Request the Email from the user username = request.data.get('username') # Request the username from the user password = request.data.get('password') # Request the password from the user first_name = request.data.get('first_name') # Request the first name from the user last_name = request.data.get('last_name') # Request the last name from the user if not email or not username or not password or not first_name or not last_name: # check the parameters for the email,username,password,firstname,lastname. return Response({'msg': 'Invalid parameters'}) pass_bool = Validate_Password(password) # Validate the … -
How to configure Django application deployed with Gunicorn with a front NGINX server, through docker compose?
I am finding difficulty in understanding the mistake in the following setup which attempts to serve a django-gunicorn application server with nginx. (Am not yet concentrating on static assets) Docker compose file # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: gunicorn --bind unix:/run_socket/gunicorn.sock StockWhiz.wsgi:application # Below command for using gunicorn to serve. volumes: - type: bind source: ./stockwhiz-web target: /code - type: bind source: ./run_socket target: /run_socket depends_on: - db environment: - "DJANGO_SETTINGS_MODULE=StockWhiz.settings.local" db: image: postgres:14-bullseye # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" nginx: image: nginx:stable restart: always volumes: - ./run_socket:/run_socket - ./config/nginx/:/etc/nginx/conf.d/ ports: - "80:80" depends_on: - web # Volumes set up volumes: postgres_data: NGINX config # Note in our docker compose it's typically located at etc/nginx/conf.d/ # Which are automatically copied on to the nginx.conf file at etc/nginx upstream gunicorn_application { server unix:/run_socket/gunicorn.sock; } server{ listen 80; server_name www.stockwhiz.in; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass gunicorn_application; } } Logs Some of the logs … -
Which database is best for python? [closed]
I am confusing to choose the database. Mysql or mongodb or sqllite -
In django, how to annotate(group by) date from a datetime field with MYSQL
Defined as class Data(models.Model): created_at = models.DateTimeField(default=timezone.now) number = models.IntegerField(default=1) And the requirement is to get sum group by date from created_at and I was using. qs = Data.objects.values('created_at__date').annotate(sum=Sum('number')) The above query works fine with sqlite3, but it failed with MySql. In MySql, it returns single result <QuerySet [{'created_at__date': None, 'sum': 100}]> Excepted: <QuerySet [ {'created_at__date': datetime.date(2021, 7, 12), 'sum': 50}, {'created_at__date': datetime.date(2021, 7, 13), 'sum': 50} ]> -
How to access properties of one-to-Many relationships in Django templates?
I am very new to Python & Django. I am building a personal diary with pretty simple properties such as Months and Entries. models.py class Month(models.Model): id = models.AutoField(primary_key=True) month_name = models.CharField(verbose_name="Month", max_length=20, unique=True) year_number = models.IntegerField(verbose_name="Year") featured_img = models.ImageField(verbose_name="Featured", upload_to='diary/featured_img', default=False) class Meta: verbose_name = "Month" ordering = ['-year_number', 'month_name'] def __str__(self): return '%s, %s' % (self.month_name, self.year_number) class Entry(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) content = models.TextField() month = models.ForeignKey('Month', on_delete=models.RESTRICT, null=True) img = models.ImageField(verbose_name="Image", upload_to='diary/entry_img', default=False) date_created = models.DateTimeField(verbose_name="Date", default=timezone.now) def __str__(self): return self.title class Meta: verbose_name_plural = "Entries" ordering = ['-date_created'] I am trying to build a simple webpage which displays the Months in list form and when I click on the month I get the entries in detail view. I completed the first step but I cannot figure out how to access the one-to-many relationships between Month and Entry model in Django templates. What I want to do is to display a page with all the Month model objects and when a user clicks on a specific month say "December", Django returns all the entries which have the month object defined as December. This worked fine in the admin site where I inserted TabularInLine … -
Is it correct to use Celery in Kafka Consumer?
I am doing some long-running tasks in Kafka Consumer. I want to know that I am doing right or wrong? I am using Kafka Consumer to consumer messages from another server and messages are processing as I want. I am putting the received message in the Celery queue. And all is working well. Does Here need Celery? Or Kafka will handle it as a queuing system? _consumer = KafkaConsumer(KAFKA_TOPIC, bootstrap_servers=['{}:{}'.format(HOST, PORT)],auto_offset_reset="earliest", value_deserializer=lambda x: ReadHelper().json_deserializer(x), group_id="mygroupZ1") for msg in _consumer: payload = msg.value print("data fetched payload------------------") long_running_task.delay(payload) # Does here need Celery task to put in? -
Cannot send javascript post data to django view
I have a function in javascript in which I am trying to a very simple key value pair of data through a post request into the same view in which the webpage is rendered from. I have a form in the same template/webpage HTML that is able to send post data to the view just fine, however the javascript is unable to do so and I am left with null data in the view. Javascript: ` postAccount(); async function postAccount() { accountPromise = getAccount().then(accounts => { return accounts[0]; }) //This function call to retrieve the account will be put here until I can figure out a way to //pull the address with the user pressing login ONLY IF the the user has already connected theyre metamask. account = await accountPromise; var data = new FormData(); data.append("address", account.toString()); console.log("address=" + account.toString()); let post = new XMLHttpRequest(); post.open("POST", "{% url 'index' %}", true); post.setRequestHeader('Content-Type', 'application/json'); post.send(data); } Django view: @csrf_exempt def index(request): context = {} usernameInput = None; address = None; if (request.method == 'POST'): usernameInput = request.POST.get("username_input") address = request.POST.get("address") print(usernameInput, address) if (usernameInput != None and address != None): user = generalUser(address = str(address), username = usernameInput, lastLogin = timezone.now()) … -
User data not updating in admin panel and forms django
When I try to update user data (in admin panel or form) it does nothing and give 0 errors. In the admin panel, it says it updated, but data stays the same. Here's my model.py: https://pastecode.io/s/jx4jpt0x -
Multi file upload with other info in Django Rest Framework
I am going to create multi file upload api in django rest framework. Each file has file description field. So I need to upload bulk files and files description data at the same time. files = request.FILES.getlist('files[]') files_description = json.loads(request.data.get('files_description')) I can create File model instances by looping files_description. The issue is, file field is optional. So above files, files_description length can be different, since file field can be optional. How can I match file field and file description? -
How should I handle package dependency conflicts, especially in Django?
I've been trying to implement BERTopic inside my Django project. However, the dependencies of BERTopic conflicts with my existing numpy version: When I run !pipdeptree -p bertopic in jupyter notebook, I get this output: * tensorflow-gpu==2.3.0 - numpy [required: >=1.16.0,<1.19.0, installed: 1.21.6] I was trying to use BERTopic in views.py More than wanting to solve this specific issue with numpy, I would like to know how to solve any conflicts between package dependencies. -
I don´t get to see my mistake. Why do I get this error? raise RequestsJSONDecodeError
......................... ....................... ...................... When I execute, python py_client/details.py, I get: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) What´s going wrong here? detail.py import requests endpoint = "http://localhost:8000/api/products/1" get_response = requests.get(endpoint) print(get_response.text) this is urls.product from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.ProductDetailAPIview.as_view()), path('', views.ProductCreateAPIview.as_view()), ] I am getting error Expecting value: line 1 column 1 (char 0) It doesn´t work in the browser either. It says: Page not found (404) this is urls.cfehome from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include("new_api.urls")), path('/api/products/', include("products.urls")) ] this is my view in the app products from rest_framework import generics from .models import Product from .serializers import Productserializers class ProductDetailAPIview(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = Productserializers class ProductCreateAPIview(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = Productserializers -
Blending the rendering of DataTableView and a standard view in Django
I'm pretty new to django and have been experimenting with some of the code I want to build a form that starts with a parent record, lists the children of that record, and then when I click on a child (or a button in the row of that child) shows the children under that in a datatableview object. phew It should look a little like this: So the dataset is the primary object into the view, and the tables are a datatables filtered by the dataset id, which all works fine... but how do I get the {{ datatable }} to render in context? The current view code is pretty basic - this is initially all just for display. def datasetview(request, datasetid): dataset = get_object_or_404(DataSet, pk=datasetid) context = { 'dataset': dataset, } return render(request, 'data/dataset_view.html', context) within the html template, I render the table list with: {% for datatable in dataset.datatables.all %} {% if not datatable.deleted %} <tr> <td class="p-1 align-middle">{{ datatable.tablename }}</td> <td class="p-1 align-middle"><button type="button" class="btn btn-outline-primary" onclick="fill_attribute_table({{ datatable.datatableid }})">Edit</button></td> </tr> {% endif %} {% endfor %} I've been able to render the dataviewtable as a generic page using the demo code provided at pypi.org/project/django-datatable-view (that's how I … -
404 error while implementing async function
detail.html {% if request.user.is_authenticated %} <form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}"> {% csrf_token %} <h4> {% if request.user in review.like_users.all %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button> {% else %} <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button> {% endif %} </h4> </form> {% endif %} <!-js--> <script> const likeForms = document.querySelectorAll('.like-forms') const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value likeForms.forEach((form) => { form.addEventListener('submit', function (event) { event.preventDefault() const reviewId = event.target.dataset.reviewId const bookId = event.target.dataset.bookId axios({ method: 'post', url: `/detail/${bookId}/like/${reviewId}/`, headers: {'X-CSRFToken': csrfToken}, }) .then(response => { const isLiked = response.data.isLiked const likeBtn = document.querySelector(`#btn-like-${reviewId}`) console.log(isLiked) if (isLiked === true) { likeBtn.classList.add('bi-emoji-heart-eyes') likeBtn.classList.remove('bi-emoji-angry') } else { likeBtn.classList.add('bi-emoji-angry') likeBtn.classList.remove('bi-emoji-heart-eyes') } }) .catch(error => { console.log(error) }) }) }) </script> urls.py path("detail/<int:book_pk>", views.detail, name="detail"), path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"), ..... views.py def detail(request, book_pk): reviews = Review.objects.order_by("-pk") book = Book.objects.get(pk=book_pk) context = { "reviews": reviews, "book": book, } return render(request, "review/detail.html", context) def like(request, book_pk, review_pk): review = Review.objects.get(pk=review_pk) book = Book.objects.get(pk=book_pk) if review.like_users.filter(pk=request.user.pk).exists(): review.like_users.remove(request.user) is_liked = False else: review.like_users.add(request.user) is_liked = True data = { "isLiked": is_liked, } return JsonResponse(data) I got a 404 not found error while writing code for a "like" async function. data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} … -
django annotate based on another annotate create a duplicate query
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation: groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate( no_members=Count('student', distinct=True), point=Sum('student__point__point', filter=point_filter), avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField())) but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is: SELECT `study_league_studygroup`.`id`, `study_league_studygroup`.`name`, `study_league_studygroup`.`parent_id`, COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`, SUM(`study_league_point`.`point`) AS `point`, ( SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`) ) AS `avg_point`, `layers_layer`.`id`, `layers_layer`.`name`, `layers_layer`.`type_id`, `layers_layer`.`parent_id`, `layers_layer`.`created`, `layers_layer`.`default`, `layers_layer`.`lft`, `layers_layer`.`rght`, `layers_layer`.`tree_id`, `layers_layer`.`level` FROM `study_league_studygroup` LEFT OUTER JOIN `users_student` ON ( `study_league_studygroup`.`id` = `users_student`.`study_group_id` ) LEFT OUTER JOIN `study_league_point` ON ( `users_student`.`user_id` = `study_league_point`.`student_id` ) INNER JOIN `layers_layer` ON ( `study_league_studygroup`.`parent_id` = `layers_layer`.`id` ) GROUP BY `study_league_studygroup`.`id` but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point -
What are Pharaoh, Grandmother, and Monarchy deletion patterns?
I was looking at the docs for Django CTE Trees and saw the text: Multiple delete semantics: supports Pharaoh, Grandmother, and Monarchy deletion patterns. This meant nothing to me, so I did a bit of googling - and found nothing! Does anyone know what "Pharaoh, Grandmother, and Monarchy deletion patterns" are? -
CKEditor in production not showing in admin panel
I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin. settings.py STATIC_URL = '/static/' MEDIA_URL = '/static/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/') STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static') CKEDITOR_UPLOAD_PATH = "uploads/" urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) models class Topic(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() def __str__(self): return self.title class BlogPost(models.Model): blog_title = models.CharField(max_length=255) blog_article = RichTextField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") def __str__(self): return self.blog_title admin from django.contrib import admin from . models import PostImage, EnterImage, BlogPost, Topic # Register your models here. admin.site.register(PostImage) admin.site.register(BlogPost) admin.site.register(EnterImage) admin.site.register(Topic) -
django DenseRank annotation based on another annotate
I want to annotate rank queryset based on avg of points. annotate(avg=Avg('point'), rank=Window(expression=DenseRank(), order_by=Value("avg").desc()) but rank is 1 for all data. When I check query straight in database result is true! but in django all rank is 1. When I use F("avg") instead of Value("avg"), result is true but query is not optimal . With F() in query once calculate average of points for avg and calculate avg again for rank avg: query 1: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY AVG(point) DESC ) rank, but I want below query: query 2: SELECT AVG(point) AS avg, DENSE_RANK() OVER ( ORDER BY avg DESC ) rank, when I user Value('avg') query 2 generate but all rank is 1 and when I use F('avg'), result is true but query 1 generate which is not optimal and calculate 'avg' twice(twice AVG(point) in query). -
Showing data in modal
Using Django 3 i developed a page where some tasks are showed like links. If task is not finished, than the user own can edit it, but if task is finished the user can only see. The tasks color are diferents from each task depends in the status: Atrasada, em dia, futura. The purpose is click in a task and open a modal with data from that task, but i dont know how to transfer data from main page to modal. I have no idea what to do. There is a way to make this using just django??? -
Django Rest Framework no read multiple records
I have tried everything on the blogs. I even consume the service with postman and multiple records are not inserted. Can you help me understand what is happening? There are no errors thrown by the code. Only one record is inserted. My code in DJANGO class ProviderListSerializer(serializers.ListSerializer): def do_stuff(data): return data def create(self, validated_data): some_data = self.do_stuff() return Provider.objects.bulk_create(some_data, ignore_conflicts=True) class ProviderSerializer(serializers.ModelSerializer): class Meta: model = Provider fields = '__all__' list_serializer_class = ProviderListSerializer class ProviderViewSet(viewsets.ModelViewSet): queryset = Provider.objects.all() serializer_class = ProviderSerializer def create(self, request, *args, **kwargs): many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data, many=many) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers) My code in POSTMAN: curl --location --request POST 'http://127.0.0.1:8000/api-auth/providers/' \ --header 'Authorization: Basic YRtaW46SklFTTkzMDYMQ==' \ --form 'name="Proveedor09"' \ --form 'representante="Proveedor09"' \ --form 'alias="Proveedor09"' \ --form 'ruc="isuioasuio92"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor09@mail.com"' \ --form 'activo="true"' \ --form 'name="Proveedor091"' \ --form 'representante="Proveedor091"' \ --form 'alias="Proveedor091"' \ --form 'ruc="isuioasuio921"' \ --form 'mobile="48489948"' \ --form 'address="shds"' \ --form 'telefono="45546546654"' \ --form 'email="Proveedor109@mail.com"' \ --form 'activo="true"' I just expect to insert multiple records. As I said, I've tried everything I've seen on the web. Maybe I'm sending the form-data wrong, but I see that in many … -
Sync to Async Django ORM queryset foreign key property
Very simple question: Django. Model. Has foreign key: class Invite(models.Model): inviter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='inviter') ... In async context, I do: # get invite with sync_to_async decorator, then print(invite.inviter) Get async favorite error: You cannot call this from an async context - use a thread or sync_to_async How do I handle this? -
Django retrieving data from m2m table
I am using Django default User model. I've made a relation m2m to it with model Books. Django made automaticly table in library app - library_books_user. How can I get acces to it? I want to be able to delete relations. Normally when I use not built in models i can do it like: models.BooksUsers.objects.get(book=book, user=user) importing models before. -
Not working Create Mutation in Graphql [django]
I use Django and graphql. Not working Create Mutation in Graphql. I can't understand why. Update and Delete works. But I can't create anything. class MovieCreateMutation(graphene.Mutation): class Arguments: title = graphene.String(required=True) year = graphene.Int(required=True) movie = graphene.Field(MovieType) def mutate(self, info, title, year): movie = Movie.objects.create(title=title, year=year) return MovieCreateMutation(movie=movie) and I have: class Query(api.schema.Query, graphene.ObjectType): pass class Mutation(api.schema.Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) I'll say it again - Update and Delete mutations work. Only Create does not work. And I can't understand why. What I'm doing: mutation { createMovie(title: "TestMovie", year: 1981) { movie { title year } } } What do I always get: { "data": { "createMovie": { "movie": null } } } -
how to customize UserCreationForm in django
Hi I am trying to clean up my usercreation form using widgets but its not working. The class is not being passed 'form-control' It does however work for model form. Not sure what I am doing wrong? I am new. forms.py class ProfileForm(UserCreationForm): class Meta: model=User fields = ('email', 'avatar', 'password1', 'password2') def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class CustomerForm(ModelForm): class Meta: model = Customer fields = ['name','email','phone_number' ] widgets={ 'name' :forms.TextInput(attrs={'class':'form-control'}), 'email' :forms.TextInput(attrs={'class':'form-control'}), 'phone_number' :forms.TextInput(attrs={'class':'form-control'}), }