Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inspect oracle database without primary key in django
command: python .\manage.py inspectdb --database=ORACLE > models.py This command run successfully. But models.py output is # Unable to inspect table 'acc_advance_other_adj_dt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier # Unable to inspect table 'acc_ari_entries_dt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier # Unable to inspect table 'acc_asset_mt' # The error was: ORA-00904: "USER_TAB_COLS"."IDENTITY_COLUMN": invalid identifier -
{% for top in topwear.brand %} is not executing
I want to list the items by brand so user can choose according to the brand of the product in the sidebar but somehow it is not happenning `your text`` views.py class home(View): def get (self,request): products=Product.objects.all() topwear=Product.objects.filter(Category='TW') bottomwear=Product.objects.filter(Category='BW') context={'topwear':topwear,'bottomwear':bottomwear,'products':products} return render(request,'store/index.html',context) models.py your text class Product(models.Model): category=[ ('TW','Top Wear'), ('BW','Bottom Wear'), ('Shoes','Shoes'), ('mobile','mobile'), ('Laptop','Laptop') ] title=models.CharField(max_length=100) selling_price=models.FloatField() discounted_price=models.FloatField() description=models.TextField() brand=models.CharField(max_length=100) Category=models.CharField(choices=category,max_length=10) product_image=models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) Bottom wear and mobile section is showing but not topwear section. index.html your text <div class="dropdown-menu position-absolute bg-secondary border-0 rounded-0 w-100 m-0"> {% for top in topwear.brand %} <a href="{% url 'searchproduct' top %}" class="dropdown-item">Top Wear</a> {% endfor %} <a href="" class="dropdown-item">Bottom Wear</a> <a href="" class="dropdown-item">Mobile</a> </div> Everything else is running file .Just top wear section is not showing in browser. Is this syntax not correct? Help will be appreciated -
how can i search for a keyword in order django
content = request.query_params.get('search') searchList = list(content.strip(" ")) resultLoop= Medicines.objects.filter(name__icontains=searchList[0]) for letter in searchList: resultLoop = resultLoop.filter(name__icontains=letter) this is the how I manage to get the result which contains all the letters that the keyword contains, but it is a scrambled result. ie. if am searching 'abc' from ['abcd','bcda','cdab','adbc'], it returns all the four elements because it contains all the letter that the keyword has, What I need is, only two elements which is in the actual order of the keyword. Those are ['abcd','abdc'] -
Django - Copy and edit data from one model into another
I have a 'Services' model that contains a user's templated services. I have a 'serviceSelect' model that I want to be able to copy and a template from 'Services' into the 'ServiceSelect' model which will then be related to a proposal and can be edited. I have a ServiceSelectForm that has initial dropdown data from the 'Service' model. I am trying to be able to select a 'service' from the drop-down and copy it into the 'ServiceSelect' model for later editing. When I try to do this I'm getting: Cannot assign "'a303adbb9bd4'": "Proposal.services" must be a "ServiceSelect" instance. This is what I have tried: **Service model ** There are only a few entries as these are templated services. title = models.CharField(null=True, blank=True, max_length=100) discription = models.TextField(null=True, blank=True) category = models.CharField(choices=CATEGORY, blank=True, max_length=100) quantity = models.FloatField(null=True, blank=True) price = models.FloatField(null=True, blank=True) paymentTerms = models.CharField(choices=PAYMENT, blank=True, max_length=100) salesTax = models.CharField(choices=SALESTAX, blank=True, max_length=100) uniqueId = models.CharField(null=True, blank=True, max_length=100) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(blank=True, null=True) def __str__(self): return '{} {}'.format(self.title, self.uniqueId) def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if self.date_created is None: self.date_created = timezone.localtime(timezone.now()) if self.uniqueId is None: self.uniqueId = str(uuid4()).split('-')[4] self.slug … -
Django ORM Using Dynamic Variable To Get Object Field Value
my_dict['name'] = my_model.objects.get(pk=pk).object_name I need ".object_name" to be a dynamic variable. I tried creating a variable and adding it to the end. my_model.objects.get(pk=pk).variable_name my_model.objects.get(pk=pk)variable_name etc... When I try to add a variable to the end of the query it throws an error. "Object has no attribute 'variable_name'". "Statements must be separated by a new line or semicolon." I'm sure there must be some other way to write this but I can't find any information to achieve this. -
How to fix type 'Null' is not a subtype of type 'Map<dynamic, dynamic>' in type cast error
Hi I am new to flutter & dart. I am trying to get the api of Django Rest Framework using the following test.dart import 'dart:convert'; import 'package:http/http.dart' as http; // var response = await http.get(Uri.parse("http://127.0.0.1:8000/")); // print(response.body); Future<void> main() async { final response = await http.get(Uri.parse("http://127.0.0.1:8000/api/Username/items/")); final decoded = jsonDecode(response.body) as Map; final data = decoded['data'] as Map; print(data['name']); for (final name in data.keys) { final value = data[name]; print('$name,$value'); } } Here is the api.views @api_view(['GET']) def getItem(request, **kwargs): user = get_object_or_404(User, username=request.user) items=Item.objects.filter(user=user) serializer = ItemSerializer(workouts, many=True) return Response(serializer.data) Here is the api/urls: path('<str:username>/workouts/',views.getWorkout, name='api_workout'), Here is the serializer.py class ItemSerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Workout fields = '__all__' I am not sure why I am getting: Unhandled exception: type 'Null' is not a subtype of type 'Map<dynamic, dynamic>' in type cast #0 main bin\test.dart:11 <asynchronous suspension> My question: Why am i getting this error and how can I get access to the api json in the mentioned http -
Subscription System IAP using some language of backend
I want to create a management subscription IAP for my app in Flutter, I don't want to use renewcat or other like that. I want to create my own backend Manager What is the best option for create faster? and what do I need, this system is like to a CRUD? exist some Api or tools for make easy this work? Sorry for my doubt, I tried looking information about but I didn't found nothing. -
python sleep for second to throttle requests
I have a celery periodic task which has a function call inside it i need to make the code sleep for a second for every 20 emails sent how can i achieve that. @app.task(bind=True) def send_email_reminder_on_due_date(self): send_email_from_template( subject_template_path='emails/subject.txt', body_template_path='emails/template.html', template_data=template_data, to_email_list=email_list, fail_silently=False, content_subtype='html' ) i have some condition before send_email_from_template i.e fetching records from database whose due_date is today and i will be sending email for all the records which i fetch let's say i have 30 records for which i need to send an email to so i would do sleep for 1 second after the email function gets executed for 20 records. -
Celery does not start when running on docker with Django, RabbitMQ with docker-compose
I have a docker-compose that contains the the following components: django, rabbitmq and celery. However for whatever reason, my celery itself does not seem to be starting. When i use the frontend to send a task (which should pass to celery), it fails. This is my docker-compose file version: "3.9" services: django: build: context: . args: build_env: production ports: - "8000:8000" command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code links: - rabbitmq - celery rabbitmq: container_name: rabbitmq restart: always image: rabbitmq:3.10-management ports: - "5672:5672" # specifies port of queue - "15672:15672" # specifies port of management plugin celery: container_name: celery restart: always build: context: . args: build_env: production command: - "celery worker -A kraken.celery -l info" depends_on: - rabbitmq Dockerfile ARG PYTHON_VERSION=3.9-slim-buster # define an alias for the specfic python version used in this file. FROM python:${PYTHON_VERSION} as python # Python build stage FROM python as python-build-stage ARG build_env # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and … -
Using django forms with separate models for labels and fields
I apologize in advance if this ends up sounding cryptic... I'm building a site using Django where users can select a topic from a list and then fill out a form that contains questions specific to that topic. I have 2 models: the Topic model is for the different topics and contains the specific questions for each. The Answers model is for the answers that are submitted in the form. The Answers model is linked to the Topic model with a foreign key. I currently have everything working the way that I want it to, but very messily. I am using purely html forms, and each input label is populated with the question text saved in the Topic model. What I am doing is running JavaScript when the form is submitted, querying all the form fields, and then using fetch to send a POST request with all the field text. Then in my views.py, I receive the request, get all the data, and save a new instance of the Answers model. I'm not well versed in form security, other than knowing to use a csrf token. Out of consideration for any SQL injection vulnerabilities, I started doing some research and … -
How to redirect http://127.0.0.1:8000/ to login page if the user is not logged in
In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/ I have tried different answers but nothing specific lead to this answer: Here is the login view after login: class LoginView(LoginView): template_name = 'login.html' def get_success_url(self): user=self.request.user.username return f'/{user}/' Here is the login urls: path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'), Here is the home views: class home(LoginRequiredMixin, ListView): model = Item template_name = 'app/home.html' context_object_name = 'items' Here is the app urls: path('<str:username>/', home.as_view(), name='home'), My question: How to redirect home page to http://127.0.0.1:8000/username/ if user is logged in and if not to login page -
Django tests not isolated when testing authentication
I am testing my authentication with the django.test.Client and two tests cases fail because once I test my test_login_success test case, the other tests fail because the user remains authenticated, even when I am instantiating a new client in the class setUp and even deleting the user in the tearDown. My code: from django.test import Client, TestCase from app.users.models import User class TestLogin(TestCase): def setUp(self): super().setUp() self.email = 'test@test.com' self.password = 'SomeRandomPass96' User.objects.create_user(email=self.email, password=self.password) self.client = Client() def tearDown(self): User.objects.filter(email=self.email).delete() super().tearDown() def test_not_authenticated(self): # success the first time, fails after test_login_success is executed for the first time. user = User.objects.get(email=self.email) assert not user.is_authenticated def test_login_success(self): # always success self.client.post( '/users/login/', {'email': self.email, 'password': self.password} ) user = User.objects.get(email=self.email) assert user.is_authenticated def test_login_wrong_credentials(self): # success the first time, fails after test_login_success is executed for the first time. self.client.post( '/users/login/', {'email': self.email, 'password': 'wrongPassword123'} ) user = User.objects.get(email=self.email) assert not user.is_authenticated -
DJANGO + ReactJS | Error when the response is not 200
Getting the below error when sending a 401 (un-authorized) response. As per the error, when I change it to 200, it works well. But here I need to send 401 itself. Access to fetch at 'http://127.0.0.1:8888/employees/api/fetch/home/data/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Frontend : ReactJS Backend : Django Any help would be greatly appreciated. -
Django Dynamic URL from Forms
TL;DR - I failed implementing dynamic urls for too long. My plan is: Whenever the form is submitted, it would redirect you to a page (with a pk as the url), that sums up your choices. I'm aware that this was asked multiple times and I was able to implement Dynamic URLs perfectly fine with a new project. Yet, my current one is simply not making any sense to me. I have a simple form with CharField as fields. It renders them from the Models file which states pretty much the same. I added to the Models.py: > task_id = models.AutoField(primary_key=True) The form is inside "hunting.html", and you access it through the navbar: > <a class="nav-link {% if 'hunting' in segment %} active {% endif %}" href="/hunting.html"> My view is quite simple, I recently opted to Class-based (when using function-base it did not work as well): app/views.py class Hunting(LoginRequiredMixin, View): def get(self, request): form = HuntForm() print('Access Hunting') return render(request, 'home/hunting.html', {'form': form}) def post(self, request): form = HuntForm(request.POST, request.FILES) name = request.POST['name'] limit = request.POST['limit'] os = request.POST.getlist('os') mal = request.POST.getlist('mal') my_type = request.POST.getlist('my_type') if form.is_valid(): form.save() print('Hunt information is saved') return redirect('home/index.html') return redirect('home/index.html') app/urls.py: path('', views.index, name='home'), … -
Custom User class, password isn't saved from the form
I've coded my own AbstractBaseUser and BaseUserManager. Creating users and superusers via terminal works fine. But there is a problem with creating users via form. All user fields are saved properly except password field, which is blank. My models.py: from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, first_name, last_name, password, **other_fields) def create_user(self, email, first_name, last_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email And my forms.py: from django import forms from .models import MyUser class MyUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = MyUser fields = ['email', 'first_name', 'last_name'] I think there is … -
I'm receiving the error: PermissionError: [Errno 13] Permission denied: '/app/vol'
The full error: The Dockerfile: FROM python:3.9-alpine3.13 LABEL maintainer="arithmeticatuition.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/static && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] The docker-compose-deploy file: version: '3.9' services: app: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: I've tried everything from similar stack exchange requests but none seem to be working... I've rewatched lots of tutorials and I don't seem to be getting anywhere, who would've … -
How can I test the URLS for my Class Based Views in Django?
I'm trying to test the URL resolutions for my first Django project- I have successfully tested my function-based views, however I am having trouble testing my Class Based Views. I'm getting the below error when I run the test on my CBV: AssertionError: <function UpdateHealth at 0x7f538f023e50> != <HealthHub.views.UpdateHealth object at 0x7f538d7aec10> Tests.py (CBV test in question): def test_health_hub_update_url_is_resolved(self): url = reverse('HealthHub:health_hub_update') self.assertEqual(resolve(url).func, views.UpdateHealth()) views.py (view in question): class UpdateHealth(View): '''View for the Update Health page. Uses StatUpdateForm to allow the user to update their stats.''' def get(self, request, *args, **kwargs): stats = HealthStats update_form = StatUpdateForm context = { 'stats': stats, 'update_form': update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, } return render(request, 'health_hub_update.html', context) def post(self, request, *args, **kwargs): update_form = StatUpdateForm(data=request.POST) if update_form.is_valid(): obj = update_form.save(commit=False) obj.user = request.user obj.save() return redirect("HealthHub:health_hub") Urls.py: path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), Any help would be much appreciated, as I seem to have hit a dead-end. -
DJANGO: How can I create a custom User with a OneToOne relationship to Person
I have a custom user model, I would like my CustomUser model to have a OneToOne relationship with the Person model; Since I want to first register persons and then create a username for them, since not all registered people need to have a username. I have tried the code shown below; but what I get is the following error: Cannot assign "1": "CustomUser.dni" must be a "Person" instance. But, the ID number is already registered in the Person table P.S. If anyone has a better suggestion for getting people to register first and then create a username for them when strictly necessary, I'd really appreciate it. models.py from .managers import CustomUserManager class Person(models.Model): dni = models.CharField('Número de DNI', max_length=8, unique=True) ... class CustomUser(AbstractBaseUser, PermissionsMixin): dni = models.OneToOneField(Person, on_delete=models.CASCADE, unique=True) email = models.EmailField('Correo electrónico', max_length=355, unique=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'dni' REQUIRED_FIELDS = ['email'] ... managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, dni, email, password=None): if not dni: raise ValueError('Debe ingresar el número de DNI.') person = self.model( dni=dni, email=self.normalize_email(email), ) person.set_password(password) person.save(using=self._db) return person def create_superuser(self, dni, email, password=None): person = self.create_user( dni, password=password, … -
How oauth works for saving users data?
I am building simple booking app in django, so flow of the app is that user's can do a booking and then their bookings will be saved into the database, However as I'll be using oatuh in my app, So my question is if user has made a booking and I want to fetch all of the bookings user's has made how do I implement this using oauth? what data of user data do I store in my own database so that each time user login using oauth I can fetch specifically that user's data (bookings). -
Passing variable into custom template filter
I've got the following custom filter myfilters.py @register.filter def my_custom_filter(value, arg): some python stuff Within my template, I'm registering the filters {% load myfilters %} I'm then applying the template tag and then trying to pass in the variable a_template_value {{ form.body|my_custom_filter:{{a_template_value}}|safe }} I'm then getting the following error: my_custom_filterrequires 2 arguments, 1 provided Thanks! -
How to make nginx serve static files from multiple directories for django project?
I have a django project. It has static files in multiple applications, that I can put together by running python3 manage.py collectstatic. All files will be moved to the static folder, which is located in the root folder of my project. Additionally, I have 200GB pictues, located in another folder /var/images/user-profile-images/subfolder/image.jpg. In both cases image url is like so: /static/path-to-image. So in first case I have static folder, in second case I don't have. this is my location block: location ~ ^\/static\/(.*) { try_files /project-root-folder/static/$1 /var/images/user-profile-images/$1; } it is supposed to serve urls /static/style.css and /static/subfolder/image.jpg respectively, but doesn't work in both cases. I have double checked everything many times, searched around stackoverflow, but no answer. Seems it's also not possible to debug this, since nginx is not logging not found cases. Actually, I see django 404 error, so probably it does not even match. -
Django static css doesn't make any change and images don't appear
Django static files are not working in my application, I defined STATICFILES_DIRS, STATIC_URL, and STATIC_ROOT in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'social_media') ] and here's base.html: {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type= "text/css" href="{% static 'style.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock %} {% block content %} {% endblock %} </body> </html> I use this in my pages: {% extends 'base.html' %} {% load static %} {% block content %} <!--stuff--> {% endblock content %} I tried using InPrivate(incognito but MS Edge version) window and nothing changed, I also tried deleting style.css file and making it again and collecting static files again but it also didn't work. -
How can I ensure enough space is left to avoid content moving down the page if a warning message appears?
I have a server-side rendered application (Django) with a login page which provides a username and password field, submit button, instructions for forgotten password and so on. This is what I will call the "main content". Sometimes, there will an extra div above the main content with a message such as "Invalid username or password". I would like it so that if the user submits an invalid login and this message appears, the main content doesn't move. (I'm aware that this will involve leaving a white space above the main content, but there's a lot of blank space on this page anyway so it doesn't matter) I considered rendering <div class="warning-message">Invalid username or password</div> if required and some kind of placeholder <div class="placeholder"></div> otherwise, but I was struggling to style them so that the empty div would always be the same height as the warning message one. I did also consider positioning either the main content or the warning message with position:absolute, but this sometimes leads to overlapping on small screens. -
error rendering the page template when placing the site on Heroku
Good afternoon. I have a problem with a website that I posted using the Heroku platform. The error "Error during template rendering" occurred. The most interesting thing is that everything works fine on the local server. I tried to re-upload the project to Heroku, but it didn't give any results. -
Django hide password fields on user creation form
I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password. So far I haven't been able to figure out the first part - hiding the password fields. The form.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age') the view: from django.views.generic import CreateView, ListView from django.urls.base import reverse from .forms import CustomUserCreationForm, AddCompanyEmployeeForm from .models import CustomUser class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = AddCompanyEmployeeForm #success_url = reverse_lazy('directory') def get_success_url(self): return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk}) I have tried a number of approaches including changing the form to class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'full_name', 'age') So far the password fields continue to be visible regardless of what I try. Any suggestions?