Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Official celery project for django is not working
I am using the official celery project for django, but it is not working on my machine. I have installed all the necessary modules, and am using the example given in the link: Example Django project using Celery. I have already searched for the same error and used some solutions, but no solution fixed my problem. When I use the command: celery -A proj worker -l INFO, I get this response: --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2022-05-16 14:19:39 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: proj:0x230fa67a6a0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . demoapp.tasks.add . demoapp.tasks.count_widgets . demoapp.tasks.mul . demoapp.tasks.rename_widget . demoapp.tasks.xsum . proj.celery.debug_task [2022-05-16 14:19:40,464: INFO/SpawnPoolWorker-4] child process 7240 calling self.run() [2022-05-16 14:19:40,481: INFO/SpawnPoolWorker-3] child process 6960 calling self.run() [2022-05-16 14:19:40,493: INFO/SpawnPoolWorker-2] child process 10964 calling self.run() [2022-05-16 14:19:40,516: INFO/SpawnPoolWorker-1] child process 6272 calling self.run() [2022-05-16 14:19:41,978: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061]``` As I said I am using … -
What design pattern are class-based views in Django?
There are usually special attributes defined in class-based views, I call them special because they can be configured from multiple places: as_view(), setting these attributes on derived classes, setting these attributes on instances of the class-based views. Is it some kind of design pattern? If so what pattern? Also, a class-based view is instantiated on every request. It is really useful because one can encapsulate a lot of response-generating logic in mixins, and the final view class can be very neat and clean with just a bunch of inherited classes and the special attributes set. Is it als o some kind of design pattern? If so what pattern? I suspect that this is the Command pattern. -
Transfer a django project to another machine
This is a beginner question, but I haven't found the answer. I'd like to transfer my django project from virtual machine with Ubuntu 18.04 to another virtual machine with Ubuntu 18.04. This is the example directory structure pd_videowebapp/ ├── db.sqlite3 ├── env │ ├── bin │ ├── lib │ └── pyvenv.cfg ├── manage.py ├── media │ ├── images │ └── video ├── mysite │ ├── core │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── templates │ ├── urls.py │ └── wsgi.py ├── Pipfile ├── requirements.txt └── static ├── admin ├── style2.css └── style3.css In env directory there is a Python virtual environment. Before I transfer it I would run $ pip freeze > requirements.txt Then I would zip all the directory structure except for db.sqlite3 and media directory. Then unzip it on another VM. Then copy the db.sqlite3 and media directory to the right place. Then create a virtual environment on another VM. Then run $ pip install -r requirements.txt Or should I rather copy the whole project with env directory in the beginning? What is better? Did I omit something? Or is there a better approach? -
Creating Trigger using javascript and django
I want to make a trigger using javascript. This is my trigger in js : setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'update_state' %}", success: function(response){ console.log('Updated'); }, error: function(response){ console.log('An error occured') } }); },60000); And this is my view : def update_state(request): requests = Request.objects.all() for req in requests: d = Request.objects.filter(id=req.id) dd = d.get() if dd.delay == timedelta(minutes=0): pass else: d_del = dd.delay - timedelta(minutes=1) d.update(delay=d_del) return HttpResponse('ok') In my db sometimes the delay decrease but some time don't decrease. I don't know where is the problem. -
DJANGO_API_SECRET_KEY is missing
I am trying to launch github project in docker, but when I'm using command python manage.py migrate I get an error DJANGO_API_SECRET_KEY is missing. It is said that I need to copy .env.example file into .env.development file but there is no such file. The error I'm getting is from my settings.py file: val = os.environ.get(name) assert val, f"{name} is missing" return val # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = required_env("DJANGO_API_SECRET_KEY") I am trying to run this project on my Windows system. -
Update django list page total items based on query done
Django admin calculates total number of items before it query for items. Due to realtime changes, count is less than the actual number of items. Is it possible to update total count after query is completed -
Large media uploads to azure blob service for authenticated users
I am new to azure and attempting to create a REST API that uploads large media files (4gb) to azure blob service. I'm using Django to create the API. The API should only allow authenticated users to upload files. I would like the upload to be handled by the front end because I am running my Django instance in a container on Azure and would like to reduce memory / compute load on it to reduce cost. I was wondering if I could dynamically generate a time-sensitive token that is sent to the front end to allow users to upload directly to my Azure blob instance. Any suggestions on how I can achieve this in a production-safe manner? Thanks! -
Converting data with a function before it's added to the database with Django and Python
File structure of the project: - Site - common - __init__.py - utils.py - App Inside utils.py, we have a function that converts any unit of measurement input by the user in a form to a unified unit - i.e lbs -> kg, ounces -> kg. How do we pass the data a user inputs from the |form -> through the function -> to the database| in a way that it is converted before being added to the database? For example: User enters 1000 grams as the weight of a product and submits the data. The function changes 1000 grams into kilograms. The weight is entered into the database as 1 kilogram. The function is already written, we are just unsure how to "plug" this into our code to achieve functionality. -
Django Export Excel Save File In Server (Celery + RabbitMQ)
I have a Django view that exports an Excel File and prompts a Download Dialog when the file is ready. I am installing Celery and RabbitMQ to make this task a background task. This means that the excel file will not be prompted to be downloaded, but I would like to save it somewhere in the machine, so the user can later go to a page and download it. Example: Go to List page -> Click on Export -> Get a message: "Your file will be ready soon" -> User goes to "Downloads" Page -> Finds the file in a list -> Clicks to download. So the process for me now is to create a new model: class Export(models.Model): dossier = models.ForeignKey( Dossier, related_name="Export", on_delete=models.CASCADE, default=None, editable=False, ) timestamp = models.DateTimeField(auto_now_add=True, editable=False) file = models.FileField( upload_to=get_rapport_filename, verbose_name="Fichiers Excel" ) def __str__(self): return "%s - %s" % (self.dossier, self.timestamp) class Meta: verbose_name = "Excel Report" verbose_name_plural = "Excel Reports" And this is the code I have that generates the Excel file: @shared_task def export_dossiers_factures(request): dossier_queryset = Dossier.objects.filter(status_admin="Facturé") today = str(date.today()) response = HttpResponse( content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = ( "attachment; filename=" + today + "-dossiers_factures.xlsx" ) workbook = Workbook() # Get active … -
My edit profile page is not displayed due to migrations
I have a doubt. It happens that I am making a page called "Edit Profile", to that page I added more fields than those that are pre-established for the edit profile. Everything was fine, I got this error: ValueError: The field Users.Profile.user was declared with a lazy reference to 'Usuarios.customuser', but app 'Usuarios' doesn't provide model 'customuser'. The field admin.LogEntry.user was declared with a lazy reference to 'Usuarios.customuser', but app 'Usuarios' doesn't provide model 'customuser' following various stack recommendations, just delete several files from my app folder and that's it, I was able to do my migrations but now the following error appears when I reload the page: django.db.utils.ProgrammingError: relation "Usuarios_customuser" does not exist LINE 1: ...omuser"."state", "Usuarios_customuser"."zip" FROM "Usuarios_... As if it had not been able to do the migrations or did not detect them. But that error seems strange to me because when placing makemigrations and migrate, no error appears, only when I reload the page html <span class="d-none d-xl-inline-block ms-1 fw-medium font-size-15">{{user.username}}</span> <i class="uil-angle-down d-none d-xl-inline-block font-size-15"></i> </button> <div class="dropdown-menu dropdown-menu-end"> <!-- item--> {% if user.is_authenticated %} <a class="dropdown-item" href="{% url 'profile' %}"><i class="uil uil-sign-out-alt font-size-18 align-middle me-1 text-muted"></i> <span class="align-middle">View Profile</span></a> <a class="dropdown-item" href="{% url 'logout' … -
How to replace special text with other special text - Python
How do I change my special string to a different value if value appears? My variables special_url = http://127.0.0.1:8000/ text = '...' special_symbol = {{URL}} Well i have text like this: It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- {{URL}} Or-less normal distribution of letters, as opposed to using 'Content here, content here', I need change above text to this when the value {{URL}} is in text It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- http://127.0.0.1:8000/ Or-less normal distribution of letters, as opposed to using 'Content here, content here', I try this, bot now work: massage = re.sub('{{URL}}', obj.special_url, text) -
"This field is required." Django rest framework
I've looked every answer in stack I cant find an answer. I 've created an API with django rest framework with some measurements . Im trying to post a TreeSensor measurement through postman or django API .Weather measurements works just fine but on my TreeSensor i get the following error even though they are identical besides the fields. { "soil_moisture_depth_1": [ "This field is required." ], "soil_moisture_depth_2": [ "This field is required." ] } Serializers : class TreeSensorMeasurementSerializer(serializers.ModelSerializer): class Meta: model = TreeSensorMeasurement fields = ["sensor", "datetime", "soil_moisture_depth_1","soil_moisture_depth_2","soil_moisture_depth_1_filtered","soil_moisture_depth_2_filtered", "soil_temperature"] class WeatherStationMeasurementSerializer(serializers.ModelSerializer): class Meta: model = WeatherStationMeasurement fields = ["sensor", "datetime", "wind_speed", "current_rain", "wind_direction", "solar_radiation", "air_temperature", "air_humidity", "air_pressure", "luminosity", "battery", "dew_point"] API : ########### TreeSensorMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'soi_moisture_depth_1' : request.data.get('soil_moisture_depth_1'), 'soi_moisture_depth_2' : request.data.get('soil_moisture_depth_2'), 'soi_moisture_depth_1_filtered' : request.data.get('soil_moisture_depth_1_filtered'), 'soi_moisture_depth_2_filtered' : request.data.get('soil_moisture_depth_2_filtered'), 'soil_temperature' : request.data.get('soil_temperature'), } serializer = TreeSensorMeasurementSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ########### WeatherStationMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'wind_speed' : request.data.get('wind_speed'), 'current_rain' : request.data.get('current_rain'), 'wind_direction' : request.data.get('wind_direction'), 'solar_radiation' : request.data.get('solar_radiation'), 'air_temperature' : request.data.get('air_temperature'), 'air_humidity' : request.data.get('air_humidity'), 'air_pressure' : request.data.get('air_pressure'), 'luminosity' : request.data.get('luminosity'), … -
How to get Image From Media Folder in Django
I uplaoded An image from fontend to media folder in django. How can I get that image inside my view.py file. so that I can process that image. image is saved in /media/images folder INPUT_IMAGE = '../media/images/inp7.jpg' but when I try to get image using this url its showing file not found. How can I fix it. -
Problem with webpack of vue3 cli v5 in order to combine it with django 4
For quite some time I'm trying to combine Django with Vue. What I'm trying to do is a simple template that uses the newer versions of these distributions. Quick environment from conda for Django and Vue3 cli project using all the juicy stuff like typescript, css processing, u testing, router, vuex and class-style ect. Everything I find in the internet is using older versions, I don't want that. I need help setting the webpack or some resources that could be helpful. -
How to get elements from callback url for generating an access token for OAuth1 using Django from behind a firewall?
I have a scenario where I'm building an app that is hosted on an ubuntu server. Currently I have all inbound traffic to the server blocked with only outbound being allowed. The only way to access the React/Django app on the server is either thru VPN or having an IP whitelisted. When doing the OAuth1 process (to connect with a data provider), I'm struggling to figure out how to keep my app closed from the public internet but still complete the OAuth 1 process for the end user. Given that this app's purpose is to aggregate user data (from user's who've granted permission), it's not practical for me to whitelist the IP address of every single end user. Currently, I'm considering making a form outside of my app for users to register with and then just having my app hourly check that form for new users so that it can then start the OAuth1 process and send the end user the authorization URL needed to grant permission to the data provider. At this point though, I have it where once the user signs up with their data provider, the callback URL redirects the user back to the Django app so … -
Nginx server not using project config
I am trying to create a configuration for the Nginx web server for my Django project. I would like to store the configuration of the web server in my project files. As I am using MacOS, the /sites-enabled directory was not present in the /usr/local/etc/nginx directory, so I've created it. In the /usr/local/etc/nginx/sites-enabled directory I have made a symbolic link to the project which seems to work. In the nginx.config file in the /usr/local/etc/nginx directory I have updated the file to make it see the sites-enabled directory: http { include /usr/local/etc/nginx/sites-enabled/*; The nginx -t command lists the following if I input incorrect data in my project nginx.conf file: nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful and correctly recognizes changes to it if I make some intentional errors: nginx: [emerg] invalid parameter "server_name" in /usr/local/etc/nginx/sites-enabled/linkem-all:6 nginx: configuration file /usr/local/etc/nginx/nginx.conf test failed The problem is that despite my changing the port to listen to in the nginx.conf file located in my project: server { # port nginx will be listening to listen 8000; # server ip address server_name 127.0.0.1.; # logs stored within the project access_log path/to/nginx-acces.log; error_log /path/to/nginx-error.log; # pass traffic from nginx … -
Django Server Error: port is already in use, docker
When working with Docker and Django setup Initially sometime we will getting this error port 5432 already in use or TCP/IP not able to make connection. How to resolve this issue please find below. -
In my Django project I have two similar url
I have a question with my sites urls. When someone want to go mysite.com I redirect them to mysite.com/register. url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), Also I have another url that allows to write somethings after the part of register. For example when someone goes to this website mysite.com/register/kh-54-m2-fc it allows to go that: url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), But when I use these urls together my guaform view doesn't work. And it goes to customer_form2.html. When someone goes this site: mysite.com/register/ anything I want them go to customer_form.html. How can I seperate these urls? urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'), url(r'^register/',views.guaform2,name='custform2'), url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'), ] views.py from django.shortcuts import render,HttpResponse from olvapp.models import Customer from olvapp.forms import CustomerForm,CustomerForm2 from django.conf import settings from django.http import HttpResponseRedirect from django.urls import reverse from olvapp import forms def guaform(request,pk): theurl = request.get_full_path() orderid = theurl[10:] form = CustomerForm(initial={'order_id':orderid}) if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form.html',{'form':form}) def guaform2(request): form = CustomerForm2() if request.method == "POST": form = CustomerForm2(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('thank')) else: HttpResponse("Error from invalid") return render(request,'customer_form2.html',{'form':form}) -
Django DecimalRangeField form validation will only accept whole numbers
All of my DecimalRangeField fields work as expected when changing values in admin but my form won't accept non-whole numbers: Interestingly, if I set the lower default value as a non-whole number, the validation tries to force any whole number added to the lowest default. For example, if I define a field like this in models.py: my_field= DecimalRangeField( blank=True, default=(0.05, 5), validators=[RangeMinValueValidator(0.05), RangeMaxValueValidator(5)], ) I get the following warning: Maybe I am missing something in the field definition or there is something I don't understand about how Django converts the input into a decimal but I've not been able to find anything online about this. Any help would be greatly appreciated :) -
pytest + django giving me a database error when fixture scope is 'module'
I have the following inside conftest.py @pytest.mark.django_db @pytest.fixture(scope='module') def thing(): print('sleeping') # represents a very expensive function that i want to only ever once once per module Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Thing.objects.create(thing='hello') Inside tests.py @pytest.mark.django_db def test_thing(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db def test_thing2(thing): assert models.Thing.objects.count() > 1 @pytest.mark.django_db @pytest.mark.usefixtures('thing') def test_thing3(): assert models.Thing.objects.count() > 1 All three tests throw the same error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I've tried using scope='session' / scope='class' / scope='package' / scope='module' -- the only one that works is `scope='function' which defeats the purpose of what I'm trying to accomplish. I want to be able to create all these items ONCE per module, not once per test. Note: I ran into this issue with a large code base and created a new django project with a single app to test and see if the problem was the existing test code, and it failed on a standalone test also. Not that it matters, but the models.py class Thing(models.Model): thing = models.CharField(max_length=100) -
Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$']
It is basically an e-Commerce website. Everything working perfectly but When I log out then occurs the below error. What will be the relevant solution? NoReverseMatch at / Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'profile_info_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile_info_update/(?P<pk>[0-9]+)$'] Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 16 May 2022 15:31:17 +0000 template: <a href="{% url 'profile_info_update' user.pk %}" class="edit_btn btn"> edit </a> urls.py: path('profile_info_update/<int:pk>', views.profile_info_update.as_view(), name="profile_info_update") views: class profile_info_update(UpdateView): model = User from_class = change_profile_info fields = 'first_name','last_name','email' template_name = '33_change_profile_info.html' success_url =("/") forms.py: class change_profile_info(forms.ModelForm): first_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) last_name = forms.CharField(widget=forms.FileInput(attrs={'class':"form-control"})) email = forms.EmailField(widget=forms.FileInput(attrs={'class':"form-control"})) class Meta: model = User fields = ('first_name','last_name','email',) -
Django update_or_create()
I'm trying to use Django update_or_create() but I could not pass the pk (obj_key) to defaults. The idea is filter by user_id and wallet_id and update if exist or create if not. class ModelSelectedWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.name = models.ForeignKey(ModelWallet, default=1, on_delete=models.CASCADE) created = models.DateField(verbose_name='Created', auto_now_add=True) modified = models.DateField(verbose_name='Modified', auto_now=True) created_by = models.ForeignKey('auth.User', related_name='selected_wallet_created_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) modified_by = models.ForeignKey('auth.User', related_name='selected_wallet_modified_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) def select_wallet(request): if request.method == "POST": wallet_id = request.POST['wallet_id'] user = get_current_user() user_id = user.id db = ModelSelectedWallet obj_key = db.objects.filter(user_id__exact=user_id, wallet_id__exact=wallet_id).values('id')[0]['id'] defaults = {'id': obj_key} try: obj = db.objects.get(user_id=user_id, wallet_id=wallet_id) for key, value in defaults.items(): setattr(obj, key, value) obj.save() except db.DoesNotExist: new_values = { 'created': datetime.datetime.now().strftime ("%Y-%m-%d"), 'created_by_id': user_id, 'modified_by_id': user_id, 'wallet_id': wallet_id, 'user_id': user_id } new_values.update(defaults) obj = db(**new_values) obj.save() -
Django view. Upload/modify one CSV/Download modified csv
i'm trying to create and API for some validation: I want to have a option to upload one CSV. I want to pass that CSV through some validations, to modify the original CSV (to add 2 new columns) I want to have a posibility to download the modified CSV (with my 2 new columns) I implemented the first part, i created the validation, but after i download, i've got the same output (file wasn't modified) Could anyone help me with this part pls? This is my code for my view: def upload(request): context = {} if request.method == 'POST': promo2 = request.FILES['document'] if request.method == 'GET': promo2 = promo2[~promo2['COMP_ARTICLE_PROMO_TYPE'].isna()] for index, row in promo2.iterrows(): promo2 = pd.read_csv(promo2, sep=';') if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if 0.95 < round(row['COMP_ART_PRICE'] * 0.80, 2) / row['COMP_ARTICLE_PROMO_PRICE_PER_UNIT'] < 1.05: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PRICE_PER_UNIT'] = 'WRONG' if (row['COMP_ARTICLE_PROMO_NAME'] == '-20%') or (row['COMP_ARTICLE_PROMO_NAME'] == '20.0% korting'): if row['COMP_ARTICLE_PROMO_PERCENT'] == 20: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'GOOD' else: promo2.loc[index, 'VALIDATE_ARTICLE_PROMO_PERCENT'] = 'WRONG' #fs = FileSystemStorage() #name = fs.save(promo2.name, promo2) #context['url'] = fs.url(name) #promo2.to_excel(response, engine='xlsxwriter', index=False) fs = FileSystemStorage() name = fs.save(promo2.name, promo2) context['url'] = fs.url(name) return render(request, 'upload.html', context) Here is my front … -
Django-rest-framework - fetching data from another server's DB
I made with Django REST Framework an API that i use for my project which is a Flutter app. *BUT, i want to add some data from another Server's database, can i do it in Django REST Framework, and then include those in my API ? -
How to differentiate access to data at the database server level?
In DB i have three roles: guest, client and admin. In my django project, there are three connections under these roles DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'guest', 'PASSWORD': 'guest', 'HOST': 'localhost', 'PORT': 5432, }, 'admin': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': 5432, }, 'customer': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'customer', 'PASSWORD': 'customer', 'HOST': 'localhost', 'PORT': 5432, } } How and where can I change the connection to the database depending on whether the user is authenticated or not?