Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate angular application in Django project
I am developing a project with Django in backend and Angular in frontend. My Angular build application contains one index.html file, some folders and some files. I want to integrate my angular application with my Django project, which contains some applications. What should be my directory structure. Where do I need to map my URLs to call the index.html page of angular. The output I need to achieve is: When hitting the homepage URL, the single sign on application of Django should run to authenticate the user and after authentication redirection to index homepage(of angular) should happen. What should be the way to achieve this? -
Problem with static files configurations - don't understand project/app staticfiles organization
I have started to develop a Django project with currently 3 apps (registration, monitor and randomization) I wand to set parameters for statics files. I am using bootstrap 4.0 and I have currently only one css files for sticky footer as this css is for all template of the project, I have created a static folder at the project's root: -project - settings.py - monitor - randomization - registration - static - css - styles.css - images and in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = 'D:/Users/jl3/DevSpace/intenseTBM_eTool/static/' I have run the commande collectatic but I have an error: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. how can I set 'global' static files for my project? how should I set parameters? -
pdf tag doesnt open pdf files on chrome but works on other browsers, why?
i am trying to display pdf documents on the browser but its not displaying on chrome, instead its downloading, but on other browsers like IE it's working just fine {% block content_display %} <embed type="application/PDF" src="{{bk.upload_content.url}}" width="100%" height="650"/> {% end block %} -
Show distinct values in dropdown menu with django-select2
I am using django-select2 with forms for creating a drop-down list, using ModelSelect2Widget. My problem is that I filter on the field 'name' and several objects can have the same 'name' but different 'value' (see model description below). This leads to the same name appearing several times in the dropdown menu. I would like to remove these duplicates. I tried to use .distinct('name') for selecting the queryset, but it doesn't seem to work. example of result obtained with ModelSelect2Widget Below is the description of the code I use: I have two models linked by a foreign key models.py class Who(models.Model): name = models.CharField(max_length=256) value = models.CharField(max_length=256) def __str__(self); return str(self.name) class Data(models.Model): who = models.ForeignKey(Who) And I use the form described here: forms.py from django_select2.forms import ModelSelect2Widget ... class CreateDataForm(ModelForm): class Meta: model = Data fields = ('who',) widgets = {'who': ModelSelect2Widget( queryset=Who.objects.all().distinct('name'), search_fields=['name_icontains'] )} Does anyone know how I could remove these duplicates? -
Why i am getting below error during installation of Django==2.0?
I have already install packages using pip several times. I am using Python3 and django==2.0. But today when i tried to install django again it throw below error. Please help me someone. PermissionError: [Errno 13] Permission denied: '/home/manas/.local/lib/python3.6 I tried below things sudo apt install python3-pip sudo apt-get install python-django -
Django Azure AD Integration
I'm currently integrating SSO using Azure AD for a Django Project. I'm currently using the package: https://github.com/leibowitz/django-azure-ad-auth . I have followed the docs to setup the Azure AD Authentication . On entering the application url, it takes me to the microsoft login page and after entering the credentials it's redirected to the application. But on redirection to the application after the Azure Auth, the code checks in the session for 'nonce' & 'state' variables , which are strangely returned as None and hence the application redirects to the failure url. -
How to send dynamic ID info from django class-based view to formset
I have a class-based view that renders a formset based on the project selected. Each project has a unique project_id. I get a 404 error caused by Line 14(below) in views.py if don't hard-code the project_id (ie '4') to replace 'None'.Also,the formset doesn't load if i don't hard-code the project_id in Line 4 under forms.py. Since the project_id needs to be passed automatically,how can i get it updated and passed into the formset? Thanks. I tried this: views.py class ReqView(CreateView): template_name = "req_view.html" model = ProjectBudgetReq form_class = ReqForm def get_form_kwargs(self,*args, **kwargs): form_kwargs = super(ReqView, self).get_form_kwargs(*args, **kwargs) form_kwargs['project_id'] = self.kwargs.get('project_id') print("get_form_kwargs:",form_kwargs) return form_kwargs def get_context_data(self,**kwargs): project_id = kwargs.pop('project_id',None)#Line 14 404 Error project = get_object_or_404(ProjectDetails,id=project_id) formset = ReqFormSet(instance=project) context = super(ReqView, self).get_context_data(**kwargs) context['project'] = project context['formset'] = formset return context def get_context_kwargs(self,**kwargs): context_kwargs = super(ReqView,self).get_context_kwargs(*args,**kwargs) context_kwargs['project_id'] = self.kwargs.get('project_id') return context_kwargs forms.py class CreateReqForm(forms.ModelForm): def __init__(self,*args,**kwargs): project_id = kwargs.pop('project_id',None) #Line 4 Formset not rendered super(CreateReqForm,self).__init__(*args,**kwargs) self.fields['proj_name'].queryset = ProjDesc.objects.filter(id=project_id) self.fields['budget_desc'].queryset = ProjBudget.objects.filter(proj_name_id=project_id) class Meta: model = ProjBudgetReq fields = '__all__' BudgetReqFormSet = inlineformset_factory(ProjDesc, ProjBudgetReq, form=CreateReqForm, fields='__all__',extra=2) Issues: views.py #Line 14: 404 Error since it returns 'None' forms.py #Line 4: Formset does not render, since it's 'None' -
Using Python, I want to check the data that is Type_Of_Wallet is already exists in my MySQL database table or not?
I am new to Django where I designed an application where I created a form in templates and used a database that is in localhost/PHPMyAdmin. Now when the user enters the data in given fields and presses the submit button, it should check in the database whether the given data is present in the database or not. But my code is not working. `views.py import mysql.connector from django.http import HttpResponse from django.template import loader from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): if request.method == 'POST': Type_Of_Wallet = request.POST.get('Type_Of_Wallet') BLE_MAC_ID = request.POST.get('BLE_MAC_ID') BAR_CODE = request.POST.get('BAR_CODE') Version = request.POST.get('Version') context = { 'Type_Of_Wallet': Type_Of_Wallet, 'BLE_MAC_ID': BLE_MAC_ID, 'BAR_CODE': BAR_CODE, 'Version': Version, } template = loader.get_template('valid_form/showdata.html') return HttpResponse(template.render(context, request)) else: template = loader.get_template('valid_form/index.html') return HttpResponse(template.render()) mydb=mysql.connector.connect( host = 'localhost', user = 'rajat', passwd = 'rajat', database = 'MyForum' ) mycursor=mydb.cursor() print('Enter Type_Of_Wallet:') Type_Of_Wallet=Input(context) CheckType_Of_Wallet=mycursor.execute( 'SELECT Type_Of_Wallet FROM form_simpleform WHERE Type_Of_Wallet=%(Type_Of_Wallet)s', {'Type_Of_Wallet':Type_Of_Wallet}) if CheckType_Of_Wallet !=0: print('Type_Of_Wallet does not exit') else: print('Its Available') ` index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Validation</title> </head> <body> <h2>Validation</h2> <form method="post" action="/getdata/"> <table> <tr> <td>Enter Wallet Type:</td> <td><input type="text" name="Type_Of_Wallet"/></td> </tr> <tr> <td>Enter your BLE_MAC_ID:</td> <td><input type="varchar" name="BLE_MAC_ID"/></td> </tr> <tr> <td>Enter your Bar Code:</td> <td><input type="varchar" name="BAR_CODE"/></td> </tr> <tr> … -
Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document
I am using preview-generator to make a pdf from docx file in Django. The code is working properly in my local machine but the same deployment is not working on the server which is ubuntu 18.04. I am having Unsupported mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document error. I have researched about it and found libre office needs to be installed in the server and its already present on my server. can you please suggest what I need to do or how I can define path of libre office. I am using Django and once I use the shell the file generated properly but in the the web its not working. This is the error on terminal. gunicorn[29453]: Builder is missing a dependency: this builder requires inkscape to be available gunicorn[29453]: Builder is missing a dependency: this builder requires convert to be available Builder is missing a dependency: this builder requires qpdf to be available Builder is missing a dependency: this builder Builder is missing a dependency: this builder requires libreoffice to be available -
How to convert this raw query to Django ORM query set
task_data_calldetail.objects.raw('SELECT id from `task_router_calldetail` where direction = "inbound" AND YEARWEEK(`time_stamp`, 1) = YEARWEEK( "' + today_date + '" - INTERVAL 1 WEEK, 1)') -
Slug generator don't generate slug for tablecontent
I don't know why the slug generator does not generate a slug for the items in my table. It works perfectly if i save the data with the .save() command. But it does not work with a pipeline wich does not use django related commands. I use a Postgresql database Model: class WhiskyContent(models.Model): products = models.CharField(max_length=250) price = models.FloatField(default=20) date = models.CharField(max_length=250) picture = models.CharField(max_length=250) site = models.CharField(max_length=250) product_link = models.CharField(max_length=250) shipping = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, blank=True, null=True) def get_absolute_url(self): return "/products/{slug}/".format(slug=self.slug) def __str__(self): return self.products objects = models.Manager def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=WhiskyContent) Pipeline into database: import psycopg2 import sys import logging class Frankbrauer360Pipeline(object): def __init__(self): self.create_connection() def create_connection(self,): hostname = 'localhost' username = 'postgres' password = 'Whisky#123!' database = 'Items' x = 1 try: if (x == 1): self.connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database) except psycopg2.DatabaseError as e: logging.error(e) sys.exit() finally: logging.info('Connection opened successfully.') def process_item(self, item, spider): cursor = self.connection.cursor() cursor.execute(''' insert into homepage_whiskycontent(products, price, picture, site, product_link, shipping, date) values (%s, %s, %s, %s, %s, %s, %s); ''', [ item['products'], item['price'], item['picture'], item['site'], item['product_link'], item['shipping'], item['date'], # item["slug"], ]) self.connection.commit() return item def close_spider(self, spider): self.connection.close() … -
Average duplicates from specific columns in QuerySet in Django
I have a Django Model I am using that looks like this: class FinancialAid(models.Model): RECEIVED_EVERY = (("J", "Jours"), ("S", "Semaines"), ("M", "Mois")) ID = models.AutoField(primary_key=True) Name = models.CharField(max_length=100, null=True, blank=True) Value = models.IntegerField(null=True, blank=True, default=-1) ReceivedEvery = models.CharField(max_length=15, null=True, blank=True, choices=RECEIVED_EVERY) Exchange = models.ForeignKey('Exchange', on_delete=models.CASCADE) I am able to access the information I want but I have an issue in that I often have duplicates within my QuerySet over the Name and ReceivedEvery columns but not always on the Value and never on the Exchange. Say I have the following QuerySet expanded out: financial_aid_qs = [ (ID=1, Name="Aid1", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=1)), (ID=2, Name="Aid2", Value=200, ReceivedEvery="S", Exchange=Exchange.objects.get(pk=2)), (ID=3, Name="Aid1", Value=150, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=3)), (ID=4, Name="Aid3", Value=100, ReceivedEvery="M", Exchange=Exchange.objects.get(pk=4)) ] As you can see, I have the same Name and ReceivedEvery for indexes 1 and 3. What I would like to do is get a QuerySet (or ValuesQuerySet although I seem to recall this was removed) that will contain all the different FinancialAid objects in terms of Name and average out the Value of FinancialAid objects that have the same Name. Ideally it would take into account the fact that ReceivedEvery can differ even though the Name is the same (This is all … -
Making generated emails 'outlook friendly'
I'm using Summernote as a WYSIWYG editor for users to create emails and send them within a django application. As it stands it works perfectly well in most clients which handle HTML in any normal way, however when the mail is sent to outlook it goes awry. Essentially Summernote is using style="float: x width: x" which outlook is simply ignoring, then rendering the image that should be floated right or left wherever it has been placed and at full size. Does anyone know of a package that can parse the generated summernote HTML and make it Outlook friendly before I go ahead and start writing up a whole lot of string replacements in the generated HTML? -
How to import the data from a data dump (SqLite3) into django?
I have a data dump file(.sql) containing certain data, I would like to import it to my database(currently Sqlite3 but thinking about changing to MySQL) in order to use it in my test website. Also, I need to know if it's possible to add the models too automatically, I presume it needs to be added manually, but any how, if there is any way to solve it, please suggest it. -
Search Marker Leaflet Map
I am working on an application with Django. There in this application, I am first using Django to create a database with points and extract a JSON file (It is called "markers.json"). Then, using this JSON file, I am creating markers on a map with Leaflet. When I finished entering all the points to the database they will be around 5000 thousand. So, I decided that it is a good idea to be able to search this markers with an input tag and a search button. I enter the "site_name" as input and when I click the "search" button the related marker should popup. However, always the same marker pops up and I don't know where I am doing wrong. Could you please help me on that? HTML PART <input type="text" id="mast_find" name="mastName" placeholder="Search or masts..."> <button type="submit" id="mast_button">Search</button> JAVASCRIPT PART var streets = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: ['a', 'b', 'c'] }), esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' }), topo = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: 'Map data: &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: … -
Annotating average and count of latest instances created by one author
So, I've got that piece of code: def generate_annotated_applications(queryset): return queryset.annotate( avg_rating=Avg( 'application_ratings__rate', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ), ).annotate( num_ratings=Count( 'application_ratings', distinct=True, filter=Q(application_ratings__job_process_step__job_process__job=F('job')), ) In general it works well, but the problem is that avg_rating is counted from every existing application_ratings. What I need to achieve is to count average taking only latest ratings with unique author. There are many instances of application_rating with different rate and author. Same thing is with num_ratings - I need to count number of latest ratings with unique author field. -
how to add multiple dict inside a list in python 3 with same key?
how to add multiple dict in python which is inside a list something like in this i need to add the amount from same person so where email id is same i want to add the amount. how can we do this i tried merging dic but i am getting duplicate responce. { "payment_type_details": [ { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 200000.0 }, { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 10049.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 128388.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 100250.85 }, ] } -
Django - Heavy database usage
Let's say you are building a SAAS application system in which every user will use the database heavily, for example, a hospital management system. Should you have separate databases for each user? And how do you implement this in Django? -
Object of type 'bytes' is not JSON serializable while calling an api
I'm trying to save a form which involves an API call but its throwing me an error that Object of type 'bytes' is not JSON serializable. when I call data=json.dump(dump) it throws the following error def getAttributes(self, jsonObj=False): attributes = vars(self) data = {var: value for var, value in attributes.items() if not var.startswith('_')} print(data, "data") if jsonObj: import json data = json.dumps(data) return data p.s.: In print data statement it is returning me a dict. -
Python: Passing an object instance from one function to another?
I'm having trouble with passing a value from one script to another, trying to take it a step at a time but the big picture would be to print the value obj1.get_predval to my Django view and wait for the users' input. active_learner.obj1.get_predval in my beta.py script doesn't work, it just prints out the initial value which makes sense because it's not running the main.py but I'm not sure how I'd pass the value of obj1.set_predval(machine_prediction) from main.py. It properly outputs the obj1.get_predval in the main.py script. I'm assuming I have a fundamental misunderstanding, for now, all I'm trying to return is the value of obj1.get_predval in function beta.py, when it gets to the line return value and wait for user input then continue. main.py script below obj1 = MachinePred() def main(): model = load_model('model_new.h5') DATAFILE = "c_user_model_data100000.csv" dataset = loadtxt(DATAFILE, delimiter=",") X_pool, Y = dataset[:, 0:5], dataset[:, 5:] sc_x, sc_y = StandardScaler(), StandardScaler() X_pool, Y = sc_x.fit_transform(X_pool), sc_y.fit_transform(Y) learner = ActiveLearner( estimator = model, query_strategy = uncertainty_sampling ) for i in range(3): query_idx, query_inst = learner.query(X_pool) print("The machine queried:\n{}\nat index {}".format( sc_x.inverse_transform(query_inst), query_idx ) ) machine_prediction = learner.predict(X_pool[query_idx]) obj1.set_predval(machine_prediction) print("predvalue:", (obj1.get_predval())) ratings = [] cc_factor = ["delay", "speed", "missing_words", … -
using django permissions.IsAuthenticatedOrReadOnly with token authentication
I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am doinf a get request in the view my code is here @api_view(['GET']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def all_Search(request): print(request.headers) src = request.GET.get('q') my settings for rest framework is REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } is there a way to work around this? will appreciate any help, thanks -
How to suppress warning message in django unit test
I'm trying to write some unit test cases for django (Restful API backend), While executing, I'm seeing below (403 Forbidden), which is expected, since the test is to hit a 403 endpoint. Is there a way to suppress that. I have already tried python -W error but no luck. (venv) python manage.py test System check identified no issues (0 silenced). [16/Nov/2019 11:15:26] WARNING [http://log.py:228 ] Forbidden: /api/test_enter ------------------------------------------------------------------------------ Ran 1 test in 0.021s OK How to suppress warning message in #python #django #unittest. Any thoughts would be very very helpful. Thanks. a fellow developer. :) -
Create session but has error 'Confirm form submission'
so i try to make a login function with session so if people logout , they cannot back to the page before but everytime i try to back (that has session or not) it always give me an error Confirm Form Resubmission This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. i dont know wheres the problem , but here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) #page when you success login def index_view(request): if request.session.has_key('username'): username = request.session['username'] return render(request,'index.html',{"username":username}) else: return redirect('/') … -
Getting validation error field can not be null, even if null=True in model
I've a foreign key in my model and this field can be null. status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True, blank=True, related_name="status") When i send a request with this field as null i get validation error saying [ { "status": [ "This field may not be null." ] } ] Even though I have set null=True I'm not sure why it's throwing me that validation error? Can anyone please help me with this. -
How to create a validation check that ensures the right-formatted directory path is stored and if it contains a file extension in Django?
I have a template that allows a user to store a pathname of a directory in my model (the directory should be available/exist in the server for a website or seen in a local machine). Before saving the path to the model, I need to ensure whether if the right format for the directory is being saved. Example: var/www/html/media/product or C:\Users\Danny\Desktop\folder. There shouldn't be any irregular strings, expressions or invalid format seen in the path like var/www/html/media/product\pic/... Moreover, I want to stop users if they want to save a specific directory path that contains a file extension. Example: var/www/html/media/product/file.<'file extension'> ('file.png', top.txt', 'random.jpg', etc...) How can this be done in my views.py code? Currently, this is what I did so far: views.py: def dashboard(request): if request.method == 'POST': form = PathForm(request.POST) if form.is_valid(): path = form.cleaned_data['path'] #CharField that stores the path name in model from form. #Two checks required. Need to see if it is a valid directory path format or if the path contains a general path directory. Not specific files (like images, text, csv file) should be seen in the path. #if file path contains a file extension at end. This is tedious since I need include all …