Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to.limit a users conten upload in django
Hello guys I want to restrict user, my I am working on a project in django where I have a producer model so I want to restrict the producer from uploading contents based on the particular package they're currently running on... Let's say if they subscribe to a pro package they can't upload more that 5 contents.. -
How to make a table only visible to a specific user in Django
So, I was studying Django and started doing some projects to fixate what I learned. I'm building a contact book like website and want to make each user have a unique Contacts table. I've tried putting this on models.py: class UserContatos(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Contato(models.Model): nome = models.CharField(max_length=255) sobrenome = models.CharField(max_length=255, blank=True) telefone = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField( default=timezone.now) descricao = models.TextField(blank=True) categoria = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) foto = models.ImageField(blank=True, upload_to='fotos/%y/%m/%d') def __str__(self): return self.nome contatos = Contato() class ContatoForm(forms.ModelForm): class Meta: model = UserContatos.Contato exclude = ('',) When I use this form to create a contact, it doesn't "go to the user". -
Export MUI components or style to use outside of React app
I'm facing a use case I'm not familiar with. I'm currently using MUI for a React application, but the authentication part is handled on another server, a Django application that includes Django OIDC Provider lib and which mostly consists in a sign in form that redirects the user to the React client upon sign in. The ultimate goal would be to have the same look and feel across both applications to provide a better user experience, I'm wondering what is the best solution for this: embed a full React application into the Django project and share the MUI theme across both application, seems to be the best choice for consistency but will be costly in term of development time and bundle size of the authentication app (basically loading React + MUI just for one page) trying to mimic the MUI components (mostly text fields, checkbox, buttons) with a pure CSS solution like https://github.com/finnhvman/matter which looks very nice, but it will take time to reproduce the main React app MUI theme, it will be harder to maintain and it will be hard to provide the exact same interactivity somehow find a way to export pure CSS with MUI theme style or … -
Django - Storing total API request from user, Limit and Filter it [Django Ninja]
I'm new to django, i'm currently working with API using Django Ninja Rest Framework. in this example, users will have a unique APIKey each time i create new APIKey from this model and attach it to selected user. this is my APIKey model : ### NOTE - This is just for testing, Not a real model, see the link below class APIKey(models.Model): key = models.CharField(max_length=64) # i know this should be unique, just for demo :) user = models.ForeignKey(get_user_model(), related_name='free_key', on_delete=models.CASCADE) label = models.CharField(max_length=40) revoked = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField(null=True, blank=True) This model is just for testing purposes, I actually use this for my project and modify it. So, My API endpoints need an API key for authentication (the API key that i have created that correspond to a specific user), so i implement and follow the steps here and it works normally My questions are : Each user has a unique API key. How to count and store the total request from a user each time user makes a request to an endpoint ? Should i add request_total field to my APIKey model or create a new Model ? Should i use custom middleware? or should … -
Django + nginx (with docker): erratic /admin redirects
So, I have a project that features a Docker deployment of a website with Nginx, Django served with Gunicorn + static files, and a Vue.js frontend (compiles to static files). The problem: When I try to access Django's admin interface, at http://localhost:8100/admin, I am redirected to https://localhost/admin/, which obviously fails. What I really want: First, for this to work. But I don't want to hardcode a website name (because it's an open source project), I don't want to force SSL, because I have a server where I'm going to deploy this behind another reverse proxy so that the website will be some subdomain on my server, under my certificates. So I want for both the Nginx and the Django layer to be as "dumb" as possible. To help debugging: docker-compose.yaml: version: "3" services: reverse-proxy: image: nginx:stable ports: - 8100:80 volumes: - frontend_data:/frontend/ - backend_data:/backend/ - ./nginx:/etc/nginx/conf.d depends_on: - backend frontend: # .... backend: build: context: ./backend dockerfile: Dockerfile entrypoint: ./entrypoint.sh stop_signal: SIGINT depends_on: - db volumes: - backend_data:/backend/ db: image: postgres:13-bullseye volumes: - postgres_data:/var/lib/postgresql/data/ volumes: # ... Nginx's config: upstream backend_server { server backend:8000; } server { listen 80; location /api { proxy_pass http://backend_server/api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; … -
AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly
I have a problem with (I think) permissions. When I try to send post request via postman, I get following error: AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set .queryset or have a .get_queryset() method. [29/Nov/2021 20:21:21] "POST /api/blog/category HTTP/1.1" 500 101581 Here are my views.py and category class. Also, I noticed that for some reason in def post(self, request, format=None) request is not being called ("request" is not accessed Pylance). I think the problem is somewhere here, but can't figure it out. Thank you in advance. class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permissions_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact=category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) -
Where does a Django generic view class call the database?
I can inherit from a class based generic view from generic.ListView as in class BookListView(generic.ListView): model = Book Supposedly the .as_view() function gets called when the Django app starts up to create an instance of this view. I find the definition of get_queryset in MultipleObjectMixin but what I dont find is, from where is this method called from? -
How to send data to running django management command?
I have a custom django management command that is constantly running through the supervisor (keep alive) I need under certain circumstances (for example, a signal in the project, or a change in the database) the django management process reacted to these changes. Tried looking for something similar but can't seem to find a simple implementation. -
Data returned by view is not recognized by Chart.JS chart
I return a dictionary within my view which should be used as data input for a basic Chart.JS bar chart. However, the chart doesn't recognize the data. # .js const ctx = document.getElementById('balances-chart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: balances_dict, options: { scales: { y: { beginAtZero: true } }, indexAxis: 'y', } }); # views.py ... balances_dict = {} for balance in balances: if not balance['asset_type'] == 'native': balances_dict[balance['asset_code']] = balance['balance'] context = { 'dashboard_site': dashboard_site, 'user': user, 'cashpool': cashpool, 'payments': payments, 'balances_dict': balances_dict } return render(request, 'dashboard/dashboard_overview.html', context) returns dashboard_overview.js:6 Uncaught ReferenceError: balances_dict is not defined Is there anything special to consider when using ChartJS with Django? -
DJANGO JWT - CANT LOGIN ( HTTP 401 Unauthorized ) PROBLEM
"HTTP 401 Unauthorized" I HAVE BEEN TRYING TO FIX THIS ERROR SINCE 3 DAYS My LoginAPIView class LoginAPIView(generics.GenericAPIView): serializer_class=LoginSerializer #permission_classes = (permissions.IsAuthenticated) def post(self,request): serializer=self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data,status=status.HTTP_200_OK) and My LoginSerializer class LoginSerializer(serializers.ModelSerializer): email=serializers.EmailField( max_length=255,min_length=3)#not matter password=serializers.CharField( max_length=68,min_length=5,write_only=True) username= serializers.CharField( max_length=255, min_length=3,read_only=True) tokens = serializers.CharField( max_length=255, min_length=6, read_only=True) class Meta: model=User fields=[ "email", "password", "username", "tokens" ] def validate(self, attrs): email= attrs.get("email", "") password = attrs.get("password", "") # Kimlik doğrulama hatası verdi bunun sebebi... ################################################ user = auth.authenticate(email=email, password=password) """ debug için örneğin, kullanıcı gelip gelmediğini buradan görebilriiz. bunu yazdığımız yer debug çalıştırır. """ """ import pdb pdb.set_trace() """ if not user: raise AuthenticationFailed('Geçerli Kimlik bilgileri giriniz!') if not user.is_active: raise AuthenticationFailed('Hesabınız aktif değildir, lütfen admin ile iletişime geçiniz.!') if not user.is_verified: raise AuthenticationFailed(' E-mailiniz doğrulanmadı, lütfen sizlere göndermiş olduğumuz doğrulama baplantısını onaylanıyınız!') return { 'email':user.email, 'username':user.username, 'tokens':user.tokens, } return super().validate(attrs) So, I used """ import pdb pdb.set_trace()""" ı checked my cmd, There was a problem like that, Unauthorized: /auth/login/ [29/Nov/2021 22:13:35] "POST /auth/login/?next=/ HTTP/1.1" 401 7638 I have an account on my system, ı trying to login in my system with my exites account, but throwig that problem ı couldnt fix it, Thak u so much for ur help -
How to use inputs to do calculations with mathfilters in Django?
I am using mathfilters in Django, I want to do a multiplication between quantity and unit_price and reflect it in total_price. I already followed the documentation from here mathfilters and when implementing it as it says and filling those 2 inputs with numbers, the result is not reflected anywhere Maybe I am not implementing it well but when I search I see that there is very little information to use mathfilters <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> <li>{{ presupuestosparteform.quantity|mul:presupuestosparteform.unit_price }}</li> </td> -
ModelChoiceField - get request.user.username
I need to choose User to form by the request.user.username and save into the database. Here I have a code of forms.py class Send(forms.ModelForm): sender = forms.ModelChoiceField(queryset=User.objects.order_by('username') Here is the models.py, where I am going to save the data about the user: class SendM(models.Model): sender = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE) And here is views.py, where I get the data def form_create(request): if not request.user.is_anonymous: form = Send(request.POST or None, initial={'sender': request.user.username}) if request.method == "POST": if form.is_valid(): send = SendM(sender=User.objects.get(username=form.cleaned_data['sender'])) send.save() return redirect("/") To understand I want to pre-filled the array with the user found in database. Thank you very much!! -
implementing oauth2 for google calendar api with django
Can anybody direct me to a complete example of implementing oauth2 with django? From the older posts, I found some bits and pieces, or work-arounds, but I am not yet experienced enough to put the pieces together. I want to integrate into an web app creating, updating, deleting events. Followed the quickstart in the documentation, it works fine. I need to switch to a web app flow, instead of the installed app flow, here I got stuck, on authorizing the app and on receiving the approval of the resource owners to access their calendars. Thank you for your support. -
Django send events via websocket to all clients
I want to send events (json strings) via websocket to all clients (to all who established connection via websocket). My code: I think that asgi and routing are ok asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base_app.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) routing.py from api_producer.consumers import EventWebSocket websocket_urlpatterns = [ url('ws/start/', EventWebSocket.as_asgi()), ] The problematic point: Some function generates events and I want to send these events to the clients from api_producer.consumers import EventWebSocket def event_producer(): my_socket = EventWebSocket() my_socket.receive("Some_text") consumers.py class EventWebSocket(WebsocketConsumer): def connect(self): self.channel_name = "CHANNEL_1" print("ZZZ_") async_to_sync(self.channel_layer.group_add)("chat", self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( # 'EventWebSocket' object has no attribute 'channel_layer "chat", { "type": "chat.message", "text": text_data, }, ) def chat_message(self, event): self.send(text_data=event["text"]) My actions: 1 Go to websocketKing and send request ws://127.0.0.1:8000/ws/start/. Log output: WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37476] WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37476] ZZZ_ WebSocket DISCONNECT /ws/start/ [127.0.0.1:37476] WebSocket DISCONNECT /ws/start/ [127.0.0.1:37476] 2 Run function event_producer() I don't see any output (guess because WebSocket DISCONNECT) What is the proper way to send events? -
How can I get Django inside a docker compose network to recognize the postgres service name while using PyCharm?
I've been fiddling with my Dockerfile and Docker Compose to try and get PyCharm to be able to run and debug my django application. I've identified that I need all services to be on the same network, and have put them on the same network, but when I go to execute the runserver command through my PyCharm configuration, I get an error that django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known I've tried adjusting the Dockerfile to expose environment variables inside of it, instead of in the compose file. As well as grouping all the services into the same network. I'm at a bit of a loss as to where to go from here, as most other StackOverflow questions relating to this tell me to do things I've already tried. docker-compose.yml version: "2" services: redis: image: redis:latest # redis restart: always logging: driver: "none" networks: - integration postgres: image: postgres:latest restart: always ports: - "5400:5399" volumes: - /usr/lib/postgresql - ./tmp:/dmp:ro - ./load.sh:/usr/app/load.sh environment: POSTGRES_USER: vagrant POSTGRES_PASSWORD: vagrant POSTGRES_HOST_AUTH_METHOD: trust logging: driver: none networks: - integration django: build: . command: "/bin/bash" working_dir: /usr/app/ stdin_open: true tty: true volumes: - ./tmp:/tmp - ./:/usr/app - ~/.ssh:/root/.ssh:ro links: … -
Is there a way in Django to expose only a certain range of URLs based on some predefined variable?
I am basically trying to expose a a range of defined URLs in an application. E.g., I have 10k x2 resources which I'm hosting at /metadata/type1_1 and /metadata/type2_1 where each resource grouping iterates up to type1_10000 and type2_10000 respectively (20,000 stored assets I intend to serve over a manually-driven interval). As such, I'm trying to define a URL scheme such that max_available_metadata = current_limit [e.g. this may be 300, 7777 etc.] and I only want to configure the URLs within the pattern up to this limit. e.g., if I sent it to 25, type1_1, type1_2...25 and likewise type2_1, type2_2... type2_25 would all map properly but attempting to go to metadata/type1_26 through type1_10000 would all return 404s, likewise for type 2. I'll probably want to configure setting this via the django admin but this isn't part of the question. -
Reverse for 'category' with keyword arguments '{'category': ''}' not found. 1 pattern(s) tried: ['category\\/(?P<category>[^/]+)\\/$']
name of the error is Reverse for 'category' with keyword arguments '{'category': ''}' not found. 1 pattern(s) tried: ['category\\/(?P<category>[^/]+)\\/$'] I know that there is a lot on this topic on this forum but my case is somewhat special due to that my views are working on other menu. To Be more accurate I have 2 navbars and if click one link on navbar A everything is good but then I click link on navbar B and I get the error I have a category model that looks like this. If the Navbar field is True I'm putting the category name and link on the navbar B. All fields are visible on navbar A class Category(models.Model): category = models.CharField(max_length=20,unique=True) navbar = models.BooleanField(null=False, blank=False, default=True) def __str__(self): return self.category Due to menu layout ( B ) looking like this I need to set nav links manually nav - nav - language_changer - nav - nav\ So I've set them like this <a href='{% url "category" category="{navbarList.0.id }" %}'> {{ navbarList.0.category }} </a> <a href='{% url "category" category="{navbarList.1.id }" %}'> {{ navbarList.1.category }} </a> the A navbar {% for x in categoryList %} <a href="{% url 'category' category=x.category %}" > {{ x.category }} … -
Docker-compose up runs perfectly localy ,but on gcp i get error could not translate host name db to address: Temporary failure in name resolution
line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution On my local machine everything works perfectly. my docker file FROM python:3.9-slim-buster # RUN apt-get update && apt-get install -y libpq-dev \ # gcc \ # postgresql-client # set work directory WORKDIR /opt/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /opt/app/requirements.txt RUN chmod +x /opt/app/requirements.txt RUN pip install -r requirements.txt # copy project COPY . /opt/app/ RUN chmod +x /opt/app/docker-entrypoint.sh EXPOSE 8000 ENTRYPOINT [ "/opt/app/docker-entrypoint.sh" ] Here is my docker-compose.yml version: '3.9' services: db: image: postgres restart: always environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_PASS=postgres volumes: - postgres_data:/var/postgres/data/ app: restart: always build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 container_name: myproj volumes: - ./app/:/usr/src/app/ ports: - "8000:8000" depends_on: - db volumes: postgres_data: driver: local my entrypoint echo "Apply database migrations" python manage.py makemigrations python manage.py migrate echo "Starting server" python manage.py runserver 0.0.0.0:8000 exec "$@" my database settings 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': … -
How to add Q lookups with the get_queryset in Django rest framework?
I have written some filtering code in get_qeuryset function. Also I have a separate search filter api which searches based on the string provided in the query parameter search. Now what I want is add the search query into the former filtering logic so that user can search only in the filtered results and not from the whole database again. My model: class Product(models.Model): WARRANTY = ( ('no_warranty', 'No Warranty',), ('local_seller_warranty', 'Local Seller Warranty',), ('brand_warranty', 'Brand Warranty',), ) merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? /.........other codes.........../ My filtering view: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer queryset = Product.objects.all() pagination_class = CustomPagination def get_queryset(self): brand = self.request.GET.get('brand', None) sub_category = self.request.GET.get("sub_category", None) warranty = self.request.GET.get("warranty", None) if brand is not None: brand_values = brand.split(",") if sub_category is not None: sub_category_values = sub_category.split(",") if warranty is not None: warranty_values = warranty.split(",") return Product.objects.filter(brand__name__in=brand_values, sub_category__name__in=sub_category_values, warranty__in=warranty_values) /..........other codes........../ My url to call this localhost/api/products?brand=Samsung,Lg&warranty=no_warranty Q lookup search view: from django.db.models import Q class PrdouctSearchAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer pagination_class = … -
How to delete a single data from database in django (not deleting the entire row)
To give you an understanding of my problem, I am showing my code first, then my question. In models.py: class Post(models.Model): content = models.CharField(max_length=140) date_created = models.DateTimeField(auto_now_add=True) poster = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) liked_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='liked_by', blank=True, null=True) def serialize(self): return { "id": self.id, "poster": self.poster.username, "poster_image_url": self.poster.image_url, "date_created": self.date_created.strftime("%b %d %Y, %I:%M %p"), "content": self.content, "likes": self.likes,} In views.py: @csrf_exempt def get_post(request, post_id): post = Post.objects.get(pk=post_id) if request.method == "GET": return JsonResponse(post.serialize()) elif request.method == "PUT": data = json.loads(request.body) if data.get('likes') is not None: if data['likes'] > post.likes: post.likes = data['likes'] post.liked_by = request.user else: post.likes = data['likes'] post.liked_by.remove(request.user) post.save() return HttpResponse(status=204) I need to remove request.user from liked_by column in the post object. But this error occurs: AttributeError: 'User' object has no attribute 'remove' How can I solve the problem? -
Django : Add extra action to a SetViewModel while using NestedViewSetMixin
I am trying to add an action to a SetViewModel in Django, this SetViewModel is already using NestedViewSetMixin succefully : here is the structure of my api call : /api/startups/1/investments So this will list all investments for startup with id 1. Now I would like to add an extra action to only display investments for a specific startups that are in active status. The api call would be this way : /api/startups/1/investments/get_active_investment/ At the moment I am getting this error code : AttributeError at /api/startups/1/investments/get_active_investment/ Got AttributeError when attempting to get a value for field `collected_amount` on serializer `InvestmentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'collected_amount'. Request Method: GET Here is my code for the SetViewModel : class InvestmentViewSet(NestedViewSetMixin, ModelViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions for Investments. """ model = Investment serializer_class = InvestmentSerializer queryset = Investment.objects.all() @action(detail=False, methods=['Get']) def get_active_investment(self, *args, **kwargs): """Get active investment Only One investment/startup is active """ queryset = self.get_queryset().filter(active=True) serializer = self.get_serializer(queryset, many=False) return Response(serializer.data) -
NoReverseMatch. Reverse for '' not found
I have a django project called main and an application called tracking. I created a register form but when I want to open the register page, I get this error: NoReverseMatch at /tracking/worker_register/ Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. My Error: `NoReverseMatch at /tracking/worker_register/ Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/tracking/worker_register/ Django Version: 3.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'worker_register' not found. 'worker_register' is not a valid view function or pattern name. Exception Location: X:\Projects\dJira_app\.venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: X:\Projects\dJira_app\.venv\Scripts\python.exe Python Version: 3.7.0 Python Path: ['X:\\Projects\\dJira_app\\main', 'X:\\Projects\\dJira_app\\.venv\\Scripts\\python37.zip', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\anubi\\AppData\\Local\\Programs\\Python\\Python37-32', 'X:\\Projects\\dJira_app\\.venv', 'X:\\Projects\\dJira_app\\.venv\\lib\\site-packages'] Server time: Mon, 29 Nov 2021 17:49:26 +0000` The urls.py: from django.urls import path from .import views urlpatterns=[ path('register/', views.register, name='register'), path('worker_register/', views.worker_register.as_view(), name=''), path('manager_register/', views.manager_register.as_view(), name=''), ] main URLs: from django.contrib import admin from django.urls import include, path from tracking import views urlpatterns = [ path('tracking/', include('tracking.urls')), path('admin/', admin.site.urls), ] HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1 class="mt-2">Worker registration</h1> <hr class="mt-0 mb-4"> <form action="{% url 'worker_register' %}" method="POST" novalidate> {% csrf_token %} {{ … -
upload file in django admin without model and use it to update database
I want to upload a CSV file in the admin that adds information to a model. I extended the change_form.html and I overwrote the response_change function in the admin.py: change_form.html: <form method="post" enctype="multipart/form-data"> <input type="file" name="uploadCSV" /> <input type="submit" name="submit" value="upload CSV" accept=".csv"/> </form> admin.py: class StoreAdmin(admin.ModelAdmin): list_display = [..] def response_change(self, request, obj): if "uploadCSV" in request.POST: with open(request.POST["uploadCSV"], encoding="utf8") as f: data = f.read() ... return redirect(".") I end up with: No such file or directory: 'test.csv' because the file is not read in yet, but just a string with the location. How can I actually load the file (temporarily)? -
django.setup(): ModuleNotFoundError: No module named 'api.apps' when DJANGO_SETTINGS_MODULE is set
I am attempting to add entries to a Django Database from an external Python script, but have run into errors when attempting to import my Django Models. I am using venv for both the database and the individual Python script I used the following link: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured to attempt to setup Django before importing my Model, but now I am running into the following error: ModuleNotFoundError: No module named 'api.apps' I also set the Python Path to be at the top of my project directory, which is above both my Database and Python Script. The Python file I am attempting to create is in a different folder from my Database, and here is the code: (Note that my Django database name is database, and is the main part as well. I have "api" as a separate directory.) import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.database.database.settings') import django django.setup() from database.api.models import Example This fails on django.setup(). I have done an alternate attempt with "from database.database.wsgi import *" that results in the same Error. I am unsure of what causes this, as when I run the database, the models in "api" appear just fine, and I do add … -
Django crispy form itself is saving the form, but crispy fields is not saving to the database
This code is saving my form <form method="POST" role="form" enctype="multipart/form-data" id="form-container"> {{ my_form|crispy }} <button type="submit">Submit form</button> </form> But when I use as_crispy_field, It is not submitting at all. <form method="POST" role="form" enctype="multipart/form-data" id="form-container"> {{ my_form.lastName|as_crispy_field }} {{ my_form.firstName|as_crispy_field }} {{ my_form.middleName|as_crispy_field }} {{ my_form.birthData|as_crispy_field }} {{ my_form.nation|as_crispy_field }} {{ my_form.birthPlace|as_crispy_field }} <button type="submit">Submit form</button> </form>