Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django's login_required decorator code inside a view function?
I want to write a view in Django (3.2) that allows any user to enter a value, and only after that has been submitted to require login (or signup!). Something like follows: def my_view(request): if request.GET.get('val', None): # now login is required to do something # can we use the login_required decorator here # to forward to login, and then back here after login? else: # login is not yet required # ... a form to gather up 'val' Can I re-use the login_required decorator in some clean way in the middle of the function? I could copy and paste its code (and the code of user_passes_test), but copy-and-paste seems unfortunate. -
Django Rest Framework, How do I grab a foreign key value and add it to my serializer or view to create a new object?
models.py User model it the import auth user model from django class Profile(models.Model): username_id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone_number = PhoneNumberField(blank=True, null=True) image_url = models.ImageField(blank=True, null=True) address = models.CharField(max_length=30) update = models.DateTimeField('Updated at', default=timezone.now()) def __str__(self): return self.username_id.__str__() views.py @api_view(['POST']) def profile_create(request, pk): request serializer = ProfileCreateSerializer(data=request.data) # print(serializer) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors) return Response(serializer.data) serializers.py class ProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['phone_number', 'image_url', 'address'] I want to create a new profile for a user put I don't know where or how to pass the foreign key value to the serializer or view to create a new profile error django.db.utils.IntegrityError: null value in column "username_id_id" of relation "users_pr ofile" violates not-null constraint DETAIL: Failing row contains (, , HELLLfwfwefwf, 2021-09-02 20:08:58.53219+00, null). -
Stripe Django no such price
I have a problem with my Django Stripe Checkout. I tried to make checkout with pricing of items from my e-commerce website but i get an error from Stripe. ERROR: Request req_wfYpUxo6bE40lR: No such price: '2.00' Models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) views.py @csrf_exempt def create_checkout_session(request): if request.method == "GET": try: item = Item.objects.get(title='Kola') checkout_session = stripe.checkout.Session.create( line_items=[ { # TODO: replace this with the `price` of the product you want to sell 'price': item.price, 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url=request.build_absolute_uri(reverse('success-page'))+ '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_uri(reverse('cancel-page')), ) except Exception as e: return HttpResponse(e) return redirect(checkout_session.url, {'item': item}, code=303) -
AttributeError: module 'htmlmin.middleware' has no attribute 'MarkRequestMiddleware'
Trying to deploy my Django Application in Heroku Platform including htmlmin and gzip the application crashed with H10 error code. Inspecting log looks like that the error is related to AttributeError: module 'htmlmin.middleware' has no attribute 'MarkRequestMiddleware' Running locally works perfect (I don´t know why), but after deployment in Heroku Platform the Application doesn´t work. Here is the settings.py code: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", 'django.middleware.gzip.GZipMiddleware', "htmlmin.middleware.HtmlMinifyMiddleware", "htmlmin.middleware.MarkRequestMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ... HTML_MINIFY = True Here is my requirements.txt file: django django_compressor htmlmin gunicorn django-heroku pip==21.0.1 numpy==1.19.1 wordcloud==1.8.1 requests==2.24.0 urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 matplotlib==3.3.4 wikipedia-API==0.5.3 livereload>=2.6.1 whitenoise>=5.0 Here is the Tail Log in Heroku App. 2021-09-02T18:56:35.730191+00:00 app[web.1]: mod = importlib.import_module(module) 2021-09-02T18:56:35.730191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-09-02T18:56:35.730192+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-09-02T18:56:35.730192+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "/app/biblestatistic/wsgi.py", line 16, in <module> 2021-09-02T18:56:35.730194+00:00 app[web.1]: application = get_wsgi_application() 2021-09-02T18:56:35.730195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in … -
Sort a tsv by date with python script
How can I reorder the arrangement of values in my TSV to be sorted by date. The current arrangement is by the first column, but I want to overwrite the file with the same data only arranged by date. The current format is as shows: param1 | param2 | param3 | date | param5 | param6 | Sample content: 1000045|sample 1|10-Q|2021-02-11|edgar/data/1000045/0001564590-21-005399.txt|edgar/data/1000045/0001564590-21-005399-index.html 1000045|sample 1|4/A|2021-02-12|edgar/data/1000045/0001398344-21-003309.txt|edgar/data/1000045/0001398344-21-003309-index.html 1000045|sample 1|4|2021-02-08|edgar/data/1000045/0001496701-21-000001.txt|edgar/data/1000045/0001496701-21-000001-index.html 1000045|sample 1|4|2021-02-09|edgar/data/1000045/0001398344-21-002769.txt|edgar/data/1000045/0001398344-21-002769-index.html 1000045|sample 1|8-K|2021-01-25|edgar/data/1000045/0001564590-21-002004.txt|edgar/data/1000045/0001564590-21-002004-index.html 1000045|sample 1|8-K|2021-02-03|edgar/data/1000045/0001564590-21-003940.txt|edgar/data/1000045/0001564590-21-003940-index.html 1000045|sample 1|8-K|2021-03-08|edgar/data/1000045/0001564590-21-011365.txt|edgar/data/1000045/0001564590-21-011365-index.html 1000045|sample 1|SC 13G/A|2021-02-08|edgar/data/1000045/0001104659-21-013485.txt|edgar/data/1000045/0001104659-21-013485-index.html 1000045|sample 1|SC 13G/A|2021-02-11|edgar/data/1000045/0001037389-21-000122.txt|edgar/data/1000045/0001037389-21-000122-index.html 1000045|sample 1|SC 13G/A|2021-02-12|edgar/data/1000045/0000354204-21-000071.txt|edgar/data/1000045/0000354204-21-000071-index.html 1000097|sample 2|13F-HR|2021-02-16|edgar/data/1000097/0001000097-21-000004.txt|edgar/data/1000097/0001000097-21-000004-index.html 1000097|sample 2|SC 13G|2021-01-11|edgar/data/1000097/0000919574-21-000165.txt|edgar/data/1000097/0000919574-21-000165-index.html 1000177|sample 3|SC 13G/A|2021-01-29|edgar/data/1000177/0000834237-21-004594.txt|edgar/data/1000177/0000834237-21-004594-index.html I tried using bash but it needs to run at the same time as the script I will use. The current script I have is like this: def edgar_filings_download(date): try: # code to rearrange the file with open(edgar_path + filename, 'r') as file: tsv_file = list(csv.reader(file, delimiter='|')) _CHECK = datetime.datetime.strptime(date, "%Y-%m-%d") start_date = datetime.datetime.strptime(tsv_file[len(tsv_file) - 1][3], "%Y-%m-%d") end_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d") if start_date <= _CHECK <= end_date: logger.debug('pass') else: logger.debug('no pass') except Exception as e: logger.error(e) As you may see, I am using the first and last lines as the range of the dates I want to check so I don't have to check line by line. Any help is … -
Django, GraphQL, Mongo - graphene-mongo the only possibility?
I was planning on building a new software using 3 popular technologies: Python, MongoDB and a GraphQL API (Frontend with Angular, but that is not the focus of this post). Although a combination of these three technologies should not be that rare it seems as though the support is extremely limited. The only framework combining these technologies that I have found graphene-python. The support for flask is super limited, the support for django is okay. BUT: I am not sure as to what is happening right now. The last release of graphene-python was more than one year ago. Issues are not answered for multiple weeks. Using it I have experienced multiple issues that seem to have been fixed partially in the repository but not in the official package. Am I missing something? This is not meant to be critique, I am just not sure as to whether I should base our new architecture on that framework. Is there a different framework for that techstack? I know that developing a graphql API could also be done manually but it just doesn't sit right with me. -
How can I properly request.POST of a form with one-to-one relationship?
I'm still getting an error "ModelForm has no model class specified." although I already specified the model in class Meta in DetailForm. How can I properly request.POST of a form with one-to-one relationship? #model.py class Component(models.Model): partnumber = models.CharField(max_length=100) maker = models.ForeignKey(Maker, on_delete=models.RESTRICT, null=True) class Description(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='descriptions') text = models.CharField(max_length=300) def __str__(self): return self.text #form.py class ComponentForm(forms.ModelForm): class Meta: model = Component fields=['partnumber','maker', 'description'] class DetailForm(forms.ModelForm): class Meta: models = Detail fields=['modelseries'] #form.py @login_required def edit(request,id): #Get the current component to edit comp = Component.objects.get(pk=id) comp_detail = comp.detail if request.method == 'POST': c_form = ComponentForm(request.POST, instance=comp) cd_form = DetailForm(instance=comp_detail) if c_form.is_valid and cd_form.is_valid: c_form.instance.author = request.user c_form.save() messages.success(request, f'Component has been updated!') return redirect('component-index') else: c_form = ComponentForm(instance=comp) cd_form = DetailForm(instance=comp_detail) context ={ 'c_form':c_form, 'cd_form':cd_form } return render(request, 'component/edit.html',context) -
Django filter by date range but exclude the year
I know that if I want to filter results by date range, I just use something like Sample.objects.filter(birthday__range=(start_date, end_date)) But how would I filter by a date range that excludes the year? -
Which version of django should I start learning? [closed]
Currently supported versions: I read that there may be some problems due to the version. -
django item have bigger len after applying another filter
As showned bellow, I try to apply new filter to my idmatch queryset. But it return a new queryset with more objects than in the first one. idmatch = IdMatch.objects.filter(idsport=idsport) idmatchcount = idmatch.count() idmatch_liematch = idmatch.filter(match__isnull=False) count = idmatch_liematch.count() print(idmatchcount, count) 605 634 I don't understand how it can be possible that I got a bigger lenght after applying a new filter. The relation between IdMatch and Match is : class IdMatch(models.Model): match = models.ManyToManyField(Match) Ps : I check the 'idmatch_liematch' queryset and it got some pk witch are double... Do someone know why and if it is possible to do the same without any double pk. Thanks -
How to change required = false to an input that is required
My html file has a select, with three different options. If you select one it will display different inputs depending on what option you choose, but this inptus are required by default, and I can't send the form if I don't fill all the inputs. js function yesnoCheck(that) { if (that.value == "1") { document.getElementById("ifStudent").style.display = "block"; } else { document.getElementById("ifStudent").style.display = "none"; } if (that.value == "2"){ document.getElementById("ifAcademic").style.display = "block"; } else { document.getElementById("ifAcademic").style.display = "none"; } if (that.value == "3"){ document.getElementById("ifWorker").style.display = "block"; }else{ document.getElementById("ifWorker").style.display = "none"; } } This is on HTML file <div class="select"> <select onchange="yesnoCheck(this);" name = "school_role" required> <option value="">--------</option> <option value="1">Student</option> <option value="2">Academic</option> <option value="3">Employee</option> </select> </div> <div id="ifStudent" style="display: none;"> <label class="label">Account number</label> <input class="input" type="text" name="account_number" value="{{ studentform.account_number.value }}" placeholder="Account number"> <div class="help is-danger"> {% for error in studentForm.account_number.errors %}{{ error }}{% endfor %} </div> <div id="ifEmployee" style="display: none;"> <label class="label">Employee Number</label> <input class="input" type="text" name="employee_number" value="{{ employeeForm.employee_number.value }}" placeholder="Employee number"> <div class="help is-danger"> {% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %} </div> <div id="ifAcademic" style="display: none;"> <label class="label">Academic number</label> <input class="input" type="text" name="academic_number" value="{{ academicForm.academic_number.value }}" placeholder="Academic number"> <div class="help is-danger"> {% for error in academicForm.academic_number.errors %}{{ error … -
Django Administration - Customize list appearance and selection of ManyToManyField keys
I have a database with 1000+ songs. I have a custom model "Schedule" that accepts songs as field. models.py from django.db import models class Song(models.Model): title = models.CharField(max_length=255) words = models.TextField() slug = models.SlugField() date = models.DateTimeField(auto_now_add=True) snippet = models.CharField(max_length=50) def __str__(self): return self.title class Schedule(models.Model): songs = models.ManyToManyField(Song) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.date) admin.py from django.contrib import admin from .models import Song, Schedule @admin.register(Song) class SongModel(admin.ModelAdmin): search_fields = ('title',) list_display = ('title',) list_per_page = 100 @admin.register(Schedule) class ScheduleModel(admin.ModelAdmin): search_fields = ('date',) list_display = ('date',) list_per_page = 100 I want to be able to add any song I want to a schedule, but it is difficult do to so through the default list in the Django-Administration, which looks like this. I have to scroll and CTRL+select each one of them, then add them. I'd like something more more practical where I can select, search, etc. What are my options? I don't know where to start looking. -
Setting a ImageField initial value
I have a form as below: class FileChangeForm(ModelForm): the_image = forms.ImageField() class Meta: model = ... fields = [ 'fields', 'the_image' ] I want to set the image in the form init, I tried to do a couple of things but nothing seems to populate the HTML form with an initial value using a bytes array. My Init: def __init__(self, *args, **kwargs): super(FileChangeForm, self).__init__(*args, **kwargs) file_data = some byte array kwargs['instance'].meter_image = SimpleUploadedFile('test.png', file_data.content) self.fields['the_image'].initial = SimpleUploadedFile('test.png', file_data.content) -
AWS Boto3: Access denied while running in Django Server
My textract code is successfully working when running in its own file, however, when I try to run it in my django development server, the authentication stops working. I recieve this exception: botocore.errorfactory.InvalidS3ObjectException: An error occurred (InvalidS3ObjectException) when calling the StartDocumentAnalysis operation: Unable to get object metadata from S3. Check object key, region and/or access permissions. So far, I have tried: Passing credentials as parameters in the boto.client() method Assuming a role, rather than using IAM user credentials Verified the object key, and region Checked my firewall Here is my authentication format: client = boto3.client('sts', region_name="us-east-2") # Assumes a role. response = client.assume_role( RoleArn='arn:aws:iam::xxx:role/xxx/xxx', RoleSessionName = 'djangoBoto3', DurationSeconds = 3600, ) textract = boto3.client( # Instantiate the textract client "textract", region_name="us-east-2", aws_access_key_id = response['Credentials']['AccessKeyId'], aws_secret_access_key = response['Credentials']['SecretAccessKey'], aws_session_token = response['Credentials']['SessionToken'] ) Here is how I am calling the textract function response = textract.start_document_analysis( DocumentLocation = { 'S3Object':{ 'Bucket': bucket, 'Name': key, } }, FeatureTypes = ['TABLES', 'FORMS'] ) Some AWS API calls are working within Django. For example I can upload files to S3 buckets. This leads me to suspect maybe this could be a signature issue. I read here Amazon Docs that certain AWS operations such as S3 can … -
Django and a Database with write-Instance + Multiple Read Replicas -- running Celery jobs
I have a django app running in production. Its database has main write instance and a few read replicas. I use DATABASE_ROUTERS to route between the write instance and the read replicas based on whether I need to read or write. I encountered a situation where I have to do some async processing on an object due to a user request. The order of actions is: User submits a request via HTTPS/REST. The view creates an Object and saves it to the DB. Trigger a celery job to process the object outside of the request-response cycle and passing the object ID to it. Sending an OK response to the request. Now, the celery job may kick in in 10 ms or 10 minutes depending on the queue. When it finally tuns, the celery job first tries to load the object based on the ID provided. Initially I had issues doing a my_obj = MyModel.objects.get(pk=given_id) because the read replica would be used at this point, if the queue is empty and the celery job runs immediately after being triggered, the object may have not propagated to the read-replicas yet. I resolved that issue by replacing my_obj = MyModel.objects.get(pk=given_id) with my_obj = … -
Submit form with Django in function view and relate it to request.user
I needed to write a function view where I made some query and a form. My problem is that I can't figure out why the form can't be related to the request.user. views.py def kapcsolodasok(request): profile = Profile.objects.get(user=request.user) related_users = Profile.objects.filter(projekt=profile.projekt) context = { 'related_users': related_users, 'profile': profile, } if request.method == 'POST': kap_bar_01 = request.POST.get('kap_bar_01') kap_bar_02 = request.POST.get('kap_bar_02') kap_bar_03 = request.POST.get('kap_bar_03') kap_bar_04 = request.POST.get('kap_bar_04') kap_bar_05 = request.POST.get('kap_bar_05') kapcsolodasok = Kapcsolodasok(kap_bar_01=kap_bar_01, kap_bar_02=kap_bar_02, kap_bar_03=kap_bar_03, kap_bar_04=kap_bar_04, kap_bar_05=kap_bar_05) kapcsolodasok.save() def form_valid(self, form): form.instance.user_name = self.request.user return super().form_valid(form) return render(request, 'stressz/kapcsolodasok.html', context) models.py class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) kap_bar_02 = models.TextField(max_length=200) kap_bar_03 = models.TextField(max_length=200) kap_bar_04 = models.TextField(max_length=200) kap_bar_05 = models.TextField(max_length=200) def get_absolute_url(self): return "/mpa/siker" class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class KapcsolodasokForm(forms.ModelForm): class Meta: model = Kapcsolodasok fields = '__all__' I think the html is not necessary her. What am I doing wrong? … -
image dislay ubunto django nginx debug=False
hello in the deployment of my site the image only works if debug = True and I would like to use images without hosting in services bad experience thank you -
DataTable limited rows
I have data in my SQLite table and it has 985 rows, so I used DataTable to organise (searching and export to Pdf, CSV...), the problem is that the DataTable is limited rows and just shows the first 200 rows!. my code is <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script the data is stored in table Sqlite and in the HTML page: so what's the solution with? -
Bootstrap nav-brand disappears once navigating to a page other than index
I am new to Python, Django and Bootstrap and was wondering why the nav-brand disappears when I navigate to another page or view other than index. The nav-brand is an image source in my case and below is the following code for my base.html: <body> <nav class="navbar navbar-expand-lg navbar-light bg-light p-md-3"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'index' %}"> <img src="static/images/logo150x63_2_2DP.png" alt=""> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <div class="mx-auto"> </div> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'basic_portfolio:uniprojects' %}">University Projects</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'basic_portfolio:contact' %}">Contact</a> </li> </ul> </div> </div> </nav> {% block content %} {% endblock %} The following is my views.py file: from django.shortcuts import render def index(request): return render(request, 'basic_portfolio/index.html') def uniprojects(request): return render(request, 'basic_portfolio/uniprojects.html') def contact(request): return render(request, 'basic_portfolio/contact.html') My project urls.py file: from django.contrib import admin from django.urls import path, include from basic_portfolio import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('projects/', include('basic_portfolio.urls')), ] My app urls.py file: from django.urls import path, include from basic_portfolio import views app_name = 'basic_portfolio' urlpatterns = [ … -
Django: Associate a social account to currently logged on user
Basically: I want a user to be able to signup with their email and once authenticated they should be able to add a social account and for the social account to be linked(associated) to that currently authenticated user. The link should happen even if the emails are different (between user and social account). A social account cant be linked to more than one user. I am not really interested in user FB account data but rather I want access to their page(s) metrics. I am using Django with Django rest Framework. I also got a custom user model with email instead of username as key Below is my initial attempt (My most relevant part); File Structure [app]/ ├── [app]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── facebook/ │ |── __init__.py | ├── urls.py | ├── serializer.py | └── views.py ├── manage.py ├── README.txt ├── static/ └── README Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'corsheaders', 'accounts', 'rest_framework', 'django_rest_passwordreset', 'social_django', 'facebook' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) ROOT_URLCONF = 'jicaBackend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
how to print attendence of all employee of a month if the attendence is on daily basis in django
I have a model named Attendance. I store the attendance of all employees of a month on daily basis. Now i want to print the attendance of employee in template in the formate EmpId name 1 2 3 4 5 ........................... 29 30 31. Like 2354 rajiv P P P A P P A P P .................................. P P A. First look at model class Attendence(models.Model): EmpId = models.IntegerField(verbose_name='EmpId') Name = models.CharField(max_length=50,verbose_name='Name') Site = models.CharField(max_length=50,verbose_name='Site') Days = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Days') Nh = models.IntegerField(verbose_name='Nh') SingleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='SingleOt',null=True) DoubleOt = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='DobleOt',null=True) choices = [('P','Present'),('A','Absent'),('O','Off')] Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status') AttendenceOn = models.DateField(default = timezone.now) def __str__(self): return '{EmpId}/{Name}/{date}'.format(EmpId=self.EmpId,Name=self.Name,date=self.AttendenceOn) to get my result accordingly i tried the follow code in function attendRegister in view.py def attendRegister(request): attendencelist = {} employee = [] if request.method == 'POST': datefrom = request.POST['DateFrom'] dateto = request.POST['DateTo'] attendencelist = Attendence.objects.filter(AttendenceOn__range=[datefrom,dateto],Site = str(request.user.SuperVisor.Site)).order_by('Name') Date__range = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31] context = { "attendencelist":attendencelist, "date":timezone.now(), "range":Date__range, } return render(request,"attendRegister.html",context) in template i tried the following process <div class="row"> <div class="col-sm-12"> <table class="table table-striped table-hover"> <thead> <tr class="bg-primary" style="color:white; font-size: 0.5rem;"> <th>id</th> <th>Name</th> {% for i in range%} <th>{{forloop.counter}}</th> {% endfor %} </thead> <tbody> {%for attendence in attendencelist%} <tr > <td>{{attendence.EmpId}}</td> <td>{{attendence.Name}}</td> {% if attendence.Status == … -
How to change template file of a PageModel for Preview mode?
I want to use wagtail as headless CMS, so I want the preview (for all pages) to load from the base.html file. Then I will deploy my React app on that file statically. I created the following Page Model class BlogPage(Page): # Database fields body = RichTextField() date = models.DateField("Post date") feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Search index configuration search_fields = Page.search_fields + [ index.SearchField('body'), index.FilterField('date'), ] # Editor panels configuration content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('body', classname="full"), InlinePanel('related_links', label="Related links"), ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] # Parent page / subpage type rules parent_page_types = ['home.HomePage'] subpage_types = [] When I want to preview a page that I created using this model I get the following error: TemplateDoesNotExist at /new-title/ home/blog_page.html Request Method: GET Request URL: http://localhost/new-title/ Django Version: 3.2.6 Exception Type: TemplateDoesNotExist Exception Value: home/blog_page.html Exception Location: My-Folder/.venv/lib/python3.7/site-packages/django/template/loader.py, line 19, in get_template Python Executable: My-Folder/.venv/bin/python Python Version: 3.7.5 Python Path: ['My-Folder/wagtail-react-website/wagtail_website', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', 'My-Folder/.venv/lib/python3.7/site-packages'] Server time: Thu, 02 Sep 2021 10:28:26 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: My-Folder/wagtail-react-website/wagtail_website/wagtail_website/templates/home/blog_page.html (Source does not exist) django.template.loaders.app_directories.Loader: My-Folder/wagtail-react-website/wagtail_website/home/templates/home/blog_page.html (Source does not exist) … -
fetch request resulting in error: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name at HTMLInputElement.<anonymous>
Why am I getting this error? I am trying to fetch my index view to edit an object in one of my models. I don't really know what I am doing with sending the CSRF token in this way, I copied it from an example I found online, so I don't know if that is the problem. Code is below: function edit_post(post) { const content_div = document.getElementById(`post-body-${post.id}`); content_div.innerHTML = ""; const edit_form = document.createElement('div'); const form_input = document.createElement('input'); form_input.setAttribute('type', 'textarea'); form_input.setAttribute('name', 'post-body'); text_to_edit = post.body; form_input.setAttribute('value', text_to_edit); const save_button = document.createElement('input'); save_button.setAttribute('type', 'submit'); save_button.setAttribute('value', 'Save'); save_button.addEventListener('click', () => { const new_body = form_input.value; console.log(`${new_body}`); fetch('/', { method: 'PUT', headers: { 'X-CSRF TOKEN': getCookie("csrftoken") }, body: body = JSON.stringify({ post_id: post.id, new_body: new_body, }) }) .then(response => null) }); edit_form.append(form_input); edit_form.append(save_button); content_div.append(edit_form); } function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length == 2) return parts.pop().split(';').shift(); } -
Django Rest Framework admin panel not using custom User Manager
I have implemented a CustomUser and CustomUserManager in my DRF app. The tutorials I have followed are this one and this one, which are nearly identical approaches to creating a custom user and custom user manager. I placed a print statement in the create_user and create_superuser methods of the custom user manager to check it was being used correctly. class MyUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): print("manager used") ... When I use the command python manage.py addsuperuser, the print statement runs, great. When I use the built-in admin panel of the DRF framework localhost:8000/admin to create a new admin or regular user, the statement doesn't run, however, the user is created without error. As far as I can see, the implementation is meant to have the admin panel use the new customer user manager, but that doesn't seem to be the case. What have I done wrong? -
Can anyone please help/tell me what I am doing wrong? And/Or what I shouldve done in my queries?
I have 3 models that I am using my query on: Models.py class Student(models.Model): ... class SchoolPeriod(models.Model): period = models.CharField(max_length = 100) class StudentGrade(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE,) period = models.ForeignKey(SchoolPeriod, ...) subjects = models.ForeignKey(Subject, on_delete=models.CASCADE) grade = models.DecimalField(default = 75.00, max_digits=4, decimal_places=2) Views.py def viewgrade(request): current_parent = request.user.parent #gets current logged in parent tempstudent = Student.objects.get(parent = current_parent ) #gets student related to parent(theres no student user level) studentgrade = StudentGrade.objects.filter(student = tempstudent) #filters the grades of the student related to the parent logged in ... context = { ... 'studentgrade': studentgrade, } return render(request, 'Information/viewgrade.html', context) viewgrade.html(template) <table style="width:50%"> <tr> <th>Subject</th> <th>Grade</th> </tr> {% for studentgrade in studentgrade %} <tr> <td>{{ studentgrade.subjects }}</td> <td>{{ studentgrade.grade }}</td> </tr> {% endfor %} </table> What I can do was to print on my template the grades of the STUDENT that is related to the PARENT that is currently logged in. But, I also want to arrange it per grading period(quarter) example: **first grading** Science = 99 Math = 99 **second grading** Science = 70 Match = 70 Thanks for the help!