Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django forms to render a large query of radio buttons in a more user friendly way
I am trying to find a way to effectively display time slots that users can select at time of application. Sometimes there will be quite a large number of slots. The issue is that I am currently using radio buttons, and a ModelChoiceField. I've attached an image below of what I have currently. I have a few ideas, and I am not sure if I need to dig into React or another front end framework to get this done. What I want is to display the radio buttons in a way thats not just an enormous list immediately, but rather a shorter list paired down into groups. I've thought about using CSS to hide some of the times. Perhaps having a checkbox for every hour that can display and hide the radio buttons within that hour (most slots are 5 minutes), but I get stuck trying to filter and render the form that way using a ModelChoiceField. I also am open to just using check boxes to have the user select a few generic ranges and use that to programmatically select a slot if thats what it is... I am not sure thats the best user experience though, so I … -
In Heroku, how to running gunicorn & import whitenoise?
2020-10-01T03:28:40.496699+00:00 heroku[web.1]: Starting process with command `gunicorn Nstory.wsgi --log-file -` 2020-10-01T03:28:43.803839+00:00 heroku[web.1]: State changed from starting to up 2020-10-01T03:28:43.367859+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-10-01T03:28:43.368669+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Listening at: http://0.0.0.0:35650 (4) 2020-10-01T03:28:43.368936+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Using worker: sync 2020-10-01T03:28:43.374298+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [9] [INFO] Booting worker with pid: 9 2020-10-01T03:28:43.382660+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [10] [INFO] Booting worker with pid: 10 2020-10-01T03:28:44.338145+00:00 app[web.1]: [2020-10-01 12:28:44 +0900] [9] [ERROR] Exception in worker process 2020-10-01T03:28:44.338188+00:00 app[web.1]: Traceback (most recent call last): 2020-10-01T03:28:44.338190+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-01T03:28:44.338191+00:00 app[web.1]: worker.init_process() 2020-10-01T03:28:44.338191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-01T03:28:44.338192+00:00 app[web.1]: self.load_wsgi() 2020-10-01T03:28:44.338192+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-01T03:28:44.338192+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-01T03:28:44.338193+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-01T03:28:44.338193+00:00 app[web.1]: self.callable = self.load() 2020-10-01T03:28:44.338194+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-01T03:28:44.338194+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-01T03:28:44.338195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-01T03:28:44.338195+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-01T03:28:44.338195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-01T03:28:44.338196+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-01T03:28:44.338196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2020-10-01T03:28:44.338197+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-01T03:28:44.338198+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2020-10-01T03:28:44.338198+00:00 … -
How to add pagination in search.html - django
how to create pagination in search.html ? i want show 4 posts per page what must I do now ? any help please and thanks this is my views.py : class SearchView(ListView): template_name = 'website_primary_html_pages/search.html' paginate_by = 20 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: android_results = Android.objects.search(query) linux_results = Linux.objects.search(query) tech_results = Tech.objects.search(query) mobile_results = Mobile.objects.search(query) windows_results = Windows.objects.search(query) # combine querysets queryset_chain = chain( android_results, linux_results, tech_results, mobile_results, windows_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Android.objects.none() # just an empty queryset as default and here is my search.html : {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Mobile' %} <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href='Mobile/{{ object.slug }}'><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ object.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href='Mobile/{{ object.slug }}'> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ object.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ … -
How can install Django on Ubuntu 20.04 LTS
I am beginners as ubuntu user. SO I need help to install Django. Already I used below command to install python, sudo apt-get install python3 Then the python version is Python 3.8.2 -
1046, 'No database selected' - unable to create programmatically the models (created with models.Model definition)
I am using multiple dbs and changing databases based on specific users/vendor permissions in Django. I am able to create dbs dynamically. But I am unable to create programmatically the models (created with models.Model definition) in the specific dynamically/programmatically created database in mysql. I am trying to use the create_model function in the schema editor but it fails. Here is the model i am trying to create and the code used to create the db and model. The model creation fails mentioning that database has not been selected. def create_model(self, new_database, model, create_database, conn): from django.db import connection, connections from django.db.utils import OperationalError from testmodel.models import Testmodel if connections[create_database.get("id")]: db_conn = connections[create_database.get("id")] try: # below cursor works c = db_conn.cursor() # create_model function is fetched print(db_conn.schema_editor().create_model) # below fails # db_conn.schema_editor().create_model(Testmodel) # below fails with db_conn.schema_editor() as schema_editor: schema_editor.create_model(Testmodel) return True return True except OperationalError as e: # (1046, 'No database selected') error print(e) connected = False return connected else: connected = True return connected return False when running this function, it gives an error saying the database has not been selected. (1046, 'No database selected') To avoid permissions issue for mysql user related errors, I tried with root user … -
Django queryset syntax using WHERE IN clause question
I could use assistance with a queryset call. Here are the models: class User(AbstractUser): pass class Post(models.Model): posterID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post") content = models.TextField(blank=False) timestamp =models.DateTimeField(auto_now_add=True) class Follow(models.Model): followerID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower") followingID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower_id") I am trying to select all Post with a posterID that are matching the followingID in Follow and are being followed (followerID) by the current user. I believe my SQL should be as such: SELECT * FROM Post WHERE Post.posterID IN ( SELECT followingID FROM Follow WHERE followerID = request.user.id ) I am guessing that I could start with something like: (assuming that currently request.user id == 1) f = Follow.objects.filter(followerID=1) p = Post.objects.filter(posterID__in= [-- something with f--] ) Any help would be appreciated. Thanks. -
Django: save() prohibited to prevent data loss due to unsaved related object
Why i get this exception even when I saved instance before assigning it as foreign key to another instance? "save() prohibited to prevent data loss due to unsaved related object " header_slip.save() form.cleaned_data['session_row'] = row_pk form.cleaned_data['brk_slip_id'] = header_slip form.save() my code here. Pls help me, thank -
How can i JSON URL use in function at flask?
My code here. I dealing with covid site and i want to retrieve data from a url but i am failing on this. I can't get the data. How can i this json url adaptive function. from flask import Flask, render_template, request import json import requests app = Flask(__name__) headers = {'content-type': 'application/json'} url = 'https://opendata.ecdc.europa.eu/covid19/casedistribution/json' filename = requests.post(url, data=json.dumps(dict(mynum=123)), headers=headers) print('response', response.text) @app.route('/', methods=['GET']) def index(): return(render_template('home.html')) @app.route("/" , methods=['POST']) def result(): country1 = request.form['country'] casesCountry1 = getCases(country1) dateLabels = getDates() return(render_template('home.html', country1=country1, casesCountry1=casesCountry1, dateLabels=dateLabels )) def getCases(country): with open(filename) as json_file: jsonData = json.load(json_file) caseList = [] for record in jsonData['records']: if record['countriesAndTerritories'] == country: caseList.append(int(record['cases'])) return(list(reversed(caseList))) if __name__ == '__main__': app.run(debug=False) -
Django processing form data without having to create form with Django
So I've coded an HTML page with all the inputs ready to go. I was going to use this on my python HTTP server but instead I am going to use Django because people have been telling me its much better for server handling. I played around with the forms.py on django but the problem is there you have to create the forms in forms.py and then it constructs the HTML for you. I already have the HTML ready so is there a way for me to just process the form data without having to rewrite my whole form again in forms.py? Thanks -
no result appear when i use search django
i want make search from my models ( multiple models ) but it don't work what's the prblem ? i am using slug so my pages like Android/some-url | Mobile/some-url etc. and the result is : just show results for : without data from models so how to fix it please any help here is my code : views.py : class SearchView(View): template_name = 'website_primary_html_pages/search.html' paginate_by = 2 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: android_results = Android.objects.search(query) linux_results = Linux.objects.search(query) tech_results = Tech.objects.search(query) mobile_results = Mobile.objects.search(query) windows_results = Windows.objects.search(query) # combine querysets queryset_chain = chain( android_results, linux_results, tech_results, mobile_results, windows_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Post.objects.none() # just an empty queryset as default search.html : <h2 id="search_page_design">{{ count }} results for <b>{{ query }}</b>: </h2> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Android' %} <div class='row'> <div class='col-12'> Blog post: <a href='{{ object.get_absolute_url }}'>{{ object.name }}</a> … -
Django app deployment in AWS Beanstalk - Error after deployment - Internal Server Error
I have a django app deployed to AWS beanstalk. The first version was fine after following the official documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html Then, I added a new feature using django-filter to my site. Now, when I deploy, I get this error on the main front end page: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Below is the error log I have. [Thu Oct 01 04:47:09.118704 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate [Thu Oct 01 04:47:09.118707 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] raise RuntimeError("populate() isn't reentrant") [Thu Oct 01 04:47:09.118722 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] RuntimeError: populate() isn't reentrant [Thu Oct 01 04:47:13.477606 2020] [:error] [pid 21279] [remote 172.31.3.100:48] mod_wsgi (pid=21279): Target WSGI script '/opt/python/current/app/djangoproject/wsgi.py' cannot be loaded as Python module. [Thu Oct 01 04:47:13.477658 2020] [:error] [pid 21279] [remote 172.31.3.100:48] mod_wsgi (pid=21279): Exception occurred processing WSGI script '/opt/python/current/app/djangoproject/wsgi.py'. [Thu Oct 01 04:47:13.477768 2020] [:error] [pid 21279] … -
Django rest framework creating Orders and order items
I want to create a Order and order items. For this i am simply creating new model object in views.py using CreateApiView but i am receiving error that "Serializer_class" should be included but i don't need serializer for this. //views.py class CreateOrder(CreateAPIView): def Post(self,request): header_token = request.META.get('HTTP_AUTHORIZATION', None) print(header_token) access_token = header_token.split(' ')[1] status,user = validate_token(access_token) cart=Cart.objects.get(user=user) print(cart) if cart: total=cart.total userprofile=UserProfile.objects.get(user=user) order,created=Order.objects.get_or_create(billing_profile=userprofile,total=total) cart_items=CartItem.objects.get(cart=cart) print(cart_items) for item in cart_items: itemid=item.item_id qty=item.quantity item_instance = Items.objects.get(item_id=item) order_item,created = OrderItems.objects.get_or_create(order=order, product=item_instance,quantity=qty) order.save() order_item.save() if created: item.delete() return Response (status=rt_status.HTTP_200_OK) I want to understand how to achieve this with or without serializer -
Django "This field is required." while trying to update CustomUser
In my models.py, I have this: class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) username = None email = models.EmailField(unique=True) .... class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my forms.py, I have this: class CustomUserForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) widget = { 'password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = CustomUser fields = ['first_name', 'last_name', 'email', 'password', ] class StudentForm(CustomUserForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta(CustomUserForm.Meta): model = Student fields = CustomUserForm.Meta.fields + \ ['course', 'gender', 'address', 'profile_pic', 'session_start_year', 'session_end_year'] widgets = { 'session_start_year': DateInput(attrs={'type': 'date'}), 'session_end_year': DateInput(attrs={'type': 'date'}), } From which I was able to add new student by passing context = {'form': StudentForm()} to my template. But now, I am having issue in trying to update students. I was able to get the student object which I pass as instance to StudentForm() but only ['course', 'gender', 'address', 'profile_pic','session_start_year', 'session_end_year'] fields value were set. … -
Rendering CSS with HTML with Django
So I have the file main.html which is being returned unstyled even though I have style.css in /polls/static/polls/style.css Here is main.html (cut down for simplicity) {% load static %}<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'polls/style.css' %}"> </head> my settings.py has this for the static URL: STATIC_URL = '/static/' Yet it still returns it unstyled while the console gets returned 404 1671 The fix is probably easy I'm just a newbie at Django Thanks -
CSRF token missing or incorrect on POSTMAN
This is my views.py from django.shortcuts import render from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' from django.views.generic import ListView, CreateView from django.urls import reverse_lazy from .forms import PostForm from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' class CreatePostView(CreateView): # new model = Post form_class = PostForm template_name = 'post.html' success_url = reverse_lazy('home') How do I pass a request to the templates render method. I am getting a csrf token error on Postman while using POST method -
How can I subclass Django TextChoices to add additional attributes?
I want to use Django 3.0 TextChoices for a models.CharField choices option and also as an Enum in other places in my code. This is a simplified version of my code from django.db import models class ValueTypeOriginal(models.TextChoices): # I know Django will add the label for me, I am just being explicit BOOLEAN = 'boolean', 'Boolean' class Template(models.Model): value_type = models.CharField(choices=ValueType.choices) I am wanting to add an additional attribute to the enum members, something so that this call >>> ValueType.BOOLEAN.native_type bool works. bool here isn't a string, but the built-in python function This blog post described doing something like that with Enum by overriding __new__. class Direction(Enum): left = 37, (-1, 0) up = 38, (0, -1) right = 39, (1, 0) down = 40, (0, 1) def __new__(cls, keycode, vector): obj = object.__new__(cls) obj._value_ = keycode obj.vector = vector return obj Based on that I tried: class ValueTypeModified(models.TextChoices): BOOLEAN = ('boolean', bool), 'Boolean' def __new__(cls, value): obj = str.__new__(cls, value) obj._value_, obj.native = value return obj That almost works. I get access to the unique TextChoices attributes like .choices, but string comparison doesn't work like it should. >>> ValueTypeOriginal.BOOLEAN == 'boolean' True >>> ValueTypeModified.BOOLEAN == 'boolean' False I think … -
Django ignoring localisation settings when displaying a DateTime on a form
I have the Django settings in "settings.py": LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True With a model in "models.py": class Foo(models.Model): date_time = models.DateTimeField(null=True, blank=True) And a form in "forms.py": class FooForm(forms.ModelForm): class Meta: model = Foo fields = ['date_time'] And in the template: <form method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Submit</button> <button type="button" onclick="javascript:window.location='/dashboard';">Cancel </button> </form> But the date is shown on the screen in the form as "2020-12-20 10:11:12" for example. Why doesn't Django use my localisation settings and display the date as "day, month, year"? I tried adding to the form: date_time = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) ...but it didn't have any effect. To quote the manual: "The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead." -
Submitting form after payment made via Paypal
helloo, I have recently integrated a PayPal payment option to my e-commerce project and everything is working fine except that after a payment is made the items remain in the cart and the payment is not notified to the backend. My question is how to set a submit the form for the address and all the details made in the check out the template along with the paid amount to reflect in the backend. Here is the checkout views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } ---------------------shipping and billing address ------------------- def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): ---------------------shipping and billing address ------------------- if is_valid_form([billing_address1, billing_province, billing_country, billing_postal_code, billing_phone_number]): billing_address = Address( user=self.request.user, street_address=billing_address1, apartment_address=billing_address2, province=billing_province, country=billing_country, postal_code=billing_postal_code, phone_number=billing_phone_number, address_type='B' ) billing_address.save() order.billing_address = billing_address order.save() set_default_billing = form.cleaned_data.get( 'set_default_billing') if set_default_billing: billing_address.default = True billing_address.save() else: messages.info( self.request, "Please fill in the required billing address fields") return redirect('core:checkout') payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option … -
using ajax with django login form
and i'm using ajax in my django login form in a bootstrap modal but i want to display if there are errors without the page being refreshed or the modal being closed , after checking some questions here is my try NB: i'm new to django and especially ajax in my views.py if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') in my forms.py class SigninForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'signin_email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control','id':'signin_password'}), } def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] in the template <form action="" method="POST" id="form_signin"> {% csrf_token %} {{signin_form.email}} {{signin_form.password}} <button type="submit" name="signin_form">Sign in</button> <hr> {% for message in messages %} {{ message }} {% endfor %} </form> -
Logout in Django auth + service worker
I have an issue with my service worker. When I try to logout my user in offline mode I face 2 issues: If I don't try to cache /logout and just redirect to the login page, the sessionid cookie is not delete and so when I leave the offline mode the user is still connected If I try to cache /logout/ I have an error because /logout/ is not a page but only a view in django Can someone help me to find a solution so I can disconnect safely my user ? :) Big thx :D -
DRY way to rename ModelSerializer fields without duplicating model/field definitions?
Working with a legacy database with an awful schema and want to rename several ModelSerializer fields without having to redefine fields already defined on the model. Here's an example model: class LegacyItem(models.Model): # Note: ignore things that feel "wrong" here (just an example) legacyitem_id = models.IntegerField(primary_key=True) legacyitem_notes = models.CharField(max_length=4000, blank=True, null=True) directory_id = models.ForeignKey('Directory', models.DO_NOTHING) created_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING) created_date = models.DateField(auto_now_add=True) modified_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING) modified_date = models.DateField(auto_now=True) Here's a working serializer: class LegacyItemSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = LegacyItem read_only_fields = [ 'created_date', 'modified_date', ] The goal is to bulk rename model fields for the API so we can abstract away the awful schema. Here's a working serializer showing the sort of renaming we want to do: class LegacyItemSerializer(serializers.ModelSerializer): created_by = serializers.PrimaryKeyRelatedField( read_only=True, source='created_by_directory_id', ) customer = serializers.PrimaryKeyRelatedField( queryset=Directory.objects.all(), source='directory_id', ) id = serializers.PrimaryKeyRelatedField( read_only=True, source='legacyitem_id' ) modified_by = serializers.PrimaryKeyRelatedField( read_only=True, source='modified_by_directory_id', ) notes = serializers.DateField(source='legacyitem_notes') class Meta: fields = [ 'id', 'customer', 'notes', 'created_by', 'created_date', 'modified_by', 'modified_date', ] model = LegacyItem read_only_fields = [ 'created_date', 'modified_date', ] All we want to do is rename the fields. We don't want to change the validation and would rather keep most of that validation on the model and … -
Django: Automatically update database field to True with background task when condition is met
I have a Model Job which has a field filled. I want to automatically update filled to True if the current_date and time is equal to the Job's end_date and time. The end_date is set when creating the job. I am using a background task to check all Jobs in the DB and repeat the process always, but I can't get it to work. Here is my code Model.py class Job(models.Model): # title, description, requirements, job type etc. end_date = models.DateTimeField(null=True, blank=True) current_date = models.DateTimeField(null=True, blank=True) filled = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title task.py from django.utils import timezone queryset = Job.objects.all() @background(schedule=60) def auto_mark_as_filled(jobs): for job in [jobs]: job.date = timezone.now() if job.end_date == job.current_date: job.filled = True job.save() return jobs # repeat always/every seconds auto_mark_as_filled(queryset, repeat=1) I get TypeError: Object of type QuerySet is not JSON serializable I don't want to use celery as a background task is easier to implement. Any help will be appreciated thanks -
WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module
I use django 3.1.1 and Python 3.8.5. I want to create simple blog. I use some old code in which programmer used django 1.11 probably, so I change many things, but now I'm stuck I get error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. When I try to remove WSGI_APPLICATION = 'mysite.wsgi.application' I get an error ImportError: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class This is my whole setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*s@w*wx_w23k5vp%c%*aatqr42dsu3m$^(et@a(yrx$(4j-u*o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] SITE_ID = 1 # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'blog', 'taggit', 'haystack', ) MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF … -
¿Cómo instalar kerberos en windows?
Estoy investigando sobre el protocolo de autenticación Kerberos, hasta ahora he creado un proyecto en Django y ahí instale el modulo django-auth-kerberos, e hice las configuración del backend. Lo que no se es cómo instalar Kerberos en Windows, para crear los reinos dominios y demás configuraciones para kerberizar. ¿Kerberos se instala es solo en un servidor?, agradecería saber si existe una configuración para instalarlo en un maquina por ejemplo de windows 10 donde pueda crear reinos y todo lo de kerberos. -
Django do something when model instance created
I'm looking to update a user's coin count in their profile whenever I create a promo code redemption object from a model. Is there a method that runs when the object is created so I can update a field in the users profile from the promo code redemption model? I tried init() but the arguments were no longer being filled in and saved in the model and I'm just looking to run extra code rather than adding custom fields. I saw the signals file mentioned but wouldn't it be simpler to have it be done automatically through the model as a method? class Promo_Code_Redemption(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=9,decimal_places=2) date = models.DateTimeField(default=timezone.now) code = models.ForeignKey(Promo_Code, on_delete=models.CASCADE) code_text = models.TextField() revenue_type = "Promo code" def __str__(self): return self.code.code class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) withdrawal_email = models.EmailField(max_length=254) currency_total = models.DecimalField(max_digits=9,decimal_places=2,default=0.00) currency_earned_all_time = models.DecimalField(max_digits=11,decimal_places=2,default=0.00) def __str__(self): return self.user.username views.py @login_required def codes(request): if request.method == 'POST': form = Promo_code_redeem_form(request.user, request.POST) if form.is_valid(): promo_code = form.cleaned_data.get('code_text') #create promo code redemption instance Promo_Code_Redemption.objects.create(user=request.user, amount=Promo_Code.objects.get(code=promo_code.lower()).internal_currency_value, code=Promo_Code.objects.get(code=promo_code.lower()), code_text=promo_code) messages.success(request, f'Promo code redeemed succesfully!') return redirect('codes') else: form = Promo_code_redeem_form(request.user) codes = Promo_Code_Redemption.objects.filter(user=request.user).order_by('-date') total_codes_redeemed = Promo_Code_Redemption.objects.filter(user=request.user).count() total_codes_value = Promo_Code_Redemption.objects.filter(user=request.user).aggregate(Sum('amount')) total_codes_value = total_codes_value['amount__sum'] context = { …