Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we represent a pandas.series value on Django?
I have the following code, where I am binning a Pandas dataframe into given number of bins: def contibin(data, target, bins=10): #Empty Dataframe newDF,woeDF = pd.DataFrame(), pd.DataFrame() #Extract Column Names cols = data.columns for ivars in cols[~cols.isin([target])]: if (data[ivars].dtype.kind in 'bifc') and (len(np.unique(data[ivars]))>10): binned_x = pd.qcut(data[ivars], bins, duplicates='drop') d0 = pd.DataFrame({'x': binned_x, 'y': data[target]}) #print(d0) else: d0 = pd.DataFrame({'x': data[ivars], 'y': data[target]}) d = d0.groupby("x", as_index=False).agg({"y": ["count", "sum"]}) d.columns = ['Range', 'Total', 'No. of Good'] d['No. of Bad'] = d['Total'] - d['No. of Good'] d['Dist. of Good'] = np.maximum(d['No. of Good'], 0.5) / d['No. of Good'].sum() d['Dist. of Bad'] = np.maximum(d['No. of Bad'], 0.5) / d['No. of Bad'].sum() d['WoE'] = np.log(d['Dist. of Good']/d['Dist. of Bad']) d['IV'] = d['WoE'] * (d['Dist. of Good'] - d['Dist. of Bad']) #temp =pd.DataFrame({"Variable" : [ivars], "IV" : [d['IV'].sum()]}, columns = ["Variable", "IV"]) #newDF=pd.concat([newDF,temp], axis=0) woeDF=pd.concat([woeDF,d], axis=0) return woeDF The problem I am facing is when I try to integrate the code on front end using Django, I am not being able to represent woeDF['Range'] in Django the way I am able to see it normally. I tried converting the Pandas.Series to string, but it still isn't giving me what I want. To illustrate what I … -
update_or_create in import feature
I am working on import data from external source in json format data. I am getting and saving data in Person model and I would like to update models that already exists, so I am using update_or_create method but during import I am getting an error: django.db.utils.IntegrityError: UNIQUE constraint failed: managment_person.person_id. person_id has to be unique. model Person class Person(models.Model): person_id = models.PositiveIntegerField(unique=True) code = models.CharField(max_length=255) name = models.CharField(max_length=255) def __str__(self): return self.name Here is function to import data for Person model: def get_persons(self): r = requests.get('https://path_to_data_in_json') for obj in r.json()['data']: event, created = Person.objects.update_or_create(person_id=obj['id'], code=obj['code'], name=obj['name']) -
what is the best way to implement a real-time connection between react and django backend server?
I need to implement a a graph which updated on real-time and I am having a backed django application to interact with the frontend using DRF. How to implement such solutions knowing that each request should make complex quries on database? -
Django Simple History - How to return the instance of the foreign key changes when using diff_against instead of just the pk?
I am using django-simple-history, and I am using the diff_against method in django-simple-history to try to get the changes between the historical instances, so that I can display what changed. However, I realised that for foreign key changes, the django-simple-history .diff_against method would return me only the pk for the change (old and new pk). What I would want is the instance of the change, not the pk, so that I would be able to return the appropriate field for displaying. For example, within my Quotation model, there is a foreign key to CustomerInformation. Whenever a quotation instance is edited and the CustomerInformation foreign key is changed to another instance, the changes recorded within the diff_against method of the django-simple-history historical records return only the pk. However, I would want it to return the CustomerInformation instance, so that I can query out the field 'customer_name' to display. Do guide me along, and let me know if it is possible! I thought about handling the logic using the .get() method in the Django querying library, but was wondering if there is any inbuilt or easier method to get what I want to achieve. Thanks all -
Not able to create database in pgadmin
i am new to PostgresSQL and i am figuring out on how to create the database in pgadmin. I have ubuntu 20.04 running and it has postgresSQL. The snap of my pgadmin panel is here -
How to set the question that an answer will be associated with?
I an building a Q&A website for practice and I want each answer to be associated with an author and a question, I managed to associate it with the user but I can not figure out the question part. Here is the code: models.py: class Questiont(models.Model): question = models.CharField(max_length=200) description = models.TextField(null = True , blank=True) date_posted =models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.question class Answer(models.Model): content = models.TextField(null=True,blank=True) question = models.ForeignKey(Question, on_delete=models.CASCADE) author = models.ForeignKey(User,on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) views.py(where the association should take place): class CreateAnswer(LoginRequiredMixin,CreateView): model = Answer fields = ['content'] context_object_name = 'answer' success_url = reverse_lazy('Lisk home') def form_valid(self, form): form.instance.question = ????????? form.instance.author = self.request.user return super().form_valid(form) How can I specify the question that the answer is specified to ? Granted that the ID of the question being answered is in the URL of the answering page(template). The url is like this: http://127.0.0.1:8000/question/22/createanswer/ Thanks in advance. -
How to retrieve data from Django database using Dash app?
I am trying to access the database of a Django app from an outside Dash/Flask app. My folder structure looks like this right now: my_django_app |--> my_django_app |-->|--> settings.py |-->|--> ... |--> data_selection |-->|--> models.py |-->|--> ... |--> my_dash_app |-->|--> dash_app.py |-->|--> ... Now I would like to access the database of my_django_app inside my_dash_app. I saw in another question that this should work by adding os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_django_app.settings") django.setup() However for me this leads to the error No module named my_django_app. How do I need to specify the path to my django app in this case? -
Hashing a value in response data from a REST API endpoint to frontend
We are using video call/chat services from a third-party company and we create tokens and channel names to use their chat services in our platform. After our FE requested from our BE for credentials (token and channel name) endpoint responses back with token and channel name information. The third-party system does not create the tokens for specific channel name so it is quite possible to obtain one chat token and as long as you know or guess the chat channel name you can join and text freely. In order to prevent this happening, we are to hash/encrypt the channel names sent in our responses to FE so that the actual channel name won't be visible in plain text. What's the best way to do this? BE: Django FE: Vue.js Thanks -
Why we serve static and media files using webserver in production not with Django?
Every web developer and programmer said that if you are working on Django project never serve your static and media files using Django on the production environment, always use webserver like Apache or Nginx to serve these files. Actually I get so many references from the internet that how to server static and media files using Django in production but on the other hand, they said that never serve static and media content with Django because it is inefficient and probably insecure. Why Django is not best for serving static and media content in production. Why serve static and media content with webservers. -
AttributeError: 'Subject' object has no attribute 'file' when upload file in Django
i 'm trying tp upload a file in Django use ImageField. I want to hash this img before upload (using ImageHash), and save the image with the hashed file name. Below is my code, can you helo me fix this? models.py from utils import hash_image ... class: Subject(models.Model): photo = models.ImageField(upload_to=hash_image) ... utils def hash_image(instance, filename): instance.file.open() ext = os.path.splitext(filename)[1] image_hash = '' image_hash = str(imagehash.average_hash(instance.file)) + '.' + ext return image_hash Error: line 34, in hash_image instance.file.open() AttributeError: 'Subject' object has no attribute 'file' -
TRYING TO RUN MANAGE.PY FOR DJANGO SERVER
Am trying to run manage.py from my command line but the command line is showing error: OSError: [WinError 123] The filename, directory name or volume label syntax is incorrect: '<frozen importlib._boostrap>' Please help. I ran the code yesterday and it worked successfully. -
DJANGO save multiple record to database with one button press inserting values using drag and drop and AJAX
i am trying to do drag and drop and after dropping save to database in django framework. I tried using ajax. 1. First question is how to do that box after dragging won't disappear from list, but draggable list would be always the same. I have list of dishes and i am trying to make manu of the day. So maybe some advices how to do that after dragging box it won't disapper from list? 2. Second question is how to save to database... I can't understand. Every place for dropping should be one record to database with saome values. Any advice? So I need to take data from drag and drop and save some records to database with one button press. How to send data with Ajax, or it is better way to do this? Thank you very much! This is my drag and drop script {% include 'dishes/layout.html' %} {% load crispy_forms_tags %} {% load static %} <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <body> {% block content %} <h1 class="mb-1" style="font-size:20px">Jūsų kelionė <var>{{ trip_title }}</var> </h1> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); //cia riek ajax … -
Can't delete records from database with Axios React Django
I'm having trouble deleting records from the database using Axios in React (front end). I use Django REST 2.2 for my backend. The URL "http://localhost:8000/api/manager/courses/" works, I can add, update & delete courses. What am I doing wrong? Delete function Axios front end React (The url routs to the viewset seen below) const handleDelete = (item) => { if (item.id) { axios .delete(`http://localhost:8000/api/manager/courses/${item.id}/`, item, { headers: { authorization: "Token " + getUserToken(), }, }) .then((response) => refreshList()); handleCloseEdit(); return; } }; ViewSet Django backend class CourseView(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): if (self.request.user): return Course.objects.filter(manager_id=self.request.user.pk) else: return Course.objects.all() def perform_create(self, serializer): if (self.request.user.pk): serializer.save(manager_id = self.request.user) else: serializer.save() EDIT: It works if I remove get_queryset. How come it interferes with Delete? -
How to hide Django rest Framwork schema?
I use drf_yasg swagger for my Django API. I would like to know how to easily disable the schema and model. screenshot here is my code: from django.utils.decorators import method_decorator from rest_framework.decorators import api_view from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi @swagger_auto_schema(methods=['get'], operation_description="description", manual_parameters=[ openapi.Parameter('category', openapi.IN_QUERY, "category1, category2, category3", type=openapi.TYPE_STRING), openapi.Parameter('name', openapi.IN_QUERY, "full name", type=openapi.TYPE_STRING), ], responses={ 200: openapi.Response('Response', ArticlesSerializer), }, tags=['Articles']) # desactivate POST methode on swagger @swagger_auto_schema(method='POST', auto_schema=None) @api_view(['GET','POST']) def articles(request): """ List all articles. """ if request.user.is_authenticated: # ..... If i add this class UserList(APIView): swagger_schema = None i got error: AssertionError: `method` or `methods` can only be specified on @action or @api_view views -
Compare Django model field and request.user.username in HTML
I want to compare two string. One from the request.user.username, and the other is from the model's attribute (field). When I print them like {{ request.user.username }} {{ model.attributecontainsname }} I see the same two strings, like Chris Chris but if I use the {% if request.user.username == model.attributecontainsname %} They are the same! {% else %} They are NOT the same! {% endif %} it doesn't work, the HTML page says they are two different strings. Why? -
How to make django-filters works in Embedded Model Field?
For example, the models.py looks like this: class Locations(models.Model): name = models.CharField(max_length=200, null=True) fendering_position = models.CharField(max_length=1000, null=True, blank=True) STS_position = models.CharField(max_length=1000, null=True, blank=True) STS_latitude = models.FloatField(null=True, blank=True) STS_longitude = models.FloatField(null=True, blank=True) class EmergencyContacts(models.Model): Oil_Spill_Responders = models.CharField(max_length=1000, null=True, blank=True) Local_Emergency_Medical_Assistance = models.CharField(max_length=1000, null=True, blank=True) Police = models.CharField(max_length=1000, null=True, blank=True) class Equipment_Details(models.Model): Primary_Fenders = models.CharField(max_length=1000, null=True, blank=True) Secondary_Fenders = models.CharField(max_length=1000, null=True, blank=True) Fender_Moorings = models.CharField(max_length=1000, null=True, blank=True) class LocationsForm(forms.ModelForm): class Meta: model = Locations fields = [ 'name', 'fendering_position', 'STS_position', 'STS_latitude', 'STS_longitude', ] class EmergencyContactsForm(forms.ModelForm): class Meta: model = EmergencyContacts fields = [ 'Oil_Spill_Responders', 'Local_Emergency_Medical_Assistance', 'Police'] class Equipment_DetailsForm(forms.ModelForm): class Meta: model = Equipment_Details fields = [ 'Primary_Fenders', 'Secondary_Fenders', 'Fender_Moorings'] class Entry(models.Model): locations = models.EmbeddedModelField( model_container=(Locations), model_form_class=LocationsForm ) emergencycontacts = models.EmbeddedModelField( model_container=(EmergencyContacts), model_form_class=EmergencyContactsForm ) equipment_details = models.EmbeddedModelField( model_container=(Equipment_Details), model_form_class=Equipment_DetailsForm ) and now everything will store in the Entry table, so if I want to use django-filters to search, what should I do? I try: class EntryFilter(django_filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains') class Meta: model = Entry.locations fields = 'name' and this does not work, I also try: class Meta: model = Entry fields = '__all__' and this also does not work, so what should I write on the filters.py to make it can search … -
Multiple databases in Django - MSSQL
i am trying to connect to another MySQL database in django. In default I am using the default LiteSQL which is provided by Django in default settings. I believed that I successfully connected to SQL database, here in settings. So it looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'timesheet': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '......', 'NAME': 'Database.department.someview', 'USER': '....', 'PASSWORD': '.....', 'PORT': '.....', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } Know I want to select something in the new database and paste it into view and work with that, like I am using the liteSQL database. Can someone please guide me how to select form this database? Since I am using the default the select looks like Name-of-model.objects.filter(id=deletesignificantaccountid) but I do not know how I should name the model, cause I don't have it in models. So can someone help me with that? The database will be used only for read, I do not and I cannot write in it. Thanks a lot. -
Is it possible to implement multi-tenancy to Django using MySQL?
I want to ensure multi-tenancy to my django application using mySQL..couldn't find any resource on how to do so, and I am seriously new to my SQL. Please note that in my particular setup, I am deploying my django app onto a VPS running CentOS along with cPanel. I would highly appreciate, if someone provides either a clear tutorial,resource or step by step on how to achieve so. Thank you! -
Using celery + django to upload file to azure file storage
@shared_task(name="upload_file") def get_file_storage(file, id): # Upload the file to file storage azure_file_storage = AzureFileStorage() # Save the object url_var = azure_file_storage.save(name=file.name, content=file) storage_path_url = azure_file_storage.url(name=url_var) obj = ChannelCsvInfo.objects.create(storage_path=storage_path_url, channel=id) obj.save() return storage_path_url -
permissions in django for the group of users
In my wen application i mad different login for different person like for HR ,for engineer ,for owner using django user creation form , and authenticate them using Django authentication ,now everything is work very well i am able to add user from the front add but the problem is that everyone get same power and authority , i can change it from the admin penal but it will not be beneficial for my client/user I WANT ALLOW DIFFERENT KIND OF PERMISSIONS TO DIFFERENT GROUP OF USER(daynamicaliy with using django penal) show How can i do that. (i'm beginner so its request to all of you to give answer in some detail format) THANK YOU -
Cache path in Django regarding Spotipy authentication
I'm making a website where users can analyze their Spotify playlists. To retrieve the Spotify data I am using the Spotipy package. To authenticate the user I use the following code from the documentation: spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=cid, client_secret=secret, scope=scope, redirect_uri='http://localhost:7777/callback', cache_path=cache_path)) My first question is what the cache path in Django is, and my second question stemming from my lack of experience working with API is whether this is the best way to let users login with the Spotify account on the website. Thanks! -
Update data on button click with ajax in django template
On clicking next i want to change John to another user without reloading the page. Can't figure out how to get new data from my views file and pass them to the template. Included my ajax code below. My template <body> <table> <tr> <th>Id</th> <th>Name</th> <th>Age</th> <th>Status</th> </tr> <tr> {% for user in users %} <td>{{user.id}}</td> <td>user.name</td> <td>user.age</td> <td>user.status</td> {% endfor %} </tr> </table> <button type="submit" onclick="" id="next">Next</button> </body> </html> <script> $('#next').on('click', function(){ $("#id").empty(); $("#name").empty(); $("#age").empty(); $("#status").empty(); ; $.ajax( { type: 'GET', url: "/users", data:{ }, success: function(data) { ; } }) }); </script> My views.py file json_data = open('/json/users.json') data = json.load(json_data) json_data.close() context = {'users':users} -
How can we convert uploaded docx file to pdf in django
I have created a models which accepts file.I'm trying to convert the uploaded docx file to pdf and display it to the user. for conversion of docx file to pdf i'm trying to use docxtopdf module of python. But when i pass my file from request.FILES['Doc] to convert function it gives error : TypeError at /convview/ expected str, bytes or os.PathLike object, not FieldFile here i the code from views.py file: def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): pdffile=UserConvert(Doc=request.FILES['Doc']) pdffile.save() convert(pdffile.Doc) How can we change mime type of files when it is in memory? -
PasswordInput in djongo models
I use jdongo models in my django project. Does PassswordInput in djongo models exist? And how can it be replaced? -
calling main app function in templates of other app
I am trying to call index function of main app in my base.html in its child app. I have a homepage in main app's view as home main/view.py def home(request): return render(request, 'main/index.html') and in base.html of other app i am trying to call this function app/template/app/base.html <a class="navbar-brand" href="{% url 'main.home' %}">Chili Pili</a> It throws error when doing this way.