Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display multiple Plotly graphs in a HTML webpage? (using plot_div)
I would like to display multiple plotly graphs in a HTML webpage. I tried many codes, but the simplest one I found was this: In my views function, I have: for graphs in res: plot_div = plot(res[graphs], output_type='div') return render(request, '__', context={'plot_div': plot_div, "result": res}) In my HTML, I have: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test</title> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} </body> </html> However, only the last graph is displayed. That's because the variable plot_div is constantly being updated under the for loop. Thus, I tried to create a dictionary like so: plot_div = dict() for index, graphs in enumerate(res, 1): plot_div.update({index: plot(res[graphs], output_type='div')}) return render(request, 'account/user/IndFin/indfin_resultado.html', context={'plot_div': plot_div, "result": res}) Thus, I needed to change the HTML to: {% for graphs in plot_div %} {{plot_div.graphs}} {% endfor %} But, as a result I get, in my webpage, the matrix result and the last graph again. No graphS at all, just the last one. Has anyone faced such problem before? Thanks -
Django/Postgre Docker deployment - Localhost:8000 404 error
I am trying to spin up a Django web application and Postgre database using docker-compose. I am following the steps at https://docs.docker.com/samples/django/ pretty spot on, but I am still getting a 404 error on localhost:8000 after spinning up my docker containers. Any help would be appreciated as to why this is not working. docker-compose.yml: version: "3.9" services: db: image: postgres environment: - POSTGRES_HOST_AUTH_METHOD=trust volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: bash -c "python3.8 manage.py makemigrations && python3.8 manage.py migrate && python3.8 manage.py runserver 0.0.0.0:8000" volumes: - .:/dittoservice-docker ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /dittoservice-docker RUN apt-get update RUN pip3 install django RUN pip3 install django-cors-headers RUN pip3 install djangorestframework RUN pip install "ditto.py[all]" RUN pip3 install psycopg2 RUN pip3 install pytz COPY . /dittoservice-docker settings.json DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } Docker-compose up output: -
New to heroku and publishing websites wanting to know the best plan/dyno-type to choose for large 203mb django website
I have a Django website that I want to publish, the size of the file being pushed to Heroku is 203 Mb (memory quota vastly exceeded when using the free version). I will also require the Heroku app to temporarily store CSV files that can range from 80kb to 10Mb as well as user login information. If anyone could recommend a plan/dyno-type to use that at least meets the storage requirements that'll be greatly appreciated. thank you! -
When i click on the same radio check twice, it changes the output to the opposite, but doesnt change the check
I've got 2 radio checks in a questionaire. If i choose Yes, it will show me certain inputs, and when check set to No it shows me different inputs. The thing is, when i click on Yes twice, check remains on the Yes, but shows me the inputs for 'no'. Do you have any idea why is it like that? This one should show me 'yes' inputs This should show me 'no' inputs Django html: <div class="form-check mt-5"> <h6 class="c-grey-900">Czy masz swoje zwierzę?</h6> <label class="form-check-label mt-2" id="choose-if-animal"> <input class="form-check-input" type="radio" name="has_animal" id="has_animal1" value="yes" > Tak, jestem właścicielem/właścicielką zwierzaka<br> </label> </div> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="has_animal" id="has_animal2" value="no"> Nie, nie mam swojego zwierzęcia </label> </div> In views.py its simple: if has_animal == 'yes': has_how_many_animals = all_post_data['has_how_many_animals'] elif has_animal == 'no': animal_type_like = all_post_data.getlist('animal_type_like[]') -
Reverse for "page" with no arguments not found. 1 pattern(s) tried
I started testing and studying Django recently and I'm building some projects to learn and test it. I tried looking for answers in the documentation but was unable to find any, if you can send me the documentation reference to solve this with your solution/tip, I'd appreciate it. I'm trying to pass an argument through the URL in Django, the url changes and the int appears on the browser when redirecting (i.e. http://127.0.0.1:8000/edit-contact/1 - 1 being put dinamically from the "redirecting") but, apparently, the view function can't recognize it. button I'm using to redirect and send the argument <a href="{% url 'edit-contact' contato.id%}" class="btn btn-primary"> Edit contact </a> urls.py file: urlpatterns = [ path('', views.index, name='index'), path('busca/', views.search, name='busca'), path('<int:contato_id>', views.details, name='detalhes'), path('edit-contact/<int:contato_id>', views.edit_contact, name='edit-contact'), ] view function I'm using to capture the request @login_required(redirect_field_name='login') def edit_contact(request, contato_id): if request.method != 'POST': form = ContatoForm() return render(request, 'contatos/detalhes.html', {'form': form, 'contato_id': contato_id}) Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/edit-contact/1 Django Version: 3.2.9 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contatos.apps.ContatosConfig', 'accounts.apps.AccountsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Template error: In template D:\Gabriel\Codando\studying\django_learning\DjangoProj_agenda\templates\base.html, error at line 0 Reverse for 'edit-contact' with no arguments … -
Django models with reverse field
I have a problem that I seem cant find a solution to it see I have 2 models with a ForeignKey as below : class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices) property_market_rent = models.DecimalField( help_text="Weekly", max_digits=7) class FamilyGroup(models.Model): Transaction= models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="family_groups") last_rent = models.DecimalField(max_digits=7, decimal_places=2) income_period = models.CharField(max_length=11, choices=income_period_choices) any_income_support_payment = models.BooleanField(null=True, blank=True) @property def rent_charged(self): rent_charged = self.transaction.property_market_rent - self.last_rent now this function is good for only one instance of FamilyGroup, what im trying to do is to Subtract this rent_charged from self.transaction.property_market_rent in the next instance of FamilyGroup, so the next instance of FamilyGroup can have something like : @property def rent_charged(self): rent_charged = self.transaction.property_market_rent - rent_charged #( of the first instance) - self.last_rent Any thoughts would be so appreciated! -
Django composition clean forms don't work correctly
class RegisterForm(forms.ModelForm): ... class Meta: model = CreateUser ... def clean(self, password1, password2, error_key="password"): symbols = ['$', '@', '#', '%', '!'] password1 = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') errors = dict() if password1 and password2: if password1 != password2: errors[error_key] = "Passwords do not match" raise forms.ValidationError(errors) if not any(symbol in symbols for symbol in password1): s = ", " errors[error_key] = f"Passwords don\'t have symbols like {s.join(symbols)}" raise forms.ValidationError(errors) if not any(char.isdigit() for char in password1): errors[error_key] = "Password should have at least one numeral" raise forms.ValidationError(errors) if not any(char.isupper() for char in password1): errors[error_key] = "Password should have at least one uppercase letter" raise forms.ValidationError(errors) if not any(char.islower() for char in password1): errors[error_key] = "Password should have at least one lowercase letter" raise forms.ValidationError(errors) return self.cleaned_data class SetPasswordsForm(forms.Form): ... def __init__(self, user, *args, **kwargs): self.user = user self.register = RegisterForm super().__init__(*args, **kwargs) def clean(self): password1 = self.cleaned_data.get('new_password') password2 = self.cleaned_data.get('confirm_new_password') self.register.clean(self, password1, password2, error_key="new_password") return self.cleaned_data I want composition class and function and override this in django, I created my own User, and now i created my own validation but i dont want duplicate code-lines. Why this second function clean don't work correctly? ;/ -
How to encrypt a file with openpgp PGPy - Django python
I am trying to use PGPy for encrypt a zip file. I had a public and private key, but it seems going to dead-end as PGPy decline my keys due to missing required flags.. I already try to bypass require flag as guided from the documentation and still error happen. Also, I sent an issue to its github https://github.com/SecurityInnovation/PGPy/issues/382 Could someone assist me the simple way to perform this? Or maybe there is another way to achieve this? Any positive feedback will be appreciated. Thanks. -
Django select_related the join table only for a many-to-many relation
I have a Django application with a model A with a ManyToManyField bees to model B. For one view, when I select a bunch of A's I also need the ids of their B's. The default where Django queries the related B's for each A individually is too slow, so I use select_related. If I do A.objects.select_related('bees') Django selects the full B models: SELECT ("app_a_bees"."from_a_id") AS "_prefetch_related_val_from_a_id", "app_b"."id", "app_b"."field1", "app_b"."field2", ... FROM "app_b" INNER JOIN "app_a_bees" ON ("app_b"."id" = "app_a_bees"."to_b_id") WHERE "app_a_bees"."from_a_id" IN (... list of A ids ...) But I only need their id values, so I only need to select the app_a_bees join table to get them, not the B model table. I tried A.objects.select_related('bees__id') (I also tries 'bees_id') but Django doesn't like that, individual fields cannot be prefetched in this way. I have also tried A.objects.select_related(Prefetch("bees", queryset=B.objects.all().only("id")), but that still joins to the B table to select the id field, which Django already has from the join table. Is there any way to prefetch just the join table for my A objects? -
i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups
i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups. i need everyone to be assigned to their specific group Signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Worker,Client def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') post_save.connect(client_profile, sender=User) def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('profile created!') i have two groups, 'client' and 'worker'.. when i register a client everything is fine but for a worker he gets assigned to both groups. i need everyone to be assigned to their specific group views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'users/register.html', context) def workerRegister(request): if request.user.is_authenticated: return redirect('plumber_home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success( request, 'Account was created for ' + username) return redirect('worker_login') context … -
docker-compose doesn't mount volumes correct for django container
Running Docker on Windows 10 with WSL 2 Ubuntu on it. I have the following Dockerfile: FROM ubuntu #base directory ENV HOME /root #subdirectory name for the REST project ENV PROJECT_NAME django_project #subdirectory name of the users app ENV APP_NAME users #set the working directory WORKDIR $HOME #install Python 3, the Django REST framework and the Cassandra Python driver RUN apt-get update RUN apt -y install python3-pip 2> /dev/null RUN pip3 install djangorestframework RUN pip3 install cassandra-driver #initialize the project (blank project) and creates a folder called $PROJECT_NAME #with manager.py on its root directory RUN django-admin startproject $PROJECT_NAME . #install an app in the project and create a folder named after it RUN python3 manage.py startapp $APP_NAME ENV CASSANDRA_SEEDS cas1 ENTRYPOINT ["python3","manage.py", "runserver", "0.0.0.0:8000"] I build a image with docker build -t django-img . and then I have the following .yaml: version: '3' services: django_c: container_name: django_c image: django-img environment: - CASSANDRA_SEEDS='cas1' ports: - '8000:8000' volumes: - /mnt/c/Users/claud/docker-env/django/django_project:/django_project When I run docker-compose up -d inside django-project folder (.yml and Dockerfile are there), I get the container running, but I can't see in the host any file from the container. If I run ls in the container, however, I see all … -
ERR_EMPTY_RESPONSE - Docker-Compose - Windows -Django
I just recently moved to windows 10 from linux and am now trying to run a dockerized django web-application but with no success. I am working with docker-compose and when I run docker-compose up, I can see the container running but the browser shows the following message: This page isn’t working 127.0.0.1 didn’t send any data. ERR_EMPTY_RESPONSE I receive the same response when using 0.0.0.0 This is my Dockerfile: # pull the official base image FROM python:3 RUN mkdir /app # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies COPY ./requirements.txt /app RUN pip install -r requirements.txt # add project ADD . /app and this is my docker-compose.yml version: "3" services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:\app command: python manage.py runserver This is a windows specific issues it appears as when I run it on my linux machine, everything works fine. Previous questions on the topic indicated that it's a port mapping issue in Windows (e.g., https://stackoverflow.com/a/65721397/6713085) However, I have not been able to solve it. Do you have any suggestions? Thanks in advance for any help. -
How to query all model objects except the ones that already are in another model?
I am working on a Django application. I have 2 models relevant to the question: class Quiz(models.Model): """ Represents a Quiz for a `Module`. It will have a `name` """ name = models.CharField(max_length=200) user = models.ManyToManyField('cme.Bussines', related_name='quizes', through='UserQuiz', through_fields=('quiz', 'user')) def __str__(self) -> str: return f'{self.name}' class Trio(models.Model): """ Represents the content for a Module. Each `Trio` will have, as it's name says, 3 content fields, plus the `Module` it belongs to. It will have a `file`, a `video` (which will be a URL to a YT video), and a `quiz` (which will be key to `Quiz`) """ file = models.FileField(upload_to='legacy/classes/', max_length=254) quiz = models.ForeignKey(Quiz, on_delete=models.SET_NULL, related_name='trios', null=True, blank=True) video = models.URLField() module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='trios') user = models.ManyToManyField('cme.Bussines', related_name='trios', through='UserTrio', through_fields=('trio', 'user')) def __str__(self) -> str: return f'Trio {self.id} de {self.module}' I want to query all the Quizzes that are not in quiz field of Trio. Is there a way of doing this? -
'rest_framework_nested.routers' error in Docker only
I am trying to deploy a Django app through docker but am stumped at this problem. When I run my application locally, I have no problems but when I deploy to Docker I get this error: AttributeError: module 'rest_framework_nested.routers' has no attribute 'NestedDefaultRouter' The last lines of the stack trace looks like this: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/= /app/store/urls.py", line 13, in <module> modules_router = routers.NestedDefaultRouter(router, 'modules', lookup='module') AttributeError: module 'rest_framework_nested.routers' has no attribute 'NestedDefaultRouter' The file where the error emanates from looks like this: from django.urls import path, include from rest_framework.routers import DefaultRouter from rest_framework_nested import routers from . import views router = DefaultRouter() router.register('modules', views.ModuleViewSet, basename='modules') modules_router = routers.NestedDefaultRouter(router, 'modules', lookup='module') My Dockerfile looks as follows: FROM python:3.9.9-slim #Set up user RUN apt-get update RUN apt-get -y install sudo RUN addgroup app && adduser -system app -ingroup app USER app WORKDIR = /app #Environment settings` ENV PYTHONUNBUFFERED=1 #Install MySQL and dependencies RUN sudo apt-get -y install python3.9-dev RUN sudo … -
How to make 1:N orm? like comment
template.html view.py model.py result. I want to use filter orm in view.py. not like this. used 'if' in template.py and select all. How can I do this? And I tried use join sql. but It was not worked. -
how to customize the image filed returned by UpdateView
i use the UpdateView to update the products informations in my future webstore in my temblate . when i open my template i find a that it renders me the image link edit_product.html <form method="post"> <div class="form-group"> <label>Name</label> {{form.name}} </div> <div class="form-group"> <label>Description</label> {{form.description}} </div> <div class="form-group"> <label>Price</label> {{form.nominal_price}} </div> <div class="form-group"> <label>Image</label> <img src="{{form.instance.photo.url}}" width="200"/> </div> <div class="form-group"> {{form.photo}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> output <form method="post"> <div class="form-group"> <label>Name</label> <input type="text" name="name" value="flawless legs" maxlength="255" required="" id="id_name"> </div> <div class="form-group"> <label>Description</label> <textarea name="description" cols="40" rows="10" required="" id="id_description">Epilateur de jambes pour femmes</textarea> </div> <div class="form-group"> <label>Price</label> <input type="number" name="nominal_price" value="199" min="0" required="" id="id_nominal_price"> </div> <div class="form-group"> <label>Image</label> <img src="/media/products/images/449165_ALTMORE2.jpeg" width="200"> </div> <div class="form-group"> Currently: <a href="/media/products/images/449165_ALTMORE2.jpeg">products/images/449165_ALTMORE2.jpeg</a><br> Change: <input type="file" name="photo" accept="image/*" id="id_photo"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> what should i do to remove this Currently: <a href="/media/products/images/449165_ALTMORE2.jpeg">products/images/449165_ALTMORE2.jpeg</a><br> -
Django form regrouping - How can I regroup a field form queryset like I would do in a template?
I have a Django form for a model called AvailabilityRequested that has a ManyToMany with another model called Event. class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField(blank=True, null=True) ... class AvailabilityRequested(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event = models.ManyToManyField(Event, blank=True) position = models.OneToOneField(JobPosition, blank=True, on_delete=models.CASCADE, related_name='availability_requested', null=True) class AvailabilityRequestedForm(forms.ModelForm): class Meta: model = AvailabilityRequested fields = ['event'] def __init__(self, *args, **kwargs): self.project = kwargs.pop('project') super(AvailabilityRequestedForm, self).__init__(*args, **kwargs) self.fields['event'].widget = CheckboxSelectMultiple() self.fields['event'].to_field_name = "event_name" #event.event_name.name self.fields['event'].queryset = self.project.jobproject_events.order_by('date') I built the form and it works fine, however I am trying to now render the events in the AvailabilityRequestedForm in a specific way inside my template and that's where the problem arise. Specifically, my goal is to basically display the events grouped by date like in the picture attached. I originally managed to do achieve my goal when I wasn't using forms but just passing to the template a queryset of dates as follow context['dates'] = project.jobproject_events.order_by('date') and then using the following template logic. {% regroup dates by date as event_by_date %} <thead> <tr> {% for date in event_by_date %} <th colspan="{{ date.list | length }}" scope="col" style="border-right: 1px solid black; text-align: center;"> {{ date.grouper }}</th> {% endfor %} </tr> … -
Django Model Property in Async Function Called from Sync View
I need to convert some of my Django views to work with async functions that query data sources. I'm experiencing big performance issues as those queries are executed one by one in series. However, the task is much harder than anticipated. I've indicated below where the problems start. I'm experiencing other problems as well, however, this is by far the one that I don't have a clue on what to do. I get the following error where indicated in the code below: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async model2 is a ForeignKey property pointing to another Model. Wrapping model1.model2 inside sync_to_async() does not work. Any idea how to make this work ? async def queryFunctionAsync(param1, param2, loop): model1 = await sync_to_async(Model1.objects.get)(pk=param1) model2 = model1.model2 # This is where the error is generated def exampleView(request): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) data = async_to_sync(queryFunctionAsync)(param1, param2, loop) loop.close() -
How can I separate categories in different pages in Python and Django?
I need help with my e-commerce website project. I will have 5 categories in the dropdown menu. I want to see different categories on different pages when I click on a category in a dropdown menu. Now I see all products on the home page and when I click on a category as BOOKS I see books on the home page but I don't want it. I want to use the home page for ads and when I click on a category, I want to see it on a different page. How can I separate them? My models: class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('products_by_category', args=[self.slug]) def __str__(self): return str(self.name) # Model: Product # Model: Cart class Add(models.Model): image = models.ImageField(upload_to='add', blank=True) image1 = models.ImageField(upload_to='add', blank=True) image2 = models.ImageField(upload_to='add', blank=True) class Meta: verbose_name = 'add' verbose_name_plural = 'adds' def __str__(self): return str(self.image) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) image1 = models.ImageField(upload_to='product', blank=True) image2 = models.ImageField(upload_to='product', blank=True) image3 = models.ImageField(upload_to='product', blank=True) … -
How to make a left join in django queryset
I have two models and I need to do a left join operation I tried some solutions, but wihout success yet Models class SmdRepairIn(models.Model): sum_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) model_code = models.CharField(max_length=20, blank=True, null=True) class SmdRepairOut(models.Model): repair_in_id = models.CharField(max_length=20, blank=True, null=True) repairman_out = models.CharField(max_length=30, blank=True, null=True) SMDRepairIn.id == SmdRepairOut.repair_in_id I want to retrieve the correspondent query result: select A.*, B.repairman_out from SmdRepairIn as A left join (select repairman_out from SmdRepairOut) B on (A.id = B.repair_in_id ) How to do it in django queryset? The expected result should be: id, sum_ymd, line_nm, model_code, repairmain_out -
How can I get image table with main table?
view.py q = Q() q &= Q(user_idx = request.user.id) portfolio_list = UserPortfolio.objects.filter(q).order_by('-idx') q &= Q(portfolio_idx = portfolio_list.values('idx')) portfolio_img_list = UserPortfolioFile.objects.filter(q).order_by('-idx') model.py class UserPortfolio(models.Model): idx = models.AutoField(primary_key=True) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) subject = models.CharField(max_length=255) client_name = models.CharField(max_length=255) client_service = models.CharField(max_length=255) client_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() content = models.TextField() write_date = models.DateTimeField(auto_now = True) update_date = models.DateTimeField(auto_now = True) is_file = models.CharField(max_length=1) class Meta: managed = False db_table = 'account_user_portfolio' def portfolio_upload_to(instance, filename): nowDate = datetime.now().strftime("%Y/%m/%d") return '/'.join([str(instance.portfolio_idx.user_idx), instance.folder , nowDate, filename]) class UserPortfolioFile(models.Model): idx = models.AutoField(primary_key=True) portfolio_idx = models.ForeignKey( UserPortfolio, db_column='portfolio_idx', on_delete=models.CASCADE ) folder = 'portfolio' file = models.ImageField(upload_to=portfolio_upload_to) class Meta: managed = False db_table = 'account_user_portfolio_file' I want to get image in my image table. ex)I want to get portfolio_idx 1 to list in template But I don't know how to get. Maybe I think that is almost done. right? If not please answer. -
REACT-DJANGO Post form to an API 400 error strict-origin-when-cross-origin
I'm having a problem where when I try to post a FORM to my API it gives me this error. Request URL: http://localhost:8000/api/ Request Method: POST Status Code: 400 Bad Request Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin I did follow a tutorial to create the API and I think that may be the problem I don't even know where to start looking! I don't know where I'm messing up at and it's really frustrating! This is my REACT Post form page import axios from "axios"; import { useState, useEffect } from "react"; import { useHistory } from "react-router"; import "./createpost.css"; const CreatePost = () => { const [username, setUsername] = useState(""); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [image, setImage] = useState(null); const [category, setCategory] = useState(""); const history = useHistory(); const AddPost = async () => { let formField = new FormData(); formField.append("title", title); formField.append("description", description); formField.append("category", category); if (image !== null) { formField.append("image", image); } await axios({ method: "post", url: "http://localhost:8000/api/", data: formField, }).then((response) => { console.log(response.data); history.push("/"); }); }; useEffect(() => { if (localStorage.getItem("token") === null) { } else { fetch("http://127.0.0.1:8000/api/v1/users/auth/user/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem("token")}`, }, }) … -
ASGI is slower than WSGI in Django Rest Framework
When I switch from WSGI to ASGI, my server Response per second (RPS) drops by more than half. I think I misunderstood how ASGI should be implemented In the docker-compose file with WSGI services: web: container_name: djangoRestFramework command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 -w 6 In the docker-compose file with ASGI services: web: container_name: djangoRestFramework command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 6 -k uvicorn.workers.UvicornWorker The post request that I am testing against @api_view(('POST',)) def some_post_request(request): serializer = serializer_class(data=request.data) if serializer.is_valid(): address = serializer.validated_data['somedata'] result = some_function.delay(address) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) Can someone please highlight what I did wrong? -
Create a zip file that contain a pdf file (static location) - Python django windows
The title says it all.. I have a django based application and already find a way to generate the Models database into pdf. And now, I am having a difficulties to create a zip of PDF file, that can be download by the user.. To be honest, I already try and look several threads and still confused how to do it. Could someone help me? Any positive comment will be appreciated -
How to remove arrows from Django integerField without maintaining the only number input feature?
forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() registration = forms.IntegerField(label='Registration Number') class Meta: model = User fields = ['username', 'email','registration','password1', 'password2'] How can I remove the up and down arrows from the registration field? P.S. I want to only allow the user to input numbers in this field.