Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tenant-schemas: How to drop a schema within utils.py?
tenant-schemas, and I am wondering how should I delete a schema from my database? Basically I have a trial system on my program, and once the trial duration is up, I would like to delete the schema entirely. Is there any way for me to do so? Either using django-tenant-schemas or using connection.cursor? I would like to achieve this inside my utils.py Thanks all -
Neo4j Spatial database and GeDjango framework
I want to develop a web app with Neo4j Spatial database and GeDjango framework but not fount any driver supporting spatial data. I am searching thinks that not exist?? -
Django def form_valid with two forms
I'd like to use two forms into the same views. It is a restricted channel. The first forms is a chat and the second one launch the conversation (boolean fiels with default = false). All forms share the same success url. Do you have any ideas? I'm beginning with Django :) Thanks for your help Here is my views: @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView, FormMixin): model = Sugargroup context_object_name = 'sugargroup' template_name = 'checkout_detail.html' form_class = CreateSugarChatForm validation_form_class = LaunchSugargroupForm # that is what I would like to add (models: boolean field with false default = user activate channel in changing it by true thanks to the forms def get_context_data(self, **kwargs): context = super(CheckoutDetail, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.sugargroup = self.object form.instance.user = self.request.user form.save() return super(CheckoutDetail, self).form_valid(form) else: return super(CheckoutDetail, self).form_invalid(form) ### I don't know how I can implement this into: def form_valid def form_valid(self, validation_form): validation_form.instance.user = self.request.user validation_form.save() return super(CheckoutDetail, self).form_valid(validation_form) ###### def post(self,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) def get_success_url(self): return reverse('checkout:checkout_detail',kwargs={"slug":self.object.slug}) ... -
My django rest api returns ID and password on authentication in response to react client
Login Function function login(username, password) { return dispatch => { dispatch(request({ username })); userService.login(username, password) .then( user => { dispatch(success(user)); history.push('/home'); window.location.reload() }, error => { dispatch(failure(error.toString())); dispatch(alertActions.error(error.toString())); } ); }; function request(user) { return { type: userConstants.LOGIN_REQUEST, user } } function success(user) { return { type: userConstants.LOGIN_SUCCESS, user } } function failure(error) { return { type: userConstants.LOGIN_FAILURE, error } } } async function login(email, password) { const axios = require('axios') const url = process.env.REACT_APP_AXIOS_URL; return axios({ method: 'post', url: `${url}/api-token-auth/`, data: { "email": email, "password": password, } }) .then(handleResponse) .then(user => { localStorage.setItem('user', JSON.stringify(user.data.token)); return user; }); } function handleResponse(response) { if (response.status !== 200){ if(response.status === 401){ logout() window.location.reload() } // const error = (data && data.message) ||response.statusText; return Promise.reject(response) } return response;} I dont think that problem will be on django side. I don't understand why the response return all data including ID and password when it is a post request. Is it standard and will it lead to big security loop holes? thank you for your help -
Django fails to login user
Authenticating a user using valid credentials passes on the login view. When request.user.is_authenticated is printed, it even outputs True. But after redirecting to LOGIN_REDIRECT_URL, the request is returned back to LOGIN_URL meaning the just authenticated user is no longer authenticated. The project in concern is a mixed project i.e It uses core django builtin view, route and templating as well as djangorestframework. djangorestframework TokenAuthentication has worked fine so far, but when i try logging in with core django view i get this weird situation. I'm using a custom auth user model and two backend authentication ( which are all working fine on api authentication and authorization ). Every other aspect of the project works fine, the only issue is this authentication. I've tried several resource to fix this, but all lead to dead ends. I even used functional based view and django builtin LoginView (as an inherited class and on path route ), same occurence i got irrespective. Tools Django 3.1.1 Python 3.8.4 Postgres Postgis django restframework 3.11.1 settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.gis', # installed apps and third party apps ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] AUTH_USER_MODEL = 'accounts.Account' … -
Looking for a module in django like autoindex in flask
I want to show all files and folders of a path to download or read files. For this task I found a module autoindex in flask but I need the same in django. Please guide. -
Page not found after host django project in server but same project working in localhost
I have host my Django projects in a shared host and after successfully host it seem everything okay.Css,main,page,abou every pages URL working good.But when i click a post in a page then Its showing Page not found (404) error. I have used slug to make user friendly URL. But the most important thing is when I run the same project in my localhost its don't show the error. Everything is okay on my localhost.Why it happening. I need the proper reason and solutions. enter image description here Here is main Projects URL code urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static #site map import from django.views.generic.base import TemplateView from blog.sitemap import PostSitemap from linux.sitemap import LinuxPostSitemap from development.sitemap import DevelopmentPostSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { "post": PostSitemap, "linuxpost": LinuxPostSitemap, "developmentpost": DevelopmentPostSitemap, } urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('blog/accounts/', include('accounts.urls')), path('blog/development/', include('development.urls')), path('blog/linux/', include('linux.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'), path( "robots.txt", TemplateView.as_view(template_name="robots.txt", content_type="text/plain"), ), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Then is my blog app urls urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = … -
Raw (without any messages) django.db.utils.OperationalError
Installed packages: Django pyscopg2 Problem: I created a django project and added postgresql engine for my database. I also created a database in psql shell named chattingsdb. When I run python manage.py runserver command I get traceback with django.db.utils.OperationalError. But when I change db engine (for example on sqlite3) django works properly. Here is all changed code (settings.py): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'chattingsdb', 'USERNAME': 'postgres', 'PASSWORD': 'proper_password', 'HOST': 'localhost', 'PORT': '', } } This is traceback: https://www.paste.org/110141 I really hope for your help, because now I have no idea how to solve it. -
How to replace Foreign Key with Many To Many in Django models without broking whole app?
I want to change my Foreign Key to Many To Many field to let user select multiple categories in a dropdown list. This is what I already have. After I change Foreign Key to Many To Many I'm getting milion errors, I have to get rid of on_delete=models.CASCADE which is a core of my app. What can I do? Which way should I take? Maybe add another model? Im so confused, especially when I am a django newbie. Thank you for help! MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' -
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
i got an error "SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data" this is the code, idk what's wrong. help me pls -
NoReverseMatch error with default django authentciation app
I am getting a http 500 NoReverseMatch error while trying to do a password reset. The error is: Exception Value: Reverse for 'password_reset_confirm' with keyword arguments '{'uibd64': 'MQ', 'token': 'aacknw-b2a16b47efcb9e103d0375c1793945f1'}' not found. 1 pattern(s) tried: ['accounts/reset/(?P<uidb64>[^/]+)/(?P<token>[^/]+)/$'] However the 4 password reset URLS are already created by default, and the password_reset_confirm URL which accepts uidb64 and tokens already exists by default: accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete'] If I try to access it manually by going to accounts/reset/<randomuid>/<randomtoken> it works! The template for the page loads. [EDIT] So the error appears to be internal when password_reset possibly tries to communicate with password_reset_confirm to try and pass tokens maybe? I feel like there is a wierd internal server error which maybe I caused with miss setting something but I have combed through the project multiple times. -
Django Script (Object of type WSGIRequest is not JSON serializable) Celery
I have a API import script that I'm trying to send to Celery. However, when I try to send the request, i get this error message. "Object of type WSGIRequest is not JSON serializable" . How do i fix this or is there a different sterilizer i should be using ? Posted below is the actual code for the function and I also attached the tasks.py with the shared app decorator . Powerschool.py def ImportStudents(request): AuthTokenP(request) print("Getting student data from SIS for K-8") #Pulls K-8 Students url = "" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') xml_string = ET.fromstring(encode_xml) students = xml_string.findall("student") for student in students: #XML Values psid = student.find("id").text first_name = student.find("name").find("first_name").text last_name = student.find("name").find("last_name").text student_name = first_name +" "+ last_name #Checks if XML Values Contain Blanks try: gender = student.find("demographics").find("gender").text projected_graduation_year = student.find("demographics").find("projected_graduation_year").text except Exception: gender = "" projected_graduation_year = "" try: email= student.find("contact_info").find("email").text except Exception: email= "" try: grade_level = student.find("school_enrollment").find("grade_level").text student_enrollment = student.find("school_enrollment").find("enroll_status").text school_number= student.find("school_enrollment").find("school_number").text except Exception: student_enrollment = "" grade_level = "" school_number= "" try: home_room = student.find("schedule_setup").find("home_room").text except Exception: home_room = "" if not Student.objects.filter(studentpsid=psid): … -
I Tried to use django template for the first time but {% block content%} doesn't return anything
I'm having trouble trying to show the content within the tag. So I wanted a Form in Content.html to show in Base.html but it doesn't show up. Base.html <div class="jumbotron text-center"> <h1>Upload Data</h1> </div> <div class="Container"> {% block content %} {% endblock %} </div> <div> <footer class="container-fluid"> <p>Footer Text</p> </footer> </div> </body> Content.html { % extends 'WareHouse/Base.html' %} {% block content %} <div class="container"> <form action="#" name="File"> <table class="container"> <tr> <td> <label for="myfile">Select a file:</label> </td> <td> <input type="file" id="myfile" name="myfile"> </td> <td> <input type="submit"> </td> </tr> </table> </form> </div> {% endblock %} Urls.py and views.py urlpatterns = [ path('',Content), path('Base/',Base) ] def Content(request): return render(request,'Warehouse/Content.html') def Base(request): return render(request,'Warehouse/Base.html') Any advice would be appreciated, Thank you -
Creating django select-2 custom widget
I am trying to add a django custom select2 in my site. However, it looks like my js file is not being read properly. I have been stuck troubleshooting this error, does anyone have insight on what might be happening? It does work with older select2 versions like 4.0.0, but I kept getting the autoscroll bug which was fixed after version 4.0.6. I am not sure why it wasn't a simple plug and play to update. I call the versions in my widgets.py class Select2Mixin(): class Media: css = { 'all': ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css",) } js = ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js", "customselect2.js") This is how I call it in my base.html <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"/> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"/> <!--Importing Javascript--> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"> </script> <script type="text/javascript" src="{% static 'js/customselect2.js' %}"></script> This is how I try and define in my customselect2.js $(document).ready(() => { $.fn.select2.amd.define('select2/selectAllAdapter',[ 'select2/utils', 'select2/dropdown', 'select2/dropdown/attachBody' ], function (Utils, Dropdown, AttachBody) { function SelectAll() { } SelectAll.prototype.render = function (decorated) { var $rendered = decorated.call(this); var self = this; var $selectAll = $( '<button type="button">&nbsp&nbsp&nbsp&nbspSelect All&nbsp&nbsp&nbsp&nbsp</button>' ); var $unselectAll = $( '<button type="button">&nbsp&nbsp&nbspUnselect All&nbsp&nbsp&nbsp</button>' ); $rendered.find('.select2-dropdown').prepend($unselectAll); $rendered.find('.select2-dropdown').prepend($selectAll); -
Need to create a Djano Model, which will provide option to add Custom-model attribute for every django model automatically
Django rest framework issue- Suppose we have 4 models right now, 1. User, 2.School, 3.Students, 4.Teachers etc. Now all these have some form fields which they need to submit own their own. Now we need to provide a "add button" (optional) on front-end side, which user(either school, students or teacher) clicks and can input a new heading there own their own. and user can add as much "heading" as they want. Now i was instructed to create a Custom model, which will store all these optional fields "heading" in it, which will have user_id , model(to which they related to ,in frontend) and heading. I need to prepare a CRUD functionality for this new custom model. class ModelCustomFields(models.Model): user_id = models.IntegerField() model_related_to = models.CharField(max_length=500) heading = models.CharField(max_length=500) - created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return str(self.heading) Now How do i identify, that which model is user currently using. and how to i input it in my database through my-custom-model(stated above). -
Adding Pop-up Message in Django
i want to display popup message like (welcome <user>) when user will log in. i can add this message to a section of the page by using Django messages Like messages.success(request,welcome {request.user}') and in template {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} but i don't want that. i just want a popup message for few seconds How can i do that in a Django project? Or, is there any way of doing that by using java script event listener? Thanks is advance -
Using Django url as Ajax url
I'm trying to submit a django form via ajax, but I get this error message: Btw my urlpatterns should be fine, they work properly when I simply render the site. jquery-3.5.1.js:10099 POST http://127.0.0.1:8000/%7B%%20url%20%22landing-home%22%20%%7D 404 (Not Found) Here's my url file: from django.urls import path from Landing import views urlpatterns = [ path('', views.home, name='landing-home'), ] My ajax call: $(document).ready(function(){ console.log("Ready!"); const form = document.getElementById("form"); form.addEventListener("submit", submitHandler); function submitHandler(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "landing-home" %}', data: $('#form').serialize(), dataType: 'json', success: function(data){ if(data.msg == 'Success'){ alert("Form is submitted!"); } } }) } }) -
When creating superuser on heroku I receive the error ModuleNotFoundError: No module named 'rest_framework'
I already installed djangorestframework both using python and python3. This error only appears when using heroku run python manage.py createsuperuser I have also tried heroku run python3 manage.py createsuperuser Settings.py: INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'core', ] -
django manytomany field inseting empty data
model class Enrollee(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name')) dependents = models.ManyToManyField(to=Dependant, blank=True, verbose_name=_('dependents')) class Dependant(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name')) view class EnrolleeViewSet(viewsets.ModelViewSet): queryset = models.Enrollee.objects.all() serializer_class = serializers.EnrolleeSerializer filter_class = filters.EnrolleeFilter serializers class EnrolleeSerializer(DynamicFieldsMixin, DynamicFieldsModelSerializer): dependents = DependantSerializer(many=True, required=False) def create(self, validated_data): dependant_data = validated_data.pop('dependents') enrollee = models.Enrollee.objects.create(**validated_data) for dependant in dependant_data: models.Dependant.objects.create(**dependant) return enrollee class Meta: model = models.Enrollee fields = '__all__' error: { "first_name": "hmo1", "dependents": [], } It means dependents is not inserting Here I am trying to send nested data for my dependents(ManyToManyField) But, Getting above error while inserting data. Is there any way we can achive this ? { "first_name":"soubhagya", "dependents" : [ { "first_name":"soubhagya" } ] } Above is the data i am sending using post method. please have a look -
Why does Django Rest Framework add a slash on my URL when i filter?
I'm just getting started to Django Rest Framework and i created my first endpoints. Now, i'm trying to add filtering to my URLS but there are two things i don't understand yet: I created the following route: router.register(r'endpoint', views.myView, basename='myView'). When i try to filter on my browser like the following http://127.0.0.1:8000/api/endpoint?&user=TEST, i will get redirected to http://127.0.0.1:8000/api/endpoint/?&user=TEST. Why is there a slash before the ?? What is the difference between using router.register and a standard view on my urlpatterns like i would do in Django? -
Why aren't my messages showing up in HTML using Django?
For some reason I'm not getting any error messages showing up when the bid is too low. Anyone see why? views.py: def bid(request, username): price = request.POST.get("price") itemID = request.POST.get("itemID") newBid = request.POST.get("newBid") title = request.POST.get("title") query = Bid.objects.filter(itemID = itemID).first() if(newBid > price): query2 = NewPost.objects.filter(title = title).update(price = newBid) new = Bid.objects.create(itemID = itemID, newBid = newBid, highestBidder = username) new.save() return render(request, "auctions/index.html") else: messages.add_message(request, messages.INFO, 'Bid Too Low') return render(request, "auctions/index.html", { "messages": messages }) index.html: {% for message in messages %} <li>{{ message }}</li> {% endfor %} -
Django middleware - get view_args
I'm implementing a new middleware using a standard implementation: def my_middleware(get_response): def middleware(request): return get_response(request) return middleware I want to get the view_args. I can change to a class-based middleware and implement the method process_view(request, view_func, view_args, view_kwargs) Is there any other way to get these view_args, view_kwargs in my middleware without changing to class-based middleware? -
jQuery form submit not triggering
I have 2 forms in my html file(Not nested). Each do their own thing in terms of their input fields and do not rely on each other. The problem i'm currently facing is that $(form).submit((event)=>{code}) only works on: <form id="mainForm" action='' method="POST" enctype="multipart/form-data"> {% csrf_token %} <!--Cover image--> <ul class="error" id="coverImageLink_errors"></ul> <div class="cover-img"> {{ mainForm.coverImageLink|add_class:'actual-img' }} <img src="#" id="cover" alt="Your image" style="color: black;"> </div> <!--Music data part--> <div class="music-data"> <ul class="error" id="albumName_errors"></ul> <label for="{ mainForm.albumName.id_for_label }">title</label><br> {{ mainForm.albumName }} <br><br> </div> <input id='albumSubmit' type="submit" value="Next" class="main-form-upload"> </form> <script> $('#mainForm').submit((event)=>{ event.preventDefault(); console.log('AJAX CALLED FOR MAIN FORM'); }); </script> But not on: <form id="AdvancedForm" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul class="last-step-error" id="advancedForm.non_field_errors"></ul> <section id="main-section"> <!-- compresso page --> <div id="compresso-page"> <div class="parent"> <div class="name">0. Hello world</div> <ul class="pre-errors"> <li>Video file is not supported</li> <li>+2 more</li> </ul> </div> </div> </section> <div style="height: 20px;"></div> <!-- prevents collision with button --> <input type="submit" value="Release" onclick="alert('Advanced form submit pressed')"> </form> <script> $('#AdvancedForm').submit((event)=>{ event.preventDefault(); console.log('AJAX CALLED FOR ADVANCED FORM') const url = '{% url "validate-upload-collection" %}' }) </script> I see AJAX CALLED FOR MAIN FORM but not AJAX CALLED FOR ADVANCED FORM If you are confused with {{ something }}, it's just some django(Web framework) variable … -
Does the order of import modules important in django?
I just need to know, either it is important or not? For example in models.py we usually import modules and libraries like reverse or get_user_model; This kinds of importing will grow larger in views.py as we all know. So my question is concerning to the order of these importing, whether is is important or not? -
Service to send email with Django
I'm trying to create a service for send e-mail if the expiration_datetime its less then a week. What i want to do is send just once and not repeat. i'm not sure what should i do Models: class License(models.Model): PACKAGE_CHOISES = ( ('Production', 'Production'), ('Evaluation', 'Evaluation'), ) LICENSE_CHOISES = ( ('js', 'Javascript_sdk'), ('ios', 'Ios_sdk'), ('android', 'Android_sdk'), ) client = models.ForeignKey('Client', on_delete=models.CASCADE) package = models.CharField(max_length=15, choices=PACKAGE_CHOISES, blank=True, null=True) license_type = models.CharField(max_length=15, choices=LICENSE_CHOISES, blank=True, null=True) created_datetime = models.DateTimeField(auto_now=True) expiration_datetime = models.DateTimeField(default=get_default_license_expiration) And here is the service i'm trying to build: def process_licenses(): client = Client.objects.all() licesens = License.objects.all() clients_name = [] hoje = datetime.today() - timedelta(days=7) for date in licesens: if hoje >= date.expiration_datetime: clients_name.append(date.client) for name in clients_name: if name in client: email = EmailMessage( 'Test', 'hi', settings.EMAIL_HOST_USER, [name.admin_poc], ) email.fail_silently=False email.send() time.sleep(30)