Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app in docker compose seems to be getting brute forced url requests with a docker ip
I have a cookiecutter-django based setup with docker-compose, with a mailing service from Mailjet with Anymail on a VPS on Vultr for staging. I use traefik as a reverse-proxy. I occasionally get emails from the app for 404 errors when I or my partner tries an invalid link. But since 3 days ago, I have been gettings hundreds of emails a day for 404 errors with url paths that can be considered usual defaults for many different frameworks such as /login, /Home/Login, /static/style.css, etc. That in itself would have been easy to fix, if Traefik was the container receiving the requests. No, the emails all say I'm getting the request from 172.19.0.08, whereas my project (nothing else is running in this VPS to my understanding) uses 172.20.0.X as the network. I even set up a RateLimit middleware in traefik but it was pointless since the requests never go through traefik. I am not very good at networks so I do not know how to identify what is happening here. Django logs don't show the requests either to my understanding although I don't have a very detailed django logging config set up (used default from cookiecutter with DEBUG as the level). … -
Password is not hashing while adding customuser @ django admin site
class CustomUser(AbstractUser): is_admin = models.BooleanField(default=False) objects = CustomUserManager() class CustomUserManager(BaseUserManager): def create_user(self, username, password=None, **extra_fields): if not username: raise ValueError('The username must be set') print(password) user = self.model(username=username, **extra_fields) user.set_password(password) # This hashes the password user.save(using=self._db) return user i just need to add extra field in this custom model but whenever i tried to add this user by django admin site the password is stored as plain the problem is the CustomUserManager is not being called -
Is it possible to create shopify payment app in django
I need to create a payment app for shopify with offsite payment app extension with Django. I have read the Documentation for payment app but the payment API it is written for nodeJS. Is it possible to implement the payment app in Django?. -
How to use naturalspeech2-pytorch convert text to audio
I'm developing the audio service with whisper, Ghat_GPT and naturalspeech2-pytorch. What I need to solve is to implement the naturalspeech2-pytorch python module to convert the text to audio. I'm lacked the data. Which python version Do I need to do. please help me. I tried naturalspeech2-pytorch to convert text to audio. -
What are some Alternatives to ChatGPT API
I have resorted to using stack overflow, I am looking for free API's that are similar to chatGPT's me and a team are building a Django application and are looking to integrate it with chatGPT4free until we realized that it wasnt an API, any free API's out there for that? -
Whats the purpose of the dot in this line: from . import views
I'm looking at the Django documentation, and in some point, they import views with this line: from . import views. It works, but... what's the purpose of the dot??? from . import views, the line works but i don't know why -
Why serializer data isn't displayed by foreign key in view?
I need to show user info in my post as nested json. Models: Profile # Django from django.db import models class Profile(HelperModel): """ User Profile UserProfile provides the principal fields for the user participation in addition using proxy model that extends the base data with other information. """ user = models.OneToOneField( 'authentication.User', on_delete=models.CASCADE) avatar = models.ImageField( upload_to='authentication/pictures/users', blank=True, null=True ) def __str__(self) -> str: """Return username""" return self.user.username Post # Django from django.db import models from zivo_app.apps.authentication.models.profiles import Profile class Post(HelperModel): ''' Implements the logic of post, this is a main model, inside save all the field logic for their correctly works. Extends authentication lawyer models. ''' title = models.CharField(max_length=130) error_code = models.CharField(max_length=150, blank=True) brief = models.TextField(max_length=250) avatar = models.ImageField( upload_to='blog/pictures/cover', blank=True, null=True ) # FK user = models.ForeignKey( Profile, related_name='profiles', on_delete=models.CASCADE, verbose_name=("User Profile") ) Serializers: ProfileSerializer """Profile serializer.""" # Django REST Framework from rest_framework import serializers # Models from ..models.profiles import Profile class ProfileModelSerializer(serializers.ModelSerializer): """Profile model serializer.""" class Meta: """Meta class.""" model = Profile fields = '__all__' PostSerializer ''' List all post in home level ''' # Django REST Framework from rest_framework import serializers # Models from ...models.post.post import Post class ListPostSerializer(serializers.ModelSerializer): profiles = serializers.StringRelatedField(many=True) class Meta: model = … -
Is there a special way of adding Django message to current template with multiple forms and calls to same page?
I have a message template: messages.html {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message | safe }} </li> {% endfor %} </ul> {% endif %} that I include in my templates: add_recipient.html {% block content %} {% include 'myapp/messages.html' %} <div class="doc"> <h2>Add Recipient</h2> <a class="btn btn-dark btn-lg" href="{% url 'myapp:recipient_list' 'A' %}">Back To List</a> <div class="form"> <form method="post"> {% csrf_token %} <table class="form form-table" style="font-size: x-large"> {{ recipient }} {{ address }} {{ demographics }} {% if person_forms %} {{ person_forms }} {% endif %} </table> <div class="row d-flex justify-content-center m-4"> <button class="btn btn-primary btn-lg " type="submit">Add Recipient</button> </div> </form> </div> </div> {% endblock content %} and: edit_recipient.html {% block content %} {% include 'myapp/messages.html' %} <div class="doc"> <h2>Edit Recipient Details</h2> <div class="container-fluid m-0"> <div class="row "> <div class="col-lg"> <a class="btn btn-dark btn-lg" href="{% url 'myapp:recipient_detail' recipient_id=recipient_id back_to=back_to %} ">BACK</a> </div> </div> </div> <div class="d-flex flex-row"> <div class="d-flex flex-column mx-auto" > <form method="post"> {% csrf_token %} <table class="form form-table" style="font-size: x-large"> {{ recipient_form }} {{ address_form }} {{ demo_form}} {{ formset }} </table> <button class="btn … -
why throw me this error when i try to show my api from django data in react "products undefined". In the console show me the data but not show
`import logo from '../logo.svg'; import SingleProduct from './SingleProduct' import { useState, useEffect } from 'react'; function AllProducts() { const [products, setProducts] = useState([]) useEffect(() => { fetchData('http://127.0.0.1:8000/api/products/'); }); function fetchData(baseurl) { fetch(baseurl) .then((response) => response.json()) .then((data) => setProducts(data.results)); } return ( <section className="container mt-4" > {/* Latest Products */} <h3 className="mb-4">All Products</h3> <div className="row mb-4" > { products.map((product) => <SingleProduct product={product} />) } </div> <nav aria-label="Page navigation example"> <ul className="pagination"> <li className="page-item"><a className="page-link" href="#">Previous</a></li> <li className="page-item"><a className="page-link" href="#">1</a></li> <li className="page-item"><a className="page-link" href="#">2</a></li> <li className="page-item"><a className="page-link" href="#">3</a></li> <li className="page-item"><a className="page-link" href="#">Next</a></li> </ul> </nav> </section> ) } export default AllProducts;` -
How do I make a custom user model the auth_user database?
I added this line in my settings.py file in order to make a custom User model the auth_user database: AUTH_USER_MODEL = 'main.User' (main is the name of one my apps and it contains all of the models). But I later found out that I should have done this before the initial migration so when I tried to integrate Google Authentication in the admin page I received this error that stated that my auth_user table was empty (something about it not having any records with an id of 1). So I tried deleting the migrations and returning the database to its state before the migrations but I always had an error like this: ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'main.user', but app 'main' isn't installed. I tried fixing this by following the adive on this article and cleared my postgresql database along with migration files and pycache. After this I tried to makemigrations and received this error: ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed.. And then this error when I tried to migrate: django.db.utils.ProgrammingError: relation "main_user" does not exist. I have tried searching for solutions but … -
Connecting a Django Project to an AS400 IBM iSeries System
I have been following the github documentation referred to from the official IBM website to use ibm_db and ibm_db_django packages to connect my Django application to an AS400 iSeries system. But I have constantly been running into the same error after trying to run "python3 manage.py runserver". django.core.exceptions.ImproperlyConfigured: 'ibm_db_django' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My settings.py file within my django app is as follows INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'django.contrib.redirects', 'ibm_db_django', ] DATABASES = { 'default': { 'ENGINE' : 'ibm_db_django', 'NAME' : 'XXXXX', 'USER' : 'XXXXX', 'PASSWORD' : 'XXXXX', 'HOST' : 'XXXXX', 'PORT' : '####', 'PCONNECT' : True, #Optional property, default is false } } Also my pip list dependencies within the virtual environment has the correct versions of python, Django, and the packages mentioned above to be compatible with each other so I am not sure why I am still running into this error. (env) floriskruger4@Floriss-MBP ibmi_test % pip list Package Version ----------------- -------- asgiref 3.7.2 Django 3.2 ibm-db 3.1.4 ibm-db-django 1.5.2.0 pip 22.0.4 pytz 2023.3 regex 2023.6.3 … -
Why does CSRF fail even though there is a CSRF token in Django?
I am building a login form with Django and it shows a CSRF error. The template is this: <html> <head> <title>TaxNow</title> <meta charset="utf-8"> </head> <body> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <header> </header> <script> $("document").ready(function () { $("header").load("static/header.html"); }) </script> <div id="loginbox"> <h3>Log In to Access TaxNow</h3> <div id="invalidCredentials"></div> <form action="http://127.0.0.1:8000" method="POST"> <label>Username:</label> <input type="text" id="uname" name="uname"><br><br> <label>Password:</label> <input type="password" id="pass" name="pass"><br> <button id="login" type="submit">Log In</button></br> {% csrf_token %}</form> <a href="signup.html">Sign Up</a><br> <a href="forgotCredentials.html">Forgot Username/Password?</a> <script> params = new URLSearchParams(location.search); params.get('name'); var GET = params.getAll('invalidCredentials') if (GET[0] == "true") { $("#invalidCredentials").innerHTML = "Invalid username or password." } </script> </div> </body> </html> The views.py function is like so: def logIn(request): if not User.is_authenticated: return render(request, "taxnow/app/login.html") urls.py: from django.urls import path from . import views urlpatterns = [ #other paths path('startFile', views.logIn, name="logIn") ] Something intresting is that there is a cookie here: I have used the @csrf_exempt decorator but IDK whether this is safe. Any thoughts? -
Django -> Git -> Heroku Deployment Failure
Trying to deploy Django app to Heroku but receiving the below error. Tried twice - same error. Pushing from laptop to Heroku. No branch git sites. Python 3.11.4 is on my laptop and what is used by Heroku. I have the necessary prep files required by Heroku in the root directory: procfile requirements.txt settings.py git push heroku master Enumerating objects: 11095, done. Counting objects: 100% (11095/11095), done. Delta compression using up to 8 threads Compressing objects: 100% (7766/7766), done. Writing objects: 100% (11095/11095), 17.60 MiB | 9.29 MiB/s, done. Total 11095 (delta 3916), reused 8495 (delta 2215), pack-reused 0 remote: Resolving deltas: 100% (3916/3916), done. remote: Updated 6372 paths from 4b90c76 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> **No Python version was specified. Using the buildpack default: python-3.11.4** remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.11.4 remote: -----> Installing pip 23.1.2, setuptools 67.8.0 and wheel 0.40.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.6.0 (from -r requirements.txt (line 1)) remote: Downloading asgiref-3.6.0-py3-none-any.whl (23 kB) remote: … -
bring the customer id from auto search box and then redirect to it the customer update page
I have a Django project. it has the functionality to create a customer and its working fine.I have added the auto search box in the same template to search already created customer. when i enter word its suggesting the names already saved in the database. but when i clicked a name its **displaying in the search box as [object object] not the correct name **. and I created button to selected customer to update . but when i clicked the button its saying "Please select a customer from the autocomplete list" i need to find whats the problem in my code. I need to correctly show the selected result from auto suggest search box and when i clicked the update button it should redirect to the customer update page. here is the html code of my auto complete search box" `<div class="col-md-6 mx-auto"> <div id="autocomplete" class="autocomplete"> <input class="autocomplete-input" /> <ul class="autocomplete-result-list"></ul> </div> <button id="update-customer-button" type="button" onclick="redirectToUpdateCustomer()">Update</button> </div> </div>"` and here is my JavaScript for the auto complete search and redirecting to the update page" `const selectedCustomerId = null; // Existing Autocomplete setup new Autocomplete('#autocomplete', { search: input => { console.log(input); const url = `/master/get_customers/?search=${input}`; return new Promise(resolve => { fetch(url) … -
while activating virtual environment in python showing this
ps1 cannot be loaded because running scripts is disabled on this system. run this command "Set-ExecutionPolicy RemoteSigned" then showing this To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser" -
"TypeError: unsupported operand type(s) for /: 'str' and 'int'" when dividing fields from Django model
I am trying to calculate how much progress a user has made towards their monetary goal they set inside a Django model, but it keeps giving me this error: TypeError: unsupported operand type(s) for /: 'str' and 'int' This is how I'm trying to calculate the user's progress: def calculateGoalPercentage(self): onePercent = self.goal / 100 goalPercentage = self.calculateBalance() / onePercent return goalPercentage This is my model: class Space(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, default="New Space") balance = models.FloatField(default=0.00) goal = models.FloatField(default=100.00, validators=[MinValueValidator(1.00)]) typeChoices = [ (0, "Private"), (1, "Shared"), ] space_type = models.CharField(max_length=7, choices=typeChoices, null=True, blank=True) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, null=True) created = models.DateField(auto_now=True) records = models.ManyToManyField(Record, blank=True, default=None) notes = models.TextField(default="") def calculateBalance(self): total = 0 for record in self.records.all(): total += record.amount return total def calculateGoalPercentage(self): onePercent = self.goal / 100 goalPercentage = self.calculateBalance() / onePercent return goalPercentage def __str__(self): return self.name Does anyone know what's going on? This seems like an error I would find back when I was a beginner, so I think I'm missing a small detail. -
Django - Not Migrating
I just made a new app called Recipes as I am new to Django and writing a test project and I came across this error when I made a model called Recipes and imported to admin.py I would like suggestions and code snippets please. Traceback (most recent call last): File "/home/thelordthemythxwz/CodesAtom/TheLearning/manage.py", line 22, in <module> main() File "/home/thelordthemythxwz/CodesAtom/TheLearning/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/thelordthemythxwz/CodesAtom/TheLearning/Recipes/admin.py", line 6, in <module> admin.site.register(Recipes) File "/home/thelordthemythxwz/.local/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 117, in register for model in model_or_iterable: TypeError: 'type' object is not iterable -
How to localize django-filter labels using django-parler
I am developing an e-commerce website and I am using django-filter to filter products by size, category, color, price. However I can't find a way to translate labels for filters using django-parler, I managed to translate choices for ascending and descending values but I am stuck here. Here is my filters.py lass ProductFilter(django_filters.FilterSet): CHOICES = ( ('ascending', _('Ascending')), ('descending', _('Descending')) ) price = django_filters.RangeFilter( widget=django_filters.widgets.RangeWidget(attrs={"class":"price-search"})) ordering = django_filters.ChoiceFilter(label='Sort', choices = CHOICES, method='filter_by_order') class Meta: model = Product fields = ['size', 'color', 'category'] def filter_by_order(self, queryset, name, value): expression = 'price' if value == 'ascending' else '-price' return queryset.order_by(expression) also HTML: <section class="category-products"> <div class="container"> <div class="category-wrapper"> {% for product in filtered_products %} <div class="category-item-block"> <div class="category-item"> <div class="category-item-image"> <div class="img-wrapper"> <a href="{% url 'product' product.slug %}"><img src=" {{product.thumbnail.url}}" alt="" /></a> </div> <h2>{{product.name}}</h2> </div> <div class="category-item-info"> <p>{{product.short_description}}</p> </div> <div class="category-item-price"> <p class="price">{{product.price}} AMD</p> <p class="price-monthly">{{product.price_monthly}} AMD / {% trans "monthly" %}</p> </div> <div class="buy"> <a href="{% url 'buy' product.id %}" class="buy-now"> <p>{% trans "Buy Now" %}</p> </a> <div class="add-cart"> <div class="img-wrapper"> <button hx-get="{% url 'add_to_cart' product.id %}" hx-target="#menu-cart-button" hx-swap="outerHTML" > <img class="cart-catalog" src="{% static 'img\add-to-cart.svg' %}" alt="" /> </button> </div> </div> </div> </div> </div> {% endfor %} <div class="load-more"> <button> {% … -
How to practice django projects
I am a beginner in django I have completedudemy courses. I have a basic knowledge about django and I don't know how now practice . Any youtube channel or other resources . Any other suggestions I am completed udemy course but now I don't know what to do now -
Django does not append trailing slash automatically
I'm creating a website using Django==4.2.3, the problem I'm facing is when I visit a URL for example http://127.0.0.1:8000/calculators it sends me to http://127.0.0.1:8000/calculators/ (it appends slash in the end as it should. However in the production server it doesn't append the slash to URL. For example https://example.com/calculators throws a 404 instead of redirecting to https://example.com/calculators/' I did not use the APPEND_SLASH setting as I think that's already true by default. Here is how my middleware looks like: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", "django_browser_reload.middleware.BrowserReloadMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is how I registered the URLs: calculators/urls.py from django.urls import path from .views import * urlpatterns = [ path('', CalculatorsView.as_view(), name='calculators'), path('stripe-fee/', StripeFeeCalculator.as_view(), name='stripe_fee_calculator'), path('fiverr-fee/', FiverrFeeCalculator.as_view(), name='fiverr_fee_calculator'), ] project/urls.py urlpatterns = [ ... path('calculators/', include('calculators.urls')), ... ] Please help me figure out how to solve this problem, thanks in advance! -
If I encode a JWT and send it in a URL then surely I need the secret key to decode it?
I have this function to encode a JWT token that I send in the URL so an application. encoded_token = jwt.encode({'token': token}, os.environ['SECRET_KEY'], algorithm='HS256') On the application side I decode the key and then use it to get the credentials of a user. Surely if I encode a JWT token using the above function and my secret key, do I need that secret key to decode it on the application side? At the moment that is not the case and the following function on the application side decodes the key and it's correct because I get the credentials of the user associated with the said token. So this is a security risk because I send the token in the URL (cannot seem to find another way)? function decodeJwt(token) { var base64Payload = token.split(".")[1]; var payload = decodeURIComponent( atob(base64Payload) .split("") .map(function (c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); }) .join("") ); return JSON.parse(payload); } Can someone please tell me why my token is decoded without my secret key and also maybe give me another way I can send the token to the application. Help is appreciated -
Django Foreign Key. How to access child model through the parent
So I created custom Profile model for a user and it's connected to the base Django User model via Foreign Key. I can easily access User model's fields through my Profile model because the Profile model has the field with Foreign Key to a User model (for example profile.user.username and etc.) But how do I access Profile model fields via User model? Here is the Profile Model user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) username = models.CharField(max_length=150) email = models.EmailField() image = models.ImageField(upload_to='images/user_profiles', blank=True, null=True) def __str__(self): return f"{self.user}'s profile" And I've tried to access profile id like that, but it doesn't work a href="{% url 'profile' pk=request.user_profile.id %}" ...``` path('profile/<str:pk>/', views.user_profile_view, name='profile'), -
requests.user returns AnonymousUser when used in api view other than login
I am using Django's default authentication and authorization system. I have used DRF in backend and React in frontend #views.py from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib.auth.models import User from django.contrib.auth import authenticate,login from .models import * from .serializers import * import json # Create your views here. @api_view(['GET']) def slips(requests): if requests.method == 'GET': data = slip.objects.all() serializer = slipserializer(data,many = True) return Response(serializer.data) @api_view(['GET']) def packages(requests): if requests.method == 'GET': data = package.objects.all() serializer = packageserializer(data,many = True) return Response(serializer.data) @api_view(['POST']) def register(requests): if requests.method == 'POST': try: data = requests.body.decode('utf-8') ref_data = json.loads(data) usr = User.objects.create_user(ref_data['firstname'],ref_data['email'],ref_data['password']) usr.last_name = ref_data['lastname'] usr.save() login(requests,usr) return Response({'message':'registered successfully'}) except: return Response({'message':'something went wrong'}) @api_view(['POST']) def logIn(requests): if requests.method == 'POST': try: data = requests.body.decode('utf-8') ref_data = json.loads(data) uname = User.objects.get(email = ref_data['ID']) usr = authenticate(username = uname,password = ref_data['password']) login(requests,usr) return Response({'message': 'successfully logged in'}) except: print('failed') return Response({'message': 'something went wrong'}) @api_view(['GET']) def projects(requests): if requests.method == 'GET': proj = project.objects.all() serializer = projectserializer(proj,many = True) return Response(serializer.data) @api_view(['GET']) def skills(requests): if requests.method == 'GET': sk = skill.objects.all() serializer = skillserializer(sk,many = True) return Response(serializer.data) @api_view(['GET']) def tech(requests): if requests.method == 'GET': tech = technology.objects.all() serializer = … -
Upload Gigabytes of files to Storage Account from Django
I have a project setup with Django and ReactJs. The use case is, users will upload Gigabytes of files and those are to be stored to their respective folders in Azure Storage Account File Shares service (using Azure Python SDK). How do I upload them through backend (Django)? How can it be handled in the scalability perspective as well? I came across RabbitMQ and Kafka to redirect the upload through backend, but since it is not yet implemented. I'm looking for suggestions and other possible ways to do the same. Any suggestions to the scenario would be helpful. Thank you! -
Problem with rendering post host profile picture in DJango template
I am trying to render a Django template with different post made by several users. In each individual post, I want to display the profile picture of the person whom created the post. For some reason, the template renders with the posts in full display but without the profile picture. I have tried to display profile pictures using absolut URL and it works fine, but it does not work dynamically when I try to access the profile picture in the database. Also, I have made sure that there are profile pictures in the database by uploading pictures from the admin panel. Here are my codes. Model: class Member(PermissionsMixin, AbstractBaseUser): # Fields for sign up page username = models.CharField( _("Användarnamn"), max_length=50, unique=True, default='') email = models.EmailField( _("Mail"), max_length=100, unique=True, default='') age = models.PositiveIntegerField(_("Ålder"), null=True, blank=False) country = models.CharField(_("Land"), max_length=50, null=True, blank=True) county = models.CharField(_("Län"), max_length=50, null=True, blank=True) city = models.CharField(_("Stad"), max_length=50, null=True, blank=True) sex = models.CharField(_("Kön"), max_length=50, null=True, blank=True, choices=sex_choices) avatar = models.ImageField( _("Profilbild"), upload_to="static/user_profile_pics", null=True, blank=True) account_created = models.DateTimeField( _("Medlem sedan"), null=True, auto_created=True) last_login = models.DateTimeField( _("Senast inloggad"), null=True, auto_created=True) city_name = models.CharField(max_length=100, null=True, blank=True) country_name = models.CharField(max_length=100, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] is_staff …