Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authorization header field absent in request.headers() and request.META when using Apache, Preflight CORS error when using custom header
I have my Django Rest Framework API's up and running on an AWS EC2 instance. I'm using Apache server and added an SSL certificate using Let's Encrypt to serve the API as HTTPS at Port 443. I'm using a custom token authentication (generating session token using my own random algorithm). This token is random and unique to each user (after the user is logged in), and hence I'm trying to pass it as a header in my POST request (for validation). But here comes the problem. On doing post request from Postman and also from my React frontend, the header is not getting received in both request.headers("Authorization") and request.META["HTTP_AUTHORIZATION"]. Strangely, the field is only absent (as checked from apache error log after printing both). Hence null is getting assigned to token. After a lot of research over the internet, I changed Authorization to Authorization2. That actually fixes the issue and works great but only while making a request through Postman. Whereas, on doing post request from react end, the browser console says: Access to fetch at 'https://www.myapi.live/api/project/add/8/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization2 is not allowed by Access-Control-Allow-Headers in preflight response. I tried … -
nginx: [emerg] "server_names_hash_bucket_size" directive is not allowed here in /etc/nginx/sites-enabled/django.conf:4 nginx: in AWS EC2
I am getting the above error while deploying my Django application to the AWS EC2 instance. server { listen 80; server_name ec2-34-220-17-196.us-west-2.compute.amazonaws.com; server_names_hash_bucket_size 64; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/AppName/app.sock; } } This is my django.config file in /etc/nginx/sites-available$ route. Please help me out I am stuck here for long while. -
i want to update and view user profile, upload profile also
my view class SignupView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data name = data['name'] email = data['email'] password = data['password'] password2 = data['password2'] if password == password2: if User.objects.filter(email=email).exists(): return Response({'error': 'Email already exists'}) else: if len(password) < 6: return Response({'error': 'Password must be at least 6 characters'}) else: user = User.objects.create_user(email=email, password=password, name=name) user.save() return Response({'success': 'User created successfully'}) else: return Response({'error': 'Passwords do not match'}) my model class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email i want to create user profile and upload profile also view that profile i want to create user profile and upload profile also view that profile i want to create user profile and upload profile also view that profilei want to create user … -
Django - how to call a parent function in a child model
I have a child model with a Foreignkey ("Objective"), that related to a parent model ("Project") in Django. So the "Project" has many "Objectives". My goal is to divide the amount of one particular objective to the total amount of the Project, computed by the function "total_budget". Hence, I am trying to call the function "total_budget" in the "Objective" model. Is it possible? Is that the best way to do it? Here is my models.py code: class Project(models.Model): model_name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) current_savings = models.IntegerField() monthly_salary = models.IntegerField() monthly_savings = models.IntegerField() horizon = models.DateField(default='2025-12-31') def save(self, *args, **kwargs): self.slug = slugify(self.model_name) super(Project, self).save(*args, **kwargs) def total_budget(self): #define current date and horizon to compute the number of months until horizon curr_date = datetime.date.today() horizon = self.horizon dates = [curr_date.strftime('%Y-%m-%d'), horizon.strftime('%Y-%m-%d')] start, end = [datetime.datetime.strptime(_,'%Y-%m-%d') for _ in dates] re_mon = (end. year - start. year) * 12 + (end. month - start. month) #budget is equal to the monthly savings times remaining months, plus current savings budget = self.monthly_savings*re_mon + self.current_savings return budget class Objective(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='objectives') title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=0) expiration = models.DateField() isexpensed = models.BooleanField() investable = models.BooleanField() class … -
This backend doesn't support absolute paths
I´m trying to set a path for some json files I have to open with python open() method. Reading documentation I noticed that path method from class Storage in django.core.files.storage must be overrided but I don't know how to override it since I don't know how to store this path. My files are this way App --index_backend ----json -------some_json.json ----index.py --views.py manage.py I'm quite new on Django, so if you need to see some more code, please tell me to upload as much as needed. -
JSON data from django rest framework not being received
What I have been tying to do recently is to send the data from a website that I am creating using django to a mobile app using flutter the thing is that whenever I try to get the data from the rest framework it doesn't return anything in fact when I see the requested being made to the website no message is displayed that it has received the request I do get a message only if I load the page directly, the catch is if I get json data from others websites like randomuser.me/api/ I do get a response and all the data from it, do I have to set anything in special for the rest framework to accept GET requests in which are not directly made by a browser ? I will be providing the settings that I am using for the rest framework right bellow ! Settings.py REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": [ "rest_framework.renderers.JSONRenderer", # "rest_framework.renderers.BrowsableAPIRenderer", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", # Delete this "rest_framework_jwt.authentication.JSONWebTokenAuthentication" # "rest_framework.authentication.BasicAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated" # Default permission for all apis ], "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", ], } As you can see the Is Authenticated is a default permission class but for the page that … -
Python: Checking between times, dates. Validating dates
I'm trying to create some kind of validation for dates. I have these kinds of dates for my API request. "date_from": "2020-11-20T20:11:00Z", "date_to": "2020-11-20T20:12:50Z" date.timestamp() = 1605903600.0 datetime.utcnow().timestamp() = 1605896932.580989 Let's say the current time is 2020-11-20 20:13:00, and I'm still able to create some objects by providing the older time (2020-11-20T20:11:00Z) than the current. I need to check if the date_from is not less than the current time, so I have tried to: def validate_date_from(self, date): if date.timestamp() <= datetime.utcnow().timestamp(): raise serializers.ValidationError("Meeting could not start earlier than the current time") return date But I'm still able to create the objects via API, so that means the validation method isn't working as it should. Secondly, I have this code snippet (below) it should check if the reservation is currently happening, so basically it checks between the start and the end date and if the current time is between the start and the end date, we can know that meeting is active, but unfortunately, it's not working as well. if parse(reservation['date_from']).timestamp() >= datetime.now().timestamp() <= parse(reservation['date_to']).timestamp(): raise serializers.ValidationError("Room is in-use") parse(reservation['date_from']).timestamp() = 1605903060.0 datetime.now().timestamp() = 1605896745.853667 parse(reservation['date_to']).timestamp() = 1605903170.0 -
Condition to check if the user is in the model and to block before re-enrolling
Hi I have a problem with writing a condition that checks if the logged in user is currently on the list of enrolled users and blocks him from re-enrolling, and if he is on the list, it unlocks my access to the tournament transition. this is my views.py file def groups(request, pk): tournament_groups = get_object_or_404(TournamentGroup, pk=pk) tournament_users = TournamentUsers.objects.filter(user_group=tournament_groups) judges = TournamentJudges.objects.filter(user_tournament=tournament_groups.tournament_name) tournament = Tournament.objects.get(tournament_name=tournament_groups.tournament_name) form = TournamentUsersForm() current_user = request.user.debatants if request.user.is_authenticated: form = TournamentUsersForm( initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups, 'user_full_name': current_user}) if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() context = {'tournament_groups': tournament_groups, 'tournament_users': tournament_users, 'form': form, 'judges': judges, "tournament": tournament, 'current_user': current_user,} return render(request, 'ksm_app2/groups.html', context) this is my models.py file class TournamentUsers(models.Model): user_full_name = models.ForeignKey(Debatants, on_delete=models.SET_NULL, null=True) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.user_full_name.id) this is my template {% for tournament_user in tournament_users %} {% if current_user.id == tournament_user.user_full_name.id %} <h2>Jesteś już zapisany</h2> {% else %} <h2>Zapisz się jako uczestnik</h2> <form method="post" style="visibility: hidden"><br> <button type="submit" style="visibility: visible!important">Zapisz się</button> {% csrf_token %} <label for="name">Imię i nazwisko</label> {{ form.user_full_name }} <label for="tournament">Wybierz turniej</label> {{ form.user_tournament }} <br> <label for="tournament">Wybierz drużyne</label> {{ form.user_group }} <br> </form> {% … -
How correct use values for group by in Django
today I solve made one thing on ORM Django, simple thing, i have a table with date, url and amount of smth(it's not have sense), i need a GROUP BY, for group all url one type in one, and, after that, i have a result, exactly i have one url, all going good, but when i try yous MAX or MIN, i have same result in both situatin (with max and min), when i try use count i get 1, and it's very strainge. Code: url of query code -
Utilizing Django url resolver vs. re-inventing the request.path parsing wheel
Let's say I had the following array: sub_urls = [ '/', '/<uuid:id>', '/test', '/test/<uuid:id>' ] The URL stings are very similar to what you'd find in Django's urlpatterns my question: can django.url.resolve be used to find the pattern in the sub_urls array given a path string like /test/189e8140-e587-4d5d-ac5c-517fd55c67bc without me having to re-invent the wheel here? -
How to make if condition in dropdown
I am trying to make a Django based website, and I want to make a dropdown with if and else conditions working on it, means that if a person selects physics in the dropdown and presses the submit button, it should go to a specific page and if he presses chemistry then it goes to a specific page, please tell me how to do this, I am attaching my code. Main page (home.html): <!DOCTYPE html> <html> <head> <title>Hi there</title> </head> <body> <form action="{% url 'test' %}"> <select name="Subject"> <option value="Mathematics">Mathematics</option> <option value="Physics">Physics</option> <option value="Chemistry">chemistry</option> <option value="accounts">accounts</option> <option value="bsuiness">business</option> </select> <input type="submit" value="Generate Password" class="btn btn-primary"> </form> </body> </html> Views.py: from django.shortcuts import render def home(request): return render(request, 'homepage/home.html') def test(request): if request.GET.get('Physics'): return render(request, 'homepage/home.html') else: return render(request, 'homepage/test2.html') urls.py from django.contrib import admin from django.urls import path from homepage import views as home_views from homepage import views as test_views urlpatterns = [ path('admin/', admin.site.urls), path('', home_views.home, name='home'), path('test/', test_views.test, name='test'), Please help by telling what to code to make the if statement work -
'ManyToManyDescriptor' object has no attribute 'filter'
I am making an application which obtains data and then displays it through graphics, the problem is that I am making a query to know when developers belong to a project, but it throws me an error I disagree that the ManyToManyDescriptor object does not have the filter attribute. My view: class ProjectTemplateView(TemplateView): template_name = 'index.html' def count_developer(self): projects = Project.objects.all() for project in projects: developers = Developer.project_set.filter(project=project).count() print(developers) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects'] = Project.objects.all() context['developers'] = self.count_developer() return context This is my project model: class Project(models.Model): STATUS_CHOICES = ( ('approver', 'Aprovado'), ('process', 'En Proceso'), ('inactive', 'Inactivo'), ) name = models.CharField(max_length=50, unique=True, verbose_name='Nombre') developer = models.ManyToManyField(Developer, verbose_name='Desarrollador') visibility = models.BooleanField(default=False, verbose_name='Visibilidad') status = models.CharField( max_length=10, choices=STATUS_CHOICES, verbose_name='Estatus') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField( auto_now_add=True, verbose_name='Fecha de Creacion') update_at = models.DateTimeField( auto_now=True, verbose_name='Fecha de Actualizacion') And this is my developer model: class Developer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de Creacion') -
contact form send email success but no message in my email box - django
I have created the below django contact form for the contact page of my website. The problem with the form is that when a user fills and clicks the submit button, it show a success message but the email is not sent. i mean i don't receive message in my box Can someone please check and tell me where I went wrong. forms.py : from django import forms from django.forms import ModelForm # contact form class ContactForm(forms.Form): contact_name = forms.CharField(required=True ) contact_email = forms.EmailField(required=True ) title = forms.CharField(required=True) content = forms.CharField(required=True ) views.py : def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') title = request.POST.get('title') template = loader.get_template('website_primary_html_pages/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'title' : title, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "Hey , There are new Message from blog", content, "Creative web" + '', ['contact@techpediaa.com'], headers = { 'Reply To': contact_email } ) email.send() return redirect('Success') return render(request, 'website_primary_html_pages/contact_us.html', {'form':Contact_Form }) #end contact form settings.py : #MY EMAIL SETTING DEFAULT_FROM_EMAIL = 'contact@techpediaa.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' when user fills all fields it show message send success but … -
Modal Submit with Ajax Submitting Non-Modal Form - Django
I am working with a django project where I have a form to create a proforma invoice. Within that form there is a button which launches a bootstrap modal to create a bank which may be needed for the proforma invoice. This modal submits via ajax and when I click submit, it is trying to trigger a submission of the proforma form which does not work because I don't have all the data entered. How can I fix my code to stop the modal submission trying to submit the non-modal form? forms.py class CreateBankForm(forms.ModelForm): class Meta: model = BankAccount fields = ['name', 'account', 'routing', 'swift'] class ProformaForm(forms.ModelForm): class Meta: model = Proforma fields = [ 'name', 'exporter', 'shipment', 'date', 'bank' ] proforma.html <form id="proformaform" method="POST"> ... ... {{proformaForm.as_p}} </form> <p> <button type="button" class="btn btn-primary js-create-book"> <span class="glyphicon glyphicon-plus"></span> New book </button> </p> <!-- THE MODAL WE WILL BE USING --> <div class="modal fade" id="modal-book"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> <script> ////////////CREATE A BANK WITH AJAX $(function () { $(".js-create-book").click(function () { $.ajax({ url: '/create_bank/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); }); $("#modal-book").on("submit", ".js-book-create-form", function () { … -
How to use hex(x ' ' ) inside of a sql statement with python execute?
I am working in Python/Django with a MySQL Db. This sql query works fine in my Workbench SELECT * FROM frontend_appliance_sensor_reading WHERE id = (SELECT max(id) FROM frontend_appliance_sensor_reading WHERE sensor_id = hex(x'28E86479972003D2') AND appliance_id = 185) I am returning the latest record for a sensor. The hex string is the sensor ID that I need to pass in as a variable in python. Here is my python function that would return this object def get_last_sensor_reading(appliance_id, sensor_id): dw_conn = connection dw_cur = dw_conn.cursor() appliance_id_lookup = appliance_id dw_cur.execute(''' SELECT * FROM frontend_appliance_sensor_reading as sr WHERE id = (SELECT max(id) FROM frontend_appliance_sensor_reading WHERE sensor_id = hex(x{sensor_id_lookup}) AND appliance_id = {appliance_id_lookup}) '''.format(appliance_id_lookup=appliance_id_lookup, sensor_id_lookup = str(sensor_id))) values = dw_cur.fetchall() dw_cur.close() dw_conn.close() print values However it seems to concat the x with the variable like this: (1054, "Unknown column 'x9720032F0100DE86' in 'where clause'") I have tried various string combinations to get it to execute correctly with no luck. What am I missing? Does the x actually get interpreted as a str? Or should I be converting it to something else prior? Also, I cannot not use Django's ORM for this as the sensor id is stored in a BinaryField as BLOB data. You cannot filter by … -
Npm run dev command is stuck and wont work
Hello there I recently started watching a tutorial about django rest framework (for the frontend I am using reactjs) but I have a problem with downloading/initializing react. I used the "npm run dev" command in the cmd and it is stuck at: "[webpack-cli] watching files for updates...". Does anyone know what to do?? If so can you pls tell me. -
Django Type Error adding data to model via django admin backend
I have no clue what happened... Yesterday I was in django/admin page testing out the form, making sure I can upload images and it was working perfectly fine. This morning, I get a type error and I cannot for the life of me track down where it's coming from. Here is my models.py from django.db import models class MenuCategory(models.Model): name = models.CharField(max_length=25, unique=True, default='') summary = models.TextField(max_length=120, unique=False, default='') class Meta: verbose_name = 'Menu Category' verbose_name_plural = 'Menu Categories' def __str__(self): return '' + self.name class MenuItem(models.Model): category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) title = models.CharField(max_length=25, unique=True) price = models.FloatField() image = models.ImageField(upload_to='', width_field=200, height_field=200) description = models.TextField(max_length=240, unique=False, default='') class Meta: verbose_name = 'Menu Item' verbose_name_plural = 'Menu Items' def __str__(self): return '' + self.title And my admin.py from django.contrib import admin from menu.models import MenuItem, MenuCategory # Register your models here admin.site.register(MenuItem) admin.site.register(MenuCategory) class MenuInlines(admin.TabularInline): model = MenuItem class CategoryAdmin(admin.ModelAdmin): inlines = [MenuInlines] I really don't understand where the TypeError is =( This seemed to be working fine yesterday and I have no clue what I changed. I did 'makemigrations' and 'migrate' just to be sure... Any clue? Did I leave something out that might be pertinent? -
Can i use Dynamic sidebar menu for multiple users using conditional operator in Django franework?
I have 1 admin and 6 prilages.. admin gives privilages to each user like a, b, c, d, e. If admin gives the prilages of a and c to me, then, i need to see the sidebar with only a and c. But when admin loged in its want to see all sidebar like a, b, c, d, e. -
Update your Django project after deployment in Apache2
So, I deployed my Django Project, my website is currently running but of course I want to keep developing it. Which way does it the most sense? It comes to mind the following methods: -Develop in my work machine, uploading to Github, clone it in my server and copy the files that have been changed. -Develop directly via SSH in VIM. Both don't sound so great. Any other idea? Thank you ! -
{% with %} tag to store 'in' expression value in django template
I'm trying to store a boolean value in a variable within the {% with %} tag of Django. But its not working. is there any other way around to do this ? Can I create a custom filter for it or is there any pre-built filter for this? {% with isEnrolled=course in all_courses %} ..... {% endwith %} -
Append <tr> to HTML table progressively with a JQuery AJAX call (Django framework)
I am new to Javascript, Jquery and Ajax request and I have an issue with the execution of my scripts. Basically I have a very long list to display on my home page (1200+ items). I used to load the page normally but since my list would take a long time to load (and since it's right in the middle of the page) there would be an enormous delay before all my HTML elements would show. For example my footer would be the last item to load and it would appear almost a full second after my navbar. I decided to use AJAX requests to load my HTML first, get my navbar and my footer done and only then fetch my list to show it in the middle of my page. The first problem I encounter is that while my script is being processed, nothing appears. This means that even if my first list item's "tr" is ready, it will only show when the 1200th's "tr" is also ready. I would need the table to be populated progressively. I can see my "tr"s being generated in my console but they are only applied in my HTML after they are all … -
Append an item to a streamfield in wagtail
I have a streamfield which is working, and has data in, the code I wrote to do this looks something like: class NewYearBlock(blocks.StructBlock): year = blocks.IntegerBlock(verbose_name="Year (the year this data is rolling into)") holidayRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") overtimeRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") class Meta: icon = 'user' and newyearStream = StreamField([ ('newyear', NewYearBlock()), ], blank=True) What I would like to do is to append an item to this streamfield via some code, I know how to replace the item with the below (which works) employeeModel.newyearStream = newyearStream employeeModel.save() But this replaces what already exists. I was then thinking I could loop over the existing stream, and then create a new object to save, but when I try to do that I receive TypeError: cannot unpack non-iterable StreamChild object so I looked at the type, and see it is <class 'wagtail.core.blocks.stream_block.StreamValue'> Can anyone help point me in the right direction to either loop through the stream and get my results out, or a better way to append to my streamField. Thanks for your time helping, Dan -
How to print Django queryset in Tabular form in python3 manage.py shell
Is there a way or package to print Django queryset in Tabular form in python3 manage.py shell The queryset prints like this: But I want it to be printed like this -
Django auto_now count results in a certain date
I want filter of all request done is done in a certain date class Log(models.Model): request = models.CharField(max_length=255) created_at = models.DateField(default=now, blank=True) def __str__(self): return self.request But I don't how to do it correctly compare both the created_at and the date today quantity_of_requests = Log.objects.filter(created_at=now()).count() -
How to serve a rendered JPEG image with Django Rest Framework?
On a call to my Django API, I'm trying to generate an image with matplotlib and then serve this image back to the client using Django Rest Framework. I'm aware of Serve images with django-rest-framework and Return image using Django REST framework Render, but they can't quite get me there. I think I'm supposed to create a sort of CustomRenderer, then pass the result to the view. I'm unclear about how such a view.py should look. What would be really ideal would be to be able to generate the image in memory, and then serve this without having to save it as a physical file on my server. So I have the image renderer, render.py in my app's directory: # app/render.py from rest_framework import renderers from matplotlib import pyplot as plt class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): # data coming in would be a numpy array # Matplotlib can create the image from the numpy data array. # It would be cool to generate and return this as a Bytes IO object # to avoid persisting the file on my server as pass this to the view, …