Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Task not getting assigned through redis
Using Celery/redis i tried creating a task, But on checking the celery working info with the below code celery -A intranet_project worker -l info I am unable to get the task added there. Settings.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intranet_project.settings') app = Celery('intranet_project') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) my_task.py from celery.decorators import task from celery import shared_task @shared_task def add(a,b): d = a + b return d Below is the server log [tasks] . intranet_project.celery.debug_task [2020-02-26 19:38:59,051: INFO/MainProcess] Connected to redis://localhost:6379// [2020-02-26 19:38:59,160: INFO/MainProcess] mingle: searching for neighbors [2020-02-26 19:39:00,379: INFO/MainProcess] mingle: all alone -
Requested setting INSTALLED_APPS, but settings are not configured
I am working on a project for a while and now from nowhere I am getting this error: where the following seems to be the important part django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.co The error is coming when I am trying to use main.py The content (that is important for comprehension) of main.py is: I know about: export DJANGO_SETTINGS_MODULE=mysite.settings But this is not the solution for me. This problem only came when I add: from device.serializers.gcloud_device import GcloudDeviceSerializer If I do export the django_settings_module with the path to my settings.py then my error become: ImportError: cannot import name I do not have circular import. I already created a lot of apps in my project and this is the first time I see this error Thank you -
Utilizing django blob field to upload file to a blob column in Oracle
I want to upload files (images,pdf,ms word,etc) in the Oracle database (blob) using Django binary field. I need to store file name and file extension (e.g. png,jpeg,etc) and file size. However i can't figure out how to store in the blob field the binary data of the file. P.S. I know it's not best practise to store static files in the database but i have to do this. My Model: class File(models.Model): du_id = models.AutoField(primary_key=True) du_file = models.BinaryField() du_file_name = models.CharField(max_length=1000) du_file_extension = models.CharField(max_length=100) du_file_size = models.CharField(max_length=100) forms.py: from django import forms class UploadFileForm(forms.Form): file = forms.FileField(label='Upload document') html form: <form method="post" action="{% url 'images:upload' %}" enctype="multipart/form-data">{% csrf_token %} {{form}} <input type="submit" value="Upload file"> </form> view: from django.shortcuts import render from images.models import File from images.forms import UploadFileForm from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.urls import reverse from django.utils.timezone import datetime import datetime,base64 def file_upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_name = str(form.cleaned_data['file']) file_name_split = file_name.split('.') extension = file_name_split[-1].upper() test_string = "test string" res = bytes(test_string, 'utf-8') a = File.objects.create(du_file = res,du_file_name=file_name,du_file_extension=extension, du_file_size='1023') a.save() return HttpResponse(file_name) #return HttpResponseRedirect(reverse('images:home')) else: return HttpResponse('Form is not valid!') else: return HttpResponse('Failed') -
How to optimize deep nested foreignKeys in Django queryset
TLDR; Is there a better way to handle deep nesting in this Django queryset? File.objects.filter(folder__project__workspace__organization__in=user.organizations.all()) Detailed question: Here is an example scenario: An organization consists of multiple users and a user can be part of multiple organizations. class User(models.Model): pass class Organization(models.Model): members = models.ManyToManyField( User, through='OrganizationMembership', related_name='organizations' ) class OrganizationMembership(models.Model): member = models.ForeignKey(User) organization = models.ForeignKey(Organization) The nested relationship among models are defined as follows: class Workspace(models.Model): organization = models.ForeignKey(Organization, related_name='workspaces') class Project(models.Model): workspace = models.ForeignKey(Workspace, related_name='projects') class Folder(models.Model): project = models.ForeignKey(Project, related_name='folders') class File(models.Model): folder = models.ForeignKey(Folder, related_name='files') I wanted to filter all the files the requesting user has access to across organizations. Here is my queryset, is there a way to optimize this queryset? user = self.request.user organizations = user.organizations.all() File.objects.filter(folder__project__workspace__organization__in=organizations) -
Django Form Can't Filter Foreign Key on Dropdown
I have a "CustomUser" class that I got from an all-auth tutorial (Django All-Auth Tutorial) and I have user as a foreign key in each model, which works as intended, only showing records pertaining to the current logged in user to that specific user. For example: class Education(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) EducationInstitutionName = models.CharField(verbose_name=_('Institution Name'), max_length=100, default=None) EducationLevel = models.CharField(verbose_name=_('Education Level'), choices=EDUCATIONLEVEL, max_length=100, default=None) EducationStartDate = models.DateField(verbose_name=_('Education Start Date'), default=None) EducationEndDate = models.DateField(verbose_name=_('Education End Date'), default=None) EducationCaoCode = models.CharField(choices=CAO_CODE, max_length=100, default=None) EducationDesc = models.CharField(verbose_name=_('Education Description'), max_length=250, default=None) def __str__(self): return self.EducationInstitutionName This works perfectly and I am achieving what is needed. The issue arises when I have a table comprised of Foreign Keys which is the focal point of my application which takes the constituent parts of a CV and allows you to combine them to make a CV of interchangable sections. class Cv(models.Model): user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, ) CvName = models.CharField(verbose_name=_('CvName'), max_length=100, default=None) CvEducation = models.ForeignKey(Education, on_delete=models.CASCADE) CvSkills = models.ForeignKey(Skills, on_delete=models.CASCADE) CvWorkExperience = models.ForeignKey(WorkExperience, on_delete=models.CASCADE) def __str__(self): return self.CvName This gives me... enter image description here Dropdown showing all users "Education" I've tried to filter this with init parameters but this breaks the "save" function. I'm really … -
Making a Django proxy for websocket (jupyter lab)
I'm having a problem with an application I'm trying to mount, I need to have a JupyterLab and notebook iframed in the django app, but I needed to proxy it through the Django app so I can use the Django authorization and authentication to access the notebooks, I used django-revproxy to proxy all the http routes to the Jupyter endpoint, and it works pretty easy, but I can't make the kernel of the Jupyter notebook to work, b/c it works through web sockets, I tried to use Django Channels and ProtocolTypeRouter/URLRouter to proxy the websockets routes, but I'm getting this error, "failed: Error during WebSocket handshake: 'Upgrade' header is missing", now I'm not sure if my approach of proxy the JupyterLab endpoints is the best, I got to a wall and I feel trap and don't know how to solve this problem, what do you recommend to handle this? thank you. -
Django:Commenting with Ajax doesn't work properly
I am trying to comment on a post with ajax. it successfully saves to the database. There is no problem with the comment process. but after reviewing it takes me to the action url of the form. It's url path('upload/<int:id>/<str:model_type>/<str:options>',views.django_image_and_file_upload_ajax,name="upload") It's views.py def django_image_and_file_upload_ajax(request,id,model_type,options): if request.method == 'POST': form = CommentForm(request.POST or None, request.FILES or None) obj = get_object_or_404(Thing, id=id) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user if model_type == "comment": comment.is_parent = True else: comment.is_parent = False comment.content_type = ContentType.objects.get_for_model(obj.__class__) comment.object_id = obj.id comment.save() comment_html = render_to_string("includes/comment/comment-list-partial.html", context={ "thing": obj }) return JsonResponse({'error': False, 'message': 'Uploaded Successfully',"thing_comment_html": comment_html}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: form = CommentForm() return render(request, 'pie_thing/deneme.html', {'form': form}) It's ajax code $(document).ready(function () { var $window=$(this); var $thing_comment_list=$window.find("#thing-comment-list") $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var $url =$form.attr("action") var formData = new FormData(this); $.ajax({ url: $url, type: 'POST', data: formData, success: function (response) { console.log(response) $thing_comment_list.html(response.thing_comment_html) }, cache: false, contentType: false, processData: false }); }); It's comment form in html <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate="" action="{% url "pie_thing:upload" thing.id "thing" options %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" /> This is the page I see after commenting page image -
Get user from multiple auth backend
Django 2.2, python 3.6 I'm using 2 authentication backends in my application : GRAPHENE = { 'SCHEMA': 'my_main_app.all_schemas.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] I can get user info from graphql queries method like : @login_required def resolve_curr_user(self, info, parent_id): user = info.context.user But I cannot get user from a view : def curr_user(request): request.user # user is None I'm passing the correct headers to the view request : const headers = new Headers(); headers.append('Authorization', `JWT ${auth_token}`); const init = { method: 'GET', headers: headers, mode: 'cors', cache: 'default' }; const response = await fetch(`/curr_user_route`, init); When authenticating for graphql query, django calls authenticate method from JSONWebTokenBackend class. How do I tell django to call the same method for regular views ? -
Jinja 2 Recursive loop to make html tree
I have a JSON dictionary which can have n depth. I am making an HTML collapsing tree out of it. Its almost done but gives a slight error. Here is the dictionary and the code. { "aaa": { "bbb": { "ccc": { "ddd1": {}, "ddd2": {}, "ddd3": {} } } } } {% for k,v in data.items() recursive %} <ol> <li> <label for="{{k}}">{{k}}</label> <input type="checkbox" checked id={{k}} /> {% if v %} {{ loop(v.items()) }} {% endif %} </li> </ol> {% endfor %} It Displays ddd2 and ddd3 under bbb, but it should display it under ccc -
django-private-chat syntax error with updated websockets
I am trying to integrate django-private-chat into my web application but I keep getting the following syntax error when I run python3 manage.py run_chat_server. asyncio_ensure_future = asyncio.async # Python < 3.5 ^ SyntaxError: invalid syntax I am using Python 3.7 and I understand that this is usually due to websockets not being updated but I have already upgraded it to version 8.1. I ran pip3 install --upgrade websockets and it now looks like this in my requirements.txt file. websockets==8.1 Could someone please advise me on how I can fix this? Thank you. -
Why is it the html showing the ID not the text? using Django
I've just finish to create my table in my views.py, if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = EmployeeUser.objects.get(Username=request.POST['p_user'], Password=request.POST['p_pass'], My_Position=request.POST['position']) #print(request.POST['position']) if m.My_Position.id != request.POST['position']: request.session['member_id'] = m.id aa = request.POST['p_user'] ss = EmployeeUser.objects.all().filter(Username=aa) teacher = SubjectSectionTeacher.objects.filter(Employee_Users__id=m.id) student_subject = Subject.objects.filter(id__in=teacher.values_list('Subjects')).distinct().order_by('id') student_section = Section.objects.filter(id__in=teacher.values_list('Sections')).distinct().order_by('id') student_gradelevel = EducationLevel.objects.filter( id__in=teacher.values_list('Education_Levels')).distinct().order_by('id') cate = gradingCategories.objects.all() studentenrolledsubject = StudentsEnrolledSubject.objects.filter( Subject_Section_Teacher__in=teacher.values_list('id')).distinct().order_by('id') period = gradingPeriod.objects.filter( Grading_Periods_Setting__Education_Levels__in=student_gradelevel.values_list('id')).distinct().order_by( 'id') students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter(Grading_Categories__in=cate.values_list('id')).filter(GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records', 'Grading_Categories', 'Grade').distinct() Categories = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = cate.values_list('id')).order_by('Grading_Categories') table = [] student_name = None table_row = None columns = len(Categories) + 1 # # # table header table_header = ['Student Names'] table_header.extend(Categories) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = student['Grade'] table.append(table_row) This is the models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) @property def dates(self): # you have Year-month-day dates … -
upload photos from the database to the carousel using ajax
How can I upload photos from the database to the carousel using ajax? And then you have to update the page when changing in the database. views.py def index(request): time_change = Time.objects.get(id=1).time_for_change_slied * 1000 image_list = Image.objects.filter(bool_field=True).order_by('number_of_slaid') return render(request, 'prezents/index.html', {'image_list': image_list, 'time_change':time_change}) index.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide carousel-fade" data-ride="carousel" data-interval="{{time_change}}" data-pause="false"> <div class="carousel-inner"> {% for a in image_list %} {% if forloop.first %} <div class="carousel-item active "> {% if a.image_prezents %} <img class="d-block " src="{{a.image_prezents.url}}" alt="first"> {% endif %} </div> {% else %} <div class="carousel-item"> {% if a.image_prezents %} <img class="d-block " src="{{a.image_prezents.url}}" alt="second"> {% endif %} </div> {% endif %} {% endfor %} </div> {% endblock %} -
Overwrite field in queryset annotate
I have a django model with the fields name (string) and value (integer). Say I need to return a queryset of {name:..., value:...} objects, with each value doubled. What I am trying to do now is: queryset.annotate(value=F('value') * 2) However, django tells me that the field value already exists. I also tried using extra: queryset.annotate(value_double=F('value') * 2).extra(select={'value': 'value_double'}) but that also does not work since value_double is not a valid field. Of course, in this case I could use something like queryset.extra(select={'value': 'value * 2'}), but I have some other, more complicated cases involving a lot of functions where I really don't want to write sql, but I'd rather find a solution in django. Again, in all of my cases, annotate works perfectly fine as long as I give the result a new name. -
Django/Python, append json with for loops
I collect data from some django models in a very specific order and output them in json to use in React. quiz = LessonQuiz.objects.filter(lesson=details).order_by('position') quizdata = [] if quiz.count() > 0: for a in quiz: qz = LessonQuiz.objects.get(id=a.id) item = {'id': qz.id, 'title': qz.title} if qz.linkbutton_set.count() > 0: buttons = qz.linkbutton_set.all() for b in buttons: item[b.id] = { "id": b.id, "type": b.qtype, "text": b.text, "link": b.link, "color": b.color } quizdata.append(item) at the moment it returns all the data I want as follows, [ { "id": 3, "title": "Do you agree?", "1": { "id": 1, "type": "btn", "text": "I agree", "link": "/lesson/welcome/completed", "color": "#e2574c" }, "2": { "id": 2, "type": "btn", "text": "I'm not sure I agree", "link": "/contact", "color": "#e2574c" }, "3": { "id": 3, "type": "btn", "text": "I have a suggestion", "link": "/contact", "color": "#e2574c" } } ] However, ideally, I would like to have array 1, 2 & 3 in it's own array eg data. [ { 'id': 3, 'title': 'Do you agree?', 'data': [ 1: { 'id': 1, 'type': 'btn', 'text': 'I agree', 'link': '/lesson/welcome/completed', 'color': '#e2574c' }, 2: { 'id': 2, 'type': 'btn', 'text': "I'm not sure I agree", 'link': '/contact', 'color': '#e2574c' }, 3: { … -
getting all the instances of a model into an oblect
I have a model called sickness, which I have used to create multiple instances like malaria, typhoid and others. model class Sickness(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name please, how can I get this into a dictionary form like this where the name will be gotten into the dictionary. duration_choices = { 'malaria':'malaria', 'typhod':'typhod', 'cough':'cough', 'headache':'headache', 'stomach gas':'stomach gas', } -
How to use the context variables passed from Django in javascript? Already changed to Json type
I want to make a table in HTML by using javascript. Now I'm done with the header and displayed correctly. Now I would like to add the content in the table by adding from the database. However, once I declare the context variable from the view.py I created, the table will disappear. How can I call the data correctly from the view.py I made into javascript? I knew it should be JSON style. How can I fix it? thanks in advance. views.py @csrf_exempt def test(request): return render(request, 'test.html') def testJS_page(request): context_list = {} customers = Customer.objects.all() carts = Cart.objects.all().select_related('customer').order_by('customer_id') goods = Good.objects.select_related('cart__customer').order_by('cart_id') context_list['Cart'] = carts context_list['Good'] = goods context_list['Customer'] = customers context = {"Customer_status": json.dumps(context_list)} return render(request, 'test.html', context) test.js var customer_status = ({{ Customer_status|safe }}); function createTable() { var myTableDiv = document.getElementById("myDynamicTable"); var table = document.createElement('TABLE'); var thread = document.createElement('THREAD'); thread.className = "thead-dark"; table.appendChild(thread); var tr1 = document.createElement('TR'); thread.appendChild(tr1); var th1 = document.createElement('TH'); var th2 = document.createElement('TH'); var th3 = document.createElement('TH'); var th4 = document.createElement('TH'); th1.appendChild(document.createTextNode("Product")); th2.appendChild(document.createTextNode("Count")); th3.appendChild(document.createTextNode("Price")); th4.appendChild(document.createTextNode("Subtotal")); tr1.appendChild(th1); tr1.appendChild(th2); tr1.appendChild(th3); tr1.appendChild(th4); myTableDiv.appendChild(table); } createTable(); once I write the code "var customer_status = ({{ Customer_status|safe }});", It seems going wrong. -
Model constants not available in data migrations?
I want to change the data format in my model and replace a char field with an int choice. The old field is called objective and the new field is called objective_new Here is the model definition (excerpt): from django.db import models from django.utils.translation import gettext_lazy as _ class Timer(models.Model): # (...) OBJECTIVE_HOSTILE = 1 OBJECTIVE_FRIENDLY = 2 OBJECTIVE_NEUTRAL = 3 OBJECTIVE_UNDEFINED = 4 OBJECTIVE_CHOICES = [ (OBJECTIVE_HOSTILE, _('Hostile')), (OBJECTIVE_FRIENDLY, _('Friendly')), (OBJECTIVE_NEUTRAL, _('Neutral')), (OBJECTIVE_UNDEFINED, _('Undefined')), ] objective_new = models.SmallIntegerField( choices=OBJECTIVE_CHOICES, default=OBJECTIVE_UNDEFINED, verbose_name='objective', ) objective = models.CharField( max_length=254, default="", blank=True, help_text='This field is no longer in use', ) # (...) To convert the existing data to the new format I want to use a data migration that maps the text from the old field to the new choice field. And here is my problem: It seams that the model class that I get in the data migration does not contain any constants, e.g. OBJECTIVE_CHOICES which I need to make the mapping. Here is my data migration code (excerpt): def migrate_forward(apps, schema_editor): Timer = apps.get_model('timerboard', 'Timer') objective_map = {x[1]: x[0] for x in Timer.OBJECTIVE_CHOICES} # (...) I am getting the following error: AttributeError: type object 'Timer' has no attribute 'OBJECTIVE_CHOICES' Of course … -
How to set repeat interval time in background-tasks using django?
I tried to run the background task code in Django. its working fine but interval time is not working. it working every second how to fix it anyone gives some solution. views.py from django.shortcuts import render from django.http import HttpResponse from background_task import background from django.core.mail import send_mail @background(schedule=5) def hello(): print('hello_world') # Create your views here. def index(request): hello() return HttpResponse('<h1> Hello World </h1>') I tried to pass repeat parameter also from django.shortcuts import render from django.http import HttpResponse from background_task import background from django.core.mail import send_mail @background(schedule=5) def hello(): print('hello_world') # Create your views here. def index(request): hello(repeat=10) return HttpResponse('<h1> Hello World </h1>') I tried many ways. But still is not working.I need every One hour to print hello world. -
How to access other field value from ModelSerializer?
I need to return some computed value using request param. To get computed result, I need login user(which could successfully restive) and access to Post model field(favorited_users). How can I get access to self.favorited_users from ModelSerializer class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() spot = SpotSerializer() is_login_user_favorite = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' read_only_fields = ('owner',) def get_is_login_user_favorite(self, validated_data): login_user = self.context['request'].user # I need to do something like below. # return self.favorited_users.contains(login_user) class PostListAPIView(generics.ListAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.all().order_by('-pk') permission_classes = [IsAuthenticated] -
Setting pre-hook for docker-compose file
I am running a dockerized django app and I am looking for a way to run (a) directive(s) every time before I build a docker container. More concretely, I would like to run docker-compose -f production.yml run --rm django python manage.py check --deploy each time before I either build or up the production.yml file. Like a pre-hook. I know I could achieve this with a bash-script, yet I was wondering if there is a way of doing this inside the docker-compose file. I can't find anything in the docker documentation (except events, but I don't understand if they serve for what I want to achieve) about it and I assume that this is not possible. Yet, maybe it is in fact possible or maybe there is a hacky workaround? Thanks in advance for any tips. -
Django DRY Models
In general, how can I keep my models DRY when I have to repeat several attributes multiple times? For example: class Event(models.Model): title = models.CharField(max_length=255) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) street = models.CharField(max_length=50) street_nr = models.CharField(max_length=5) class Person(models.Model): name = models.CharField(max_length=50) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) street = models.CharField(max_length=50) street_nr = models.CharField(max_length=5) -
File "/app/.heroku/python/lib/python3.6/tkinter/__init__.py", import _tkinter # If this fails your Python may not be configured for Tk
Im working on heroku and i trying to deploy my django application on heroku but i got this error ECONNREFUSED: connect ECONNREFUSED 50.19.103.36:5000. This is caused by network issue soI disconnected my lan and connected in my mobile wifi and i gave migrate then the migrate command ran and showing tkinter error, and i think is any problem in python version because in my normal command prompt my python version is 3.7, if i check version in anaconda prompt it showing the python version 3.6. In that error also it showing in screenshot. -
How to make your own custom hasher Django?
I need to make my own custom MD5 hasher in Django in order username + password. I create hashers.py import hashlib from django.contrib.auth.hashers import MD5PasswordHasher from jd.models import AdvUser, Users, create_user from django.contrib.auth.models import UserManager class JDMD5PasswordHasher(MD5PasswordHasher): def encode(self, password, salt=None): assert password is not None hash = hashlib.md5(password.encode()).hexdigest() return hash I get username from forms.py def save(self, commit=True): user = super().save(commit=False) username = self.cleaned_data.get('username') user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, instance=user) return user But I cant find solution how to hash username too. Something like: logpass = str(username) + str(password) hash = hashlib.md5(logpass.encode()).hexdigest() -
How to use an optional parameter in django URL
I want solution for how Django URL work without any optional parameter or with optional parameter see my url structure that I want path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>-vs-<slug:brand_slug3>/',views.compare_brand) now, I want something like 1st two slugs for comparison is compulsory so, as per the above URL path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>',views.compare_brand) this is working fine because this are compulsory url parameter but i want to pass optional url from 2nd 'vs' to brand_slug3. can anyone help me in this? -
Make Django REST to call create method of first class from retrieve method of another class
Below code calls the retrieve method and works fine class SomeWorkflow(ViewSet): serializer_class = SomeWorkflowSerializer def retrieve(self, request, pk): response = OtherWorkflowSerializer.as_view({'get': 'retrieve'})(request._request, 'some_id').data Now I want to call the OtherWorkflowSerializer class's create method. The create method also takes some parameters like {'id': 1, 'file_path': '/foo/bar/file.txt'}