Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass "LIVE" data with django sessions?
I have a long task to process in django admin's response_change . It takes a few good minutes so I would like to make a progress indicator. I store the progress into sessions but when I read the session from a different view (which is called on a timer from JS every 300ms) the session does not contain the updated progress (which I set in the long task). It always has what the session had when the long task ended last time. Official docs say "You can read it and write to request.session at any point in your view. You can edit it multiple times.". So why isn't it working ? -
Select2 with Django not accepting selections
I've been working on this problem for a couple days now and I am just stumped. Trying to integrate Select2.js without using the django-select2 app. My model: class CEID(models.Model): process = models.CharField(max_length=4, choices=PROCESS_LEVELS) ceid = models.CharField(max_length=6) representative = models.ManyToManyField(get_user_model(), blank=True) functional_area = models.CharField(max_length=200) score = models.IntegerField(null=True, blank=True) ceid_is_production = models.BooleanField(default=True) ceid_is_front_end = models.BooleanField(default=True) ceid_is_hidden = models.BooleanField(default=False) ceid_pdl = models.ManyToManyField('PDL', blank=True) user_edited = models.BooleanField(default=False) def __str__(self): return str(self.process) + ' ' + str(self.ceid) if self.ceid else '' def __unicode__(self): return str(self.process) + ' ' + str(self.ceid) if self.ceid else '' class Meta: ordering = ('process', 'ceid', 'process',) def calculate_ceid_score(self): entities = Entity.objects.filter( ceid__id=self.id).filter(production=True) score = 0 for entity in entities: score += entity.score if entity.score else 0 self.score = score / len(entities) if len(entities) > 0 else 0 self.save() return My view: class PagesAdminSetCeidUserAssociation(LoginRequiredMixin, View, UserPassesTestMixin): template_name = 'pages/pages_admin_set_ceid_user_association.html' login_url = '/login/' def test_func(self): return self.request.user.is_superuser def get(self, request): form = PagesAdminSetCeidUserAssociationForm() if request.is_ajax(): if request.GET.get('dat_type') == 'representatives': representatives = get_user_model().objects.filter( username__icontains=request.GET.get('term') ) representative_response_content = list( representatives.values()) return JsonResponse(representative_response_content, safe=False) elif request.GET.get('dat_type') == 'ceids': ceids = CEID.objects.filter( ceid__icontains=request.GET.get('term') ) ceid_response_content = list(ceids.values()) return JsonResponse(ceid_response_content, safe=False) return render(request, self.template_name, {'form': form}) def post(self, request): form = PagesAdminSetCeidUserAssociationForm(request.POST or None) if form.is_valid(): print(form) … -
Add onetoone field to all users, django
In the middle of the project, I was faced with the fact that I needed to expand my user model. Since it is very problematic to create a custom model at the moment, I decided to use the onetoone field and everything is successful, but there is a question. I would like to add a relationship to my user model proxy for existing users and set permissions for them. How can I do that? I need to set start value for all users class UserPermission(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) start = models.BooleanField(default=True) professional = models.BooleanField() team = models.BooleanField() last_update = models.DateTimeField() -
DRF permissions best practise DRY
Whats the best way to do view permissions in DRF based on user type currently? In my structure there are several user_types and for example TEAM_LEADER cant create a team object but can see the list of teams. Which means for the same class view i want to use different permissions for POST and GET for example. I'm looking to do this as dry as possible and i'm trying to follow the skinny view fat models design principle(also wondering if that's good practice to follow in 2021). models.py for the user model class User(AbstractBaseUser): ...fields here objects = UserManager() USERNAME_FIELD = "email" def __str__(self): return self.email def has_perm(self, perm, obj=None): if perm.Meta.verbose_name=="worksite" and perm.request.method =="POST": if self.user_type <= self.DEPARTMENT_MANAGER: return True else: return False return True views.py class DashboardPermissions(BasePermission): message="You dont have permission for this action" def has_permission(self, request, view): return request.user.has_perm(view.Meta.verbose_name) class ViewName(CreateAPIView): permission_classes = (IsAuthenticated,DashboardPermissions) authentication_classes = () serializer_class = WorksiteSerializer queryset = Worksite.objects.all() class Meta: verbose_name="view_name" def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Bonus question would my solution create any performance issues? -
Django Case When with backward relationship
I want to annotate "status". And I need: status="Not Processed" if at least one of backward related forlistproduct has status == ListProduct.Status.NOT_PROCESSED; status="Deficit" if at least one of backward related forlistproduct has status == ListProduct.Status.Deficit and no one of them has a status == ListProduct.Status.NOT_PROCESSED; status="Completed" if at least one of backward related forlistproduct has status == ListProduct.Status.Completed and no one of them has a status == ListProduct.Status.DEFICIT and no one of them has a status == ListProduct.Status.NOT_PROCESSED. I have tried this code def annotate_status(self): return self.annotate(status=Case( When( forlistproduct_set__status=ListProduct.Status.NOT_PROCESSED, then=Value("Not Processed") ), When( Q(forlistproduct_set__status=ListProduct.Status.DEFICIT) & ~Q(forlistproduct_set__status=ListProduct.Status.NOT_PROCESSED), then=Value("Deficit") ), When( Q(forlistproduct_set__status=ListProduct.Status.COMPLETED) & ~Q(forlistproduct_set__status=ListProduct.Status.DEFICIT) & ~Q(forlistproduct_set__status=ListProduct.Status.NOT_PROCESSED), then=Value("Completed") ), output_field=CharField() )) but it raised an exception below. Traceback (most recent call last): File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/SlopehelperERP/backend/production_api/views.py", line 74, in retrieve return … -
Cannot access field in Django Graphene
The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. -
Please help me is fixing this problem in python-django forms
from django import forms from .models import Tweet MAX_TWEET_LENGTH=240 class TweetForm(forms.ModelForm): class meta: model = Tweet field = ['content'] def clean_content(self): content = self.cleaned_data.get('content') if len(content)>MAX_TWEET_LENGTH: raise forms.ValidationError("This tweet is to long") return content This is my code for form ... but when I call the TweetForm in views.py it says Exception Type: ValueError Exception Value : ModelForm has no model class specified I tried in django shell also : here is the error message ~\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py in __init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance, use_required_attribute, renderer) 285 opts = self._meta 286 if opts.model is None: > 287 raise ValueError('ModelForm has no model class specified.') 288 if instance is None: 289 # if we didn't get an instance, instantiate a new one ValueError: ModelForm has no model class specified. here is my views.py def tweet_creat_view(request,*args,**kwargs): form = TweetForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.save() form = TweetForm() return render(request,"components/forms.html",context={"form":form}) -
ValueError: ModelForm has no model class specified. ValueError at /profile/ ModelForm has no model class specified
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm,ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f'Yor account has been created! You are now able to login') return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html',{'form': form}) @login_required def profile(request): u_form = UserUpdateForm() p_form = ProfileUpdateForm() context = { 'u_form' : u_form, 'p_form' : p_form } return render(request,'users/profile.html', context) -
AWS not acknowledging my Procfile during deploy
I am trying to run some commands in a Procfile (located in my root, also tried placing it in any relevant directory that could be the root to no avail). Ideally, I would like to see this log: 2021-01-27 19:04:05 INFO Instance deployment successfully used commands in the 'Procfile' to start your application Environment: Elastic Beanstalk Python 3.6 running on 64bit Amazon Linux/2.10.0 -
Sort based on multiple models and properties
I have two models as bellow: class Source: user = ForeignKey(User) title = models.CharField(max_length=300) class Post: source = ForeignKey(Source) like = ManyToMany(User) title = models.CharField(max_length=300) Each post has a source, and a user can choose multiple or all sources that created by the admin. users can like posts. Firstly, I wanna limit posts to just the sources chosen by the logged in user, and then sort them based on the number of likes that each post has, How? Thanks in advance -
How to order in django on two columns when one of the column is null
I would like to order the dataset based upon the two columns let's say created_date and updated_date. If updated_date is null it should order be using created_date otherwise using updated_date column. -
Django atomic transaction works on sqlite but doesn't work on postgresql
I'm currently using a sqlite db for testing and everything works fine but I realize when I switch to postgresql db the atomic transaction doesnt work properly. if bool(airplane): if airplane[0].is_ready==True: service=ServiceModel.AirplaneService.objects.get(airplane=pk,is_next=True) serializer=ServiceSerializer.AirplaneServiceList(service) with transaction.atomic(): next_service.do_service(airplane[0]) data={ 'service':service.id, 'airplane':airplane[0].id, 'company':request.auth.payload.get('company'), 'tt':airplane[0].tt, 'ct':airplane[0].ct, 'dt':airplane[0].dt, } log=ServiceSerializer.AirplaneServiceLog(data=data) log.is_valid() log.save() return Response(serializer.data,status=200) else: return Response("The airplane is not ready to fly",status=500) -
Show field in template but dont allow it to be edited (Django)
Say I have a model class MyModel(model.Models): name = model.CharField() age = model.IntField() Then in my template I want to display the name but only allow age to be changed i.e the user should not be able to modify what is written in the name field but it should just be there to show, which name they are editing the age for. My template is as the following {% extends "myapp/base.html" %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="content-section"> <div class="form-group"> {{form.name|as_crispy_field}} <!-- Can still edit this field --> <form method="POST"> {% csrf_token %} {{form.age|as_crispy_field}} <button class="btn btn-outline-success" type="submit">Update</button> <a role="button" class="btn btn-outline-info" href="{% url 'my_list' %}"> Wups, take me back!</a> </div> </form> </div> {% endblock content %} -
How to response image? in Django
I'm new to Django. This is my Chatbot made by Django. I'd like to answer two things at once, text and photo. But I can't. I tried to input this module import base64 with open(image_path, "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode('utf-8') ctx["image"] = image_data return render(request, 'index.html', ctx) But I failed to change 'return Jsonresponse(''')' properly. views.py @csrf_exempt def chatanswer(request): context = {} questext = request.GET['questext'] import pickle import colorama colorama.init() from colorama import Fore, Style, Back file = open(f"./static/intents.json", encoding="UTF-8") data = json.loads(file.read()) def chat3(inp): # load trained model model = keras.models.load_model('static/chat_model') # load tokenizer object with open('static/tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) # load label encoder object with open('static/label_encoder.pickle', 'rb') as enc: lbl_encoder = pickle.load(enc) # parameters max_len = 20 # while True: print(Fore.LIGHTBLUE_EX + "User: " + Style.RESET_ALL, end="") # inp = 'What is name' result = model.predict(keras.preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences([inp]), truncating='post', maxlen=max_len)) tag = lbl_encoder.inverse_transform([np.argmax(result)]) for i in data['intents']: if i['tag'] == tag: txt1 = np.random.choice(i['responses']) print(Fore.GREEN + "ChatBot:" + Style.RESET_ALL, txt1) return txt1 anstext = chat3(questext) print(anstext) context['anstext'] = anstext context['flag'] = '0' return JsonResponse(context, content_type="application/json") I don't know what should I do.. Thanks a lot -
Login form writes that the ' ' already exists
So, i have a problem. I have a login form, but when i try to login it writes that ' ' is already exists. How is it possible?If user has an account it means that it'll exists. But why i get this mistake? views.py def login(request): if request.method == 'POST': form = LoginForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): cd = form.cleaned_data user = authenticate(email=cd['email'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: return HttpResponse('Form is not valid') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) I get a mistake: <ul class="errorlist"><li>email<ul class="errorlist"><li>User with this already exists.</li></ul></li></ul> Login form class LoginForm(ModelForm): class Meta: model = User fields = ['email', 'password'] widgets = { 'email': EmailInput(attrs={ 'class': 'form-email', 'placeholder': 'email' }), 'password': PasswordInput(attrs={ 'class': 'form-password', 'placeholder': 'password' }) } User model class User(models.Model): CHOICES = ( ('1', 'Author'), ('2', 'Customer'), ('3', 'Author and Customer') ) first_name = models.CharField(max_length=64, blank=False, verbose_name='') last_name = models.CharField(max_length=64, blank=False, verbose_name='') patronymic = models.CharField(max_length=64, blank=False, verbose_name='') age = models.PositiveSmallIntegerField(verbose_name='', blank=False) email = models.EmailField(unique=True, max_length=128, blank=False, verbose_name='') password = models.CharField(max_length=32, blank=False, verbose_name='') role = models.CharField(max_length=32, choices=CHOICES, default='Customer') about = models.TextField(max_length=512, verbose_name='', blank=True) -
Use model in models.py -> fix 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I have the following models.py code: class SlackAccountMatching(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True) slack_user_id = models.CharField(default=None, null=True, max_length=50) class SlackNotifications(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) slack_notification_name = models.CharField(default=None, null=True, max_length=255) slack_notification_time = models.TimeField(default=datetime.time(16, 00)) Below in the same file I want to use both SlackNotifications and SlackAccountMatching to make queries in the respective model. I was looking into the [ready()][1] and therefore am doing: from django.apps import AppConfig class SlackApplicationConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'slack_application' def ready(self): from .models import SlackAccountMatching, SlackNotifications However, the error is still showing up: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Any ideas on how to fix this? Thank you. [1]: https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig.ready -
Django + AJAX abort executing funtion
I am using ajax to run a django function. In this function, I connect to the database and run a sql statement, the result of which is saved to a csv file. This sql takes a long time to run at times, and I would like to be able to interrupt this function on demand. Is it possible? Can I get the id of the running process or request and use it to kill it? -
How to efficiently Rank model obj in django
I have a model called 'Student' and it has a field 'score' that stores the total marks attained by a student. I would love to know a fucntion that will enable me to rank students based on their respective scores -
Django Rest Framework Hiding the JSON data
I have just started learning Django Rest Framework. Most of the tutorials I follow use drf with react. Now I want to hide the api so that no one can see any data whenever they enter that url. I just need the url to post data (for ex- from a membership form...name email and stuff). How can I achieve this. Most of the questions here only talk about hiding browsable api. Please do tell if I am thinking in the wrong direction. The idea behind this is that I don't want the information I ask from a user to be visible to everyone through that url. I tried achieving this in the following way. Is this a fine way of doing this or is this going to mess up the application, because I don't see any errors and the post requests are working. I am using React for the frontend. This is my first time posting a question. Please tell if you need any other information. Thanks a lot in advance. I have only done this in the first if block {if request.method == 'GET':}, I returned a string instead of serializer.data and now whenever i go to membershipform/ it … -
Form Not Clearinng after submit
I created a booking form using Django's modelformset_factory and when I fill up the form and click on submit, it successfully stores data in database but there arise a problem the form doesnt clears instead it creats new form. But when I clears data from database the forms clears automatically. Can somebody tell me the problems. Here is my models.py code: class Booking(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) nationality = models.CharField(max_length=100) passport = models.CharField(max_length=100) email = models.CharField(max_length=100) phnumber = models.CharField(max_length=100) checkin = models.DateTimeField(max_length=20) checkout = models.DateTimeField(max_length=20) roomtype = models.CharField(max_length=100) def __str__(self): return self.name class Meta: db_table = "room_book" Here is the code of views.py def form(request): BookForm = modelformset_factory(Booking, fields=( 'name', 'address', 'nationality', 'passport', 'email', 'phnumber', 'checkin', 'checkout', 'roomtype'),extra=2) if request.method == 'POST': form = BookForm(request.POST or None, request.FILES or None) form.save() form = BookForm() return render(request, 'form.html', {'form': form}) Here is my code of form.html: <form id="mainForm" method="post"> {% csrf_token %} {{ formset.management_form }} {{form.as_p}} <input type="submit"> -
Django DRF serializer return duplicate objects while query_set is unique
I have a model LessonsData and I am trying to serialize LessonsData.objects.filter(creator=request.user) The result of query set is <QuerySet [<LessonData: LessonData object (22)>]> This means only one object is returned in query_set. Then I pass this to my model serializer that returns the duplicate result containing three same objects [OrderedDict([('creator', OrderedDict([('user', OrderedDict([('created_at', 'Saturday, 01 May 2021'), ('first_name', 'Hashir'), ('last_name', 'Hassan'), ('email', 'mhashirhassan@gmail.com'), ('phone_no', '+923228080110'), ('user_type', 'CR'), ('is_active', True), ('last_login_ip', None)])), ('profession', 'Fitness Trainer2'), ('profile_image', None), ('year_of_experience', None), ('subdomain', 'eddygrero'), ('bio', 'Testing the web'), ('intro_video', None), ('avg_rating', 3.0)])), ('name', 'lorem'), ('description', 'pesum'), ('no_of_participants', 2), ('language', ['English']), ('lesson_type', 'GROUP'), ('session_type', 'SINGLE'), ('meeting_type', 'HOST_LESSON'), ('meeting_link', 'https://us05web.zoom.us/j/81870334516?pwd=VWxYSFdEMXpLVmFNUTJTS0J2QS9OZz09'), ('lesson_uuid', '2145fa1e-b5a7-4d76-8c0e-a1a4555642c2'), ('cover_image', None), ('learnings', ['abc']), ('requirements', ['abc']), ('status', 'ACTIVE'), ('price', {'type': 'pricePerSession', 'value': '10', 'currency': 'USD'}), ('upcoming_slot', {'creator': OrderedDict([('user', OrderedDict([('created_at', 'Saturday, 01 May 2021'), ('first_name', 'Hashir'), ('last_name', 'Hassan'), ('email', 'mhashirhassan@gmail.com'), ('phone_no', '+923228080110'), ('user_type', 'CR'), ('is_active', True), ('last_login_ip', None)])), ('profession', 'Fitness Trainer2'), ('profile_image', None), ('year_of_experience', None), ('subdomain', 'eddygrero'), ('bio', 'Testing the web'), ('intro_video', None), ('avg_rating', 3.0)]), 'lesson': OrderedDict([('id', 22), ('name', 'lorem'), ('description', 'pesum'), ('no_of_participants', 2), ('language', ['English']), ('lesson_type', 'GROUP'), ('session_type', 'SINGLE'), ('meeting_type', 'HOST_LESSON'), ('price', {'type': 'pricePerSession', 'value': '10', 'currency': 'USD'}), ('timezone', 'America/Juneau'), ('meeting_info', {'id': 81870334516, 'type': 3, 'uuid': '+7wO45guSrmgEa4ynQDpMw==', 'topic': 'lorem', 'status': 'waiting', 'host_id': 'PTU0xTJjTOOAi_iFUZZa-g', 'join_url': 'https://us05web.zoom.us/j/81870334516?pwd=VWxYSFdEMXpLVmFNUTJTS0J2QS9OZz09', … -
I want to load a static file from django template like.. {% static {{post.image}} %}
I want to load a static file from django template like.. {% static {{post.image}} %} but is error Can you show me code like this? Did you understand? Need more clarification? -
No CSRF input field in html form of dajngo rest framework in put method
PUT, DELETE method is generating this error when submitted from the api webpage { "detail": "CSRF Failed: CSRF token missing or incorrect." } But POST method is working fine in the same API modal created using viewsets.ModelViewSet So I inspect the form and found that the post method has CSRF input field but PUT html form doesn't have the CSRF so the error is showing how can I fix this issue. Package used: Django==2.2.5 djangorestframework==3.7.7 django-rest-auth==0.9.5 django-filter==2.2.0 settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_FILTER_BACKENDS': [ 'django_filters.rest_framework.DjangoFilterBackend', ], } Why DRF template adds the CSRF field in POST HTML form but doesn't add that field in PUT HTML form. I am ready to provide any additional info if required is there anything I had missed in the setup. -
python variable having , between like this: (order_item, created = ...)
order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) now here I can't understand how it will work I tried searching the web but had no luck :( -
Can not query foreign key related objects using _set | Django?
can not access foreignkey related objects , showing error i have crated instance of Hospital and Availablity , But while querying using H1.availablity_set.all() //error 'Hospital' object has no attribute 'availablity_set' models.py class Hospital(models.Model): name = models.CharField(max_length = 256) address = models.CharField(max_length=256,null=True, blank=True) phone = models.CharField(max_length=10) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name = 'City') def __str__(self): return self.name class Availablity(models.Model): hospital = models.ForeignKey(Hospital, on_delete = models.CASCADE, related_name='availablities') facility = models.ForeignKey(Facility, on_delete= models.CASCADE, related_name='facilities') updated_at = models.DateTimeField(auto_now=True) total = models.IntegerField(default=0) available = models.IntegerField(default=0) code