Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I write an AWS lambda function for python to resize images?
I am looking for a python script for AWS lambda function but I can't seem to find a proper one. I have looked online and haven't found any answers(yet) to completely fulfill my requirements. I want my photos to be resized immediately and then uploaded into the bucket. I have seen many already build scripts but I wondered how to write that script on the lambda's function on my own. I want to resize my images on different sizes depending on the folder they are being uploaded to. (for example folder1 images to be resized at 600x400 and folder2 at 500x500) Is anyone able to help me with this? I'm very new to this whole AWS services and it's bugging me. -
Django: problem with assignment of the ForeignKey
I want to update the database records from the Pandas DataFrame, and I faced an issue with the ForeignKey. for i, r in df.iterrows(): try: person = Person.obejcts.get(id_no=r['ID Number']) except Person.DoesNotExist: print(f"{r['ID Number']} does not exist in the database") continue t = Task.objects.get_or_create(no=r['Task_no'], defaults={'area': r['Area']}) if not t[1]: t[0].area = r['Area'] t[0].person = person t[0].save() I got an error saying "Task.person" must be a "Person" instance. Any idea what I'm doing wrong? -
remove comments of minified css/js in django compressor
I have django-compressor in my project and i use this filters for minify: 'css': [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ], 'js': [ 'compressor.filters.jsmin.JSMinFilter' ] that works correctly. but this not removed license comments like: /*! * example plugin v1.1.9 * * Copyright 2015-present me * Released under the MIT license * * Date: 2020-09-10 13:16:21 */ i searched and i found that cssmin filter has arguments that removed them. but i think django-compressor not supported it. also i think that i can with COMPRESS_PRECOMPILER config remove this comments. -
How to use hyperlinkedModelSerializer in django rest framework
class ProgramSerializer(serializers.ModelSerializer): class Meta: model = Program fields = '__all__' class ProgramMiniSerializer(serializers.ModelSerializer): programCode = serializers.HyperlinkedRelatedField(many=True,view_name='program-detail', read_only=True) class Meta: model = Program fields = ('programCode', 'pro_name', 'url', 'DepartmentID') -
Django ForeignKey Relationship with an intermediate Table
I have the Goal Model and every Goal can have one Mastergoal and or multiple Subgoals. Goals are connected with Links and every Link can have a different weight. How do I achieve this with Django? What I've got so far: class Goal(models.Model): user = models.ForeignKey(CustomUser, related_name='goals', on_delete=models.CASCADE) name = models.CharField(max_length=300) sub_goals = models.ManyToManyField(to='self', through='Link', symmetrical=False, related_name='master_goals') class Link(models.Model): master_goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="sub_links") sub_goal = models.OneToOneField(Goal, on_delete=models.CASCADE, related_name="master_links") weight = models.PositiveSmallIntegerField(default=1) I can't just add an ForeignKey Field on Goal to itself, because every Link can have a different weight. The solution I've got now works, but it feels wrong. I want to be able to access a Goal's Mastergoal like this: goal.master_goal -
Django framework project
I have tried to make a blog using python django and I have created it but while I try to register and save the data it says operationalError no such table: main_auth_user__old I have tried python manage.py migrate still I am having problems. -
See if values is related to ManyToManyField
I have two models, Major and Course like this: class Major(models.Model): required_courses = models.ManyToManyField(Course, related_name='required_courses') class Course(models.Model): # a bunch of fields... I have several Majors (Computer Science, Psychology, etc.) where each of them contains a different set of required_courses. In my views.py I am getting the course like this course = Course.objects.get(id=pk). Is there an elegant way to see if this particular class is in required_courses in any of my Major models? Im trying to use majors = Major.objects.all().values("required_courses") but that just returns <QuerySet [{'required_courses': 1}, {'required_courses': 2}, {'required_courses': 4}, {'required_courses': 5}]> -
ERRORS: products.ProductsEnterprise: (fields.E180) SQLite does not support JSONFields
after doing migrate in django i get this error. ERRORS: products.ProductsEnterprise: (fields.E180) SQLite does not support JSONFields. -
accsec dicts inside one list python
i have this dicts inside list : myList = [ { 'foo':12, 'bar':14 }, { 'foo':52, 'bar':641 }, { 'foo':6, 'bar':84 }] print(myList) = [{'foo': 12, 'bar': 14}, {'foo': 52, 'bar': 641}, {'foo': 6, 'bar': 84}] i want to access to all dict with key 'foo' only to get this ruslut : [{'foo': 12}, {'foo': 52}, {'foo': 6}] or [12, 52, 6] i try print(myList['foo']) but i got erorr -
Django LDAP: uid and password set from post request
I am a beginner in Django and I am trying through LDAP at login to set uid and password from POST request but I can`t figure it out. Im using django rest framwork which returns token after login superuser but I dont know how to do it with LDAP Is there a way to do it? Here is my code: setings.py AUTH_LDAP_SERVER_URI = "ldap://exmaple.com" # I need something like this but I dont know how to do it user_from_POST_request = request.GET.get('username') password_from_POST_request = request.GET.get('password') AUTH_LDAP_BIND_DN = "uid" + user_from_POST_request + ",ou=group,dc=exmaple,dc=com" AUTH_LDAP_BIND_PASSWORD = password_from_POST_request AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=group,dc=exmaple,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) urls.py path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'), request http://127.0.0.1:8000/api-token-auth/ body: username: user_login password: password -
Factory-Boy - KeyError: 'locale'
Got an exception: def generate(self, params): > locale = params.pop('locale') E KeyError: 'locale' Code example: import factory from django.db import models class MyModel(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() is_cheat = models.BooleanField() class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel name = factory.Faker("name") is_cheap = factory.Faker("boolean") price = factory.Maybe("is_cheap", yes_declaration=factoryFaker("pyint", max_value=10), no_declaration=factory.Faker("pyint", min_value=100)) How to solve that issue? Everything worked few days ago. -
I can't get my tags value from object Django
I am trying to get my BlogPost's tags value from obj in my case but I am not sure how. I am not sure but I think there is a different approach because for my tags field I used : manytomanyfield. For my other fields it is properly working. My models.py class Tag(models.Model): tag = models.CharField(max_length=250) def __str__(self): return self.tag class BlogPost(models.Model): # blogpost_set -> queryset .... title = models.CharField(max_length=120) content = models.TextField(null=True, blank=True) tags = models.ManyToManyField(Tag) .... This is a part of my views.py @login_required(login_url='login') def blog_post_update_view(request, slug): template_name = 'form.html' update_view = True obj = get_object_or_404(BlogPost, slug=slug) form = BlogPostForm(some_title=obj.title, some_content=obj.content) category = Category.objects.all() tagss = Tag.objects.all() print(obj.title) print(obj.tags) .... This is the value of obj.tags in cmd: I do have tags in my BlogPost -
Django annotate date with timedelta and increase
I am trying to query all the expired bookings and i don't have any fields like end_date, I have start date and total days. This is my query: import datetime from django.db.models import Avg, Count, Min, Sum, FloatField, ExpressionWrapper, F, DateTimeField trip = Booking.objects.annotate( end_date=ExpressionWrapper( F('start_date') + datetime.timedelta(days=F('itineraray__days')), output_field=DateTimeField() ) ) these are my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Booking(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) You may be noticed that I have a method to get end_date def get_end_date(self): That is why I am trying to annotate to get the end date and query based on the end date to get expired booking. in my query, you may noticed this line: DateTime.timedelta(days=F('itineraray__days')) so you know timedelta days take argument type as an integer but passed this itineraray__days which caused the error. Can anyone help me in this case? -
Ajax call takes too much more time to be resolved
The waiting (TTFB) takes many seconds (52s) as we can see here enter image description here and I don't know the reason that caused the delay and the only thing I doubt is in an external directory ("app") I have added to my django's view because when I don't use it, everything goes well, and here my project structure. . ├── app | |_ __init__ | |_ oop(.py) | ├── conjug_app │ |_ __init__ | |_ admin | |_ apps | |_ models | |_tests | |_views │ ├── _my_conjugaison │ |_ __init__ | |_ asgi | |_ settings | |_ urls | |_wsgi ├── templates │ |_ "some files here" │ ├── manage(.py) My AJAX call: $(document).ready(function(){ $(".btn").on("click",(e)=>{ e.preventDefault(); // Get the current button value let vrb = e.target.innerText; //Get the value of the search input let getInputval = $('#searched_vrb').val(); if(vrb == 'Recherche'){ vrb = getInputval; }else{ vrb = vrb; } $.ajax({ type : 'POST', url : '/footer/', async: true, data : { csrfmiddlewaretoken: $('input[name = csrfmiddlewaretoken]').val(), verb_name: vrb, }, success: function (data) { $('body').html(data); }, error: function (data) { alert("it didnt work"); } }) }); }) the Views.py: def Footer(request): res0 = [] context = {} context0 = … -
How to send Django-Template variable to Morris.Line data variable?
I am trying to draw a chart with Morris.line. I have to draw a couple of them so I am trying to make a chart dynamically with for loop. Template.html - body {% for data in datas %} <div class="col-xl-6"> <div class="card"> <div class="card-header" id="test"> <input type="hidden" id="myVar" name="variable" value="{{ data.data|safe}}"> <h5>{{data.id}}</h5> </div> <div class="card-block"> <div id="myfirstchart" style="height:300px"></div> </div> </div> </div> {% endfor %} Template.html - Scripts <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var myVar = document.getElementById("myVar").value; new Morris.Line({ // ID of the element in which to draw the chart. element: 'myfirstchart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: myvar, // The name of the data record attribute that contains x-values. xkey: 'day', // A list of names of data record attributes that contain y-values. ykeys: ['value'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Value'] }) }); </script> here is my view: def data_chart(request): markets = Markets.objects.all().filter(~Q(spider=5)) cutoff = datetime.date.today() - datetime.timedelta(days=7) datas = [] for market in markets: raw_data = ( Products.objects.filter(created_dates__gte=cutoff) .values_list("created_dates__date") .filter(market=market.id) .annotate(count=Count("id")) .values_list("created_dates__date", "count") ) data = [{"day": str(day), … -
Mysql: Django: How to solve Mysql server gone away error
I am using mysql and Django: In Django using celery i get data from 10,000 api connections and then insert the data (10,000 bulk inserts) into sql table everyday. I have my table indexed for certain columns also Sometimes after 1000+ api connections, get mysql server gone After reading many solutions i am running import django.db django.db.close_old_connections() before every api connect. I am not sure will this solve my problem, i am still checking it after implementing it. Can any one give some confirmation will this solve my problem -
DRF Implementing Search Function based on Child field
I need some suggestion. Current my models are define as User = settings.AUTH_USER_MODEL class Profile(models.Model): #originally this is a one-to-one field but will cause an error in my nested serialization Userid= models.ForeignKey(User,on_delete=models.CASCADE,related_name='profile') X= models.CharField(max_length=50) class Post(models.Model): Postid = models.AutoField(primary_key=True) Userid = models.ForeignKey(User,on_delete=models.CASCADE ,related_name='posting') Y = models.TextField() User Model is the Django build in 'auth_User'. And my serialize.py is class viewchildItemSeralizer(serializers.ModelSerializer): class Meta: model=Post exclude = ['Z'] #some other field in post that is not required class viewchildProfileSeralizer(serializers.ModelSerializer): class Meta: model=Profile fields=['X'] class ViewItemSeralizer(serializers.ModelSerializer): posting= viewchildItemSeralizer(read_only=True ,many=True) profile = viewchildProfileSeralizer(read_only=True,many=True) class Meta: model=User fields=['username','email','posting','profile'] The code work fine(I am able to response in Json) if my search is base on the X field in the Profile.But I would also need to Implement another search function where base on the "search_argument" on Y field in Post I am able to return only the particular row value along with some data in User( username,email ) and Profile(X). I do not think that the queryset will be User.objects.filter(post__Y=searcharg) # as that will just return all the Post Item for that User #Unsure what would be the queryset if I am query from Post.. will search__related help ? plus, most likely I would also need … -
Django Form Render in Bootstrap Modal
I hope you could help me to solve this. I have a bootstrap modal HTML template with tabs Login/Register. More specifically in the home page there is a button when clicked a popup appears with 2 tabs buttons Login (tab1), Register (tab2). Below is the html code: <!-- Main Header Nav Starts --> <header class="header-nav menu_style_home_one navbar-scrolltofixed stricky main-menu"> <div class="container-fluid p0"> <!-- Ace Responsive Menu --> <nav> <!-- Menu Toggle btn--> <div class="menu-toggle"> <img class="nav_logo_img img-fluid" src="{% static 'images/header-logo.png' %}" alt="header-logo.png"> <button type="button" id="menu-btn"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <a href="{% url 'index' %}" class="navbar_brand float-left dn-smd"> <img class="logo1 img-fluid" src="{% static 'images/header-logo.png' %}" alt="header-logo.png"> <img class="logo2 img-fluid" src="{% static 'images/header-logo2.png' %}" alt="header-logo2.png"> <span>Evillio</span> </a> <!-- Responsive Menu Structure--> <!--Note: declare the Menu style in the data-menu-style="horizontal" (options: horizontal, vertical, accordion) --> <ul id="respMenu" class="ace-responsive-menu text-right" data-menu-style="horizontal"> <li> <a href="{% url 'dashboard' %}"><span class="title">Manage Property</span></a> </li> <li> <a href="#"><span class="title">Blog</span></a> </li> <li class="last"> <a href="{% url 'contact' %}"><span class="title">Contact</span></a> </li> <li class="list-inline-item list_s"><a href="" class="btn flaticon-user" data-toggle="modal" data-target="#bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a></li> <li class="list-inline-item add_listing"><a href="#profile"><span class="flaticon-plus"></span><span class="dn-lg"> Create Listing</span></a></li> </ul> </nav> </div> </header> <!-- Main Header Nav Ends --> <!-- Login/Register Starts --> <!-- Modal --> <div … -
DRF PATCH on ManytoMany Field
I would like to add a M2M entry using DRF to my model. And I found this article https://medium.com/@kingsleytorlowei/building-a-many-to-many-modelled-rest-api-with-django-rest-framework-d41f54fe372 The issue I have is, when I use "PATCH" to an asset nothing appears. models : class Asset(models.Model): [...] vulnerabilities = models.ManyToManyField("Vulnerability",verbose_name="vulnerability",blank=True,) class Vulnerability(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) level = models.PositiveSmallIntegerField() serializers: class VulnerabilitySerializer(serializers.ModelSerializer): key = serializers.CharField(source='id', read_only=True) controls = ControlSerializer(read_only=True, many=True) class Meta: model = models.Vulnerability fields = ( 'key', 'id', 'name', 'level', 'controls', ) class AssetSerializer(serializers.ModelSerializer): key = serializers.CharField(source='id', read_only=True) class Meta: model = models.Asset fields = ( 'key', 'id', 'name', 'weight', 'vulnerabilities', ) depth = 3 When I GET /api/asset/xxx { "key": "xxx", "id": "xxx", "name": "aaaaaaaaaaaa", "weight": 3, "vulnerabilities": [ { "id": "V004", "name": "xazeaze", "level": 3, "controls": [] } ] } So I try to POST an asset and it works : { "key": "A099", "id": "A099", "name": "Asset 999", "weight": 10, "vulnerabilities": [] <---- empty } BUT, when I want to PATCH/PUT for adding Vulnerabilities, there is nothing : Assets Id are "Axxx" Vulnerabilities Id are "Vxxx" as primary_key PATCH ./api/asset/A099 data : { "vulnerabilities": ["V001","V002"] } it returns an empty vulnerabilities: { "key": "A099", "id": "A099", "name": "Asset 999", … -
Django App Deployment to Azure Failing Via Three Methods (problems creating/accessing tmp files)
I have been trying to upload the code from my Django app to Azure. Using multiple methods, it has been failing, with the log messages shown below. The failure seems to relate to the creation of temporary directories by Onyx build. To be transparent, I'm new to both Django and Azure. First, I worked through the Azure tutorial (link below) and was able to get it working with minimal issues. https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone When I attempted to follow the same steps (using "webapp up") with my own app, I get the following error message: Zip deployment failed. {'id': 'XXXXX', 'status': 3, 'status_text': '', 'author_email': 'N/A', 'author': 'N/A', 'deployer': 'Push-Deployer', 'message': 'Created via a push deployment', 'progress': '', 'received_time': '2020-10-21T13:59:11.0137785Z', 'start_time': '2020-10-21T13:59:11.3572791Z', 'end_time': '2020-10-21T13:59:34.2598809Z', 'last_success_end_time': None, 'complete': True, 'active': False, 'is_temp': False, 'is_readonly': True, 'url': 'https://att-informativeness-task.scm.azurewebsites.net/api/deployments/latest', 'log_url': 'https://att-informativeness-task.scm.azurewebsites.net/api/deployments/latest/log', 'site_name': 'att-informativeness-task'}. Please run the command az webapp log deployment show -n att-informativeness-task -g DjangoPostgres-attInform-rg Running the command they recommend, az webapp log deployment show -n att-informativeness-task -g DjangoPostgres-attInform-rg I get: [ { "details_url": null, "id": "XXXXXX", "log_time": "2020-10-21T13:59:11.2061269Z", "message": "Updating submodules.", "type": 0 }, { "details_url": null, "id": "XXXXXX", "log_time": "2020-10-21T13:59:11.324348Z", "message": "Preparing deployment for commit id '53d578b78c'.", "type": 0 }, { "details_url": null, … -
Multiple requests at same time in Django with Sqlalchemy
I am using Django with Sqlalchemy , I am worried about the situation where lets say multiple users request at the same time. I have connection setup with odbc like given below: enginemssql = create_engine(f'mssql+pyodbc://{username}:{password}@DB') do i need to change the connection to avoid exception when multiple requests are made at the same time ? any suggestion will be helpful Thanks -
Django, how to get the time until a cookie expires
Before marked as dup (I believe many answers are incorrect becase): According to my research: request.session.get_expiry_age returns the TOTAL lifespan of the cookie, not the time from now until it expires. It always returns the same value, irrespecitive of how much time is left. Similarly get_expiry_date adds the total lifespan to the now time. It always increases when called. Hence niether of them help. settings.SESSION_SAVE_EVERY_REQUEST refreshes the cookie on every request, this is NOT what I am trying to achieve. get_session_cookie_age() ONLY returns the value of settings.SESSION_COOKIE_AGE, as seen in the sourcecode: def get_session_cookie_age(self): return settings.SESSION_COOKIE_AGE I use the cached_db session back end. The cached part is made none in void because it has to save the cookie everytime, hence SESSION_SAVE_EVERY_REQUEST is not applicable. The reason I ask this question is because I wish to refresh a cookie ONLY if the time left has gone below a threshold, and hence have some hysterious (have the benefits of caching and auto refreshing). Here is my code that does not work because of the behaviour of get_expiry_age/get_expiry_date as explained above: from django.conf import settings from django.utils.deprecation import MiddlewareMixin class SessionExpiry(MiddlewareMixin): def process_request(self, request): """Automatically refresh a session expirary at a certain limit. … -
func form.is_valid() return all time False
I have a form that takes "username" from the User model and my own "email" field. I want to change this data for the User model. At first glance everything seems to work fine, the name changes and the mail is the same. But if I only change the mail and I don't touch the username, I get an error: "A user with this name already exists. file views.py: form=UserUpdateForm(request.POST) if form.is_valid(): user=User.objects.get(username=self.request.user) user.username=form.cleaned_data.get('username') user.email=form.cleaned_data.get('email') user.save() file forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=False) def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) if 'label_suffix' not in kwargs: kwargs['label_suffix'] = '*' self.fields['username'].widget = forms.TextInput(attrs={'class':'input-text'}) self.fields['email'].widget = forms.EmailInput(attrs={'class':'input-text'}) class Meta: model = User fields = ("username","email",) def clean_email(self): cleaned_data = super(UserUpdateForm,self).clean() email=cleaned_data.get('email') return email -
from Django email coming to my Gmail account but sender detail(empty email coming) not coming in my Gmail please suggest any solutions
from Django empty message coming to my Gmail account message body not coming def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_phone = request.POST['message-phone'] message_body = request.POST['message-body'] message_email = request.POST['message-email'] send_mail( 'message_name', 'message_body', 'message_email', ['mye@gmail.com'], fail_silently=False, ) return render(request, 'contact.html', {'message_name': message_name}) else: return render(request, 'contact.html', {})** -
Get the url that should have a function which renders an HTML, Django doesn't show it and returns TemplateDoesNotExist
I want to show an html file when I go to http://localhost:8000/signup/. I tried this views.py: from django.shortcuts import render def signupuser(request): return render(request, 'todo/signupuser.html') And here is urls.py: from django.contrib import admin from django.urls import path from todo import views urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signupuser, name="signupuser") ] But it returns: Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\antoi\Documents\Programming\Learning\Django\todowoo\todo\views.py", line 5, in signupuser return render(request, 'todo/signupuser.html') File "C:\Python36\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: todo/signupuser.html [20/Oct/2020 19:10:08] "GET /signup/ HTTP/1.1" 500 78389 Pero el template existe, esta en C:\Users\antoi\Documents\Programming\Learning\Django\todowoo\todo\templates\todo