Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Relate an object to another using views, serializers and foreign key
Basically I have two models with one-to-one relationship. And I want retrieve information from one, when I call the other. My models: class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class CurrentAccount(models.Model): customer_account = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_account', blank=True, null=True) balance = models.FloatField() So I can just call an POST and create an Customer, that customer will have id, first_name and last_name. For now everything is working. But when I try to call my endpoint to create an CurrentAccount informing my Customer to relate, nothing happens. My input: { "customer_account": 1 #this is some id from an Customer that is already created, "balance": 0.0 } The output that I expected: { "id": 42, "customer_account": { "id": 2, "first_name": "Michele", "last_name": "Obama" } "balance": 0.0 } The output that I received: { "id": 4, "balance": 0.0 } As you can see, Django are ignoring the relationship (In the database the field 'customer_account_id' is null too, so isn't just an problem with my return). Here is my serializers: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'first_name', 'last_name') class CurrentAccountSerializer(serializers.ModelSerializer): customer_account = CustomerSerializer(read_only=True) class Meta: model = CurrentAccount fields = ('id', 'customer_account', 'balance') And my views to create the CurrentAccount: @api_view(['GET', … -
AUTH_USER_MODEL refers to model 'account_account.CustomUser' that has not been installed
I have checked solutions for the issue for two days only with failures. I have defined a customUser in my model.py to create a login system with email. The code snippet from the model is as following. class CustomUser(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ("username", ) def __str__(self): return self.username also installed my app in settings.py added AUTH_USER_MODEL INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ............. AUTH_USER_MODEL = "account.CustomUser" When I ran the migrations I got the following error: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 270, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\my_env\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", line 213, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "F:\Ecom\my_env\lib\site-packages\django\apps\config.py", line 272, in get_model raise LookupError( LookupError: App 'account' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Ecom\ecomProject\manage.py", line 22, in <module> main() File "F:\Ecom\ecomProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "F:\Ecom\my_env\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "F:\Ecom\my_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "F:\Ecom\my_env\lib\site-packages\django\apps\registry.py", … -
How to get total number
Kindly guild me on how to get the total number of loved clicked. See my attempt below, but it is not working. This is my model: class Review(models.Model): reviewer = models.ForeignKey(User, related_name='review', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='review', on_delete=models.CASCADE, null=True) date_time = models.DateTimeField(auto_now_add=True) comment = models.TextField(max_length=250, blank=True, null=True) rating = models.CharField(choices=RATING_CHOICES, max_length=150) loved = models.BooleanField(default=False) This is my view: class ListReviewAPIView(generics.ListAPIView): queryset = Review.objects.filter(loved="True").count() serializer_class = ReviewSerializers The serializers class ReviewSerializers(serializers.ModelSerializer): class Meta: model = Review fields = ['product', 'comment', 'rating', 'loved', 'date_time', 'reviewer'] -
SQL data base in Django
Please i have some issues if anyone can help me. I have an SQL data base (SSMS) with different tables contains data that i need for create reporting web application. I'll work with Django/python . But i noticed that in settings Django support just mysql,oracle,sqlite or postgres and there isn't SQL! How i can connect to my Data base SQL to get the data ? I tried many solutions from stackoverflow but doesn't work! Thanks in advance Settings file: DATABASES={ ENGINE :'sql_server.pyodb', PS: for enging i tried mssq too ERROR: django.core.exceptions.ImproperlyConfigured: 'mssql' 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' -
Nested Serializers - how to access attrs from serializer's field during validate
I created nested serializers and during validate method in parent serializer I don't have any data from child serializer. When i raise error with 'attrs' as message then i get only data from 'pk' and 'name' fields. How can i get data from OpenningTimeSerializer in WarehouseSerializer? serializers.py class OpenningTimeSerializer(serializers.ModelSerializer): class Meta: model = OpenningTime fields = ['weekday', 'from_hour', 'to_hour'] class WarehouseSerializer(serializers.ModelSerializer): openning_time = OpenningTimeSerializer(many=True) class Meta: model = Warehouse fields = ['pk', 'name', 'openning_time'] def validate(self, attrs): raise serializers.ValidationError(attrs) -
interdicting django admin page except superuser
I made a web application called contact and I want to make it so that no one except the superuser can enter the admin page even by entering the url and after entering the url like : 127.0.0.1:800/admin then show them a 404 page or redirect to the home page. please help me !!! -
Get list of values from object in FastApi
I want to get list of values on a query instead of objects. Coming from a Django World I want to get something like values = list(MyModel.objects.filter(data=data).values('field_1', 'field_2')) Which would directly coming me something like values = [ { 'field_1': 'data_1', 'field_2': 'data_2' }, { 'field_1': 'data_1', 'field_2': 'data_2' } ] -
How to access a Uvicorn web server with it's domain name rather than it's IP address and port number?
I use uvicorn and Django to run an ASGI application and I would like to access the web server with it's domain name. I create a A record in the DNS server to point to the correct IP address and it is now reachable with http://my-domain.com:8000 How can I tell him to accept the URL without the port number ? The desired URL is http://my-domain.com This is how I run the server with systemd: uvicorn myapp.asgi:application --host 0.0.0.0 --port 8000 --lifespan off settings.py ALLOWED_HOSTS=['my-domain.com', '1.22.333.332'] Firewall rules : (env) user@ubuntu-1cpu-2gb-pl-waw1:/var/www/myapp$ sudo ufw status Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 8000 ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) -
Django importing excel in not good format
I am a starting programmer and I need to create a site in django, with the ability to add an excel file, where some columns are merged, there is a header and convert it to a normal view. Can anyone please tell me some advices/books/paccages, that can help me to do this? The example of excel file in the screen below image Thank you very much! -
TypeError at /admin/ , 'QueryDict' object is not callable
I am getting this error when i am check this validation ,in django forms , how i can solve this error form.py d=[] b=[] my_tuple = [] for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) d.append((start_new,start_old)) b.append((end_new,end_old)) my_tuple.append((d[0],b[0])) for i in my_tuple[0]: my_result = [sub for sub in i if all(element >= 0 for element in sub)] if len(my_result)>2: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
I can only login with an administrator account but I need to do it with a custom user model
Users can register without any problem, but they cannot login, only a super user Im using a custom user model, so i can login with just the email and the password, i already tried using the django build-in templates for login but they doesn't work, it give the same error When i try to login as a normal user, it gives me this error <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Invalid login</li></ul></li></ul> My models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=150, unique=True) username = models.CharField(max_length=150, unique=True) # password = models.CharField(max_length=150) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def … -
Why doesn't Azure show me my design files CSS, HTML, JavaScript
When I enter the command: 'az webapp up' My Django/Python site appears but with no design at all. When I enter the command: 'python manage.py runserver' in the terminal, the app works as usual with the design. Am I missing a command? Or maybe something in the settings is not correct? -
Django admin inlines: single inline for multiple foreign keys
I have a model that stores Conversations as follows: class Conversation: sender_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_starter_user") recipient_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_recipient_user") It references the User model twice. I would like to be able to go to Django Admin and see a section called 'Conversations' that would list all conversations that the user participates in, both as a starter and as a recipient. Currently, I am creating two separate inlines ConversationRecipientInline and ConversationSenderInline that I add to the User admin. This splits the Conversation view into two which is not ideal. -
Attempting to Bulk Update A Priority List - DRF
I'm attempting to Bulk Update my entire priority list. Here's the model: class OrderPriority(models.Model): order = models.OneToOneField(Order, related_name='priority_order', on_delete=models.CASCADE) priority = models.BigIntegerField(unique=True) Here's my Bulk Update Serializer and List Serializer Class: class BulkPriorityUpdateListSerializer(serializers.ListSerializer): def update(self, instances, validated_data): instance_hash = {index: instance for index, instance in enumerate(instances)} result = [ self.child.update(instance_hash[index], attrs) for index, attrs in enumerate(validated_data) ] writable_fields = [ x for x in self.child.Meta.fields if x not in self.child.Meta.read_only_fields ] try: self.child.Meta.model.objects.bulk_update(result, writable_fields) except IntegrityError as e: raise ValidationError(e) return result def to_representation(self, instances): rep_list = [] for instance in instances: rep_list.append( dict( id=instance.id, order=instance.order.id, priority=instance.priority, ) ) return rep_list class BulkOrderPrioritySerializer(serializers.ModelSerializer): class Meta: model = OrderPriority fields = ("id", "order", "priority") read_only_fields = ("id",) list_serializer_class = BulkPriorityUpdateListSerializer Here's my view along with the custom bulk update view: class CustomBulkUpdateAPIView(generics.UpdateAPIView): def update(self, request, *args, **kwargs): def validate_ids(data, field="id", unique=True): if isinstance(data, list): id_list = [int(x[field]) for x in data] if unique and len(id_list) != len(set(id_list)): raise ValidationError("Multiple updates to a single {} found".format(field)) return id_list return [data] ids = validate_ids(request.data) instances = self.get_queryset(ids=ids) serializer = self.get_serializer( instances, data=request.data, partial=False, many=True ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) class OrderPriorityUpdateAPIView(CustomBulkUpdateAPIView): serializer_class = BulkOrderPrioritySerializer def get_queryset(self, ids=None): return OrderPriority.objects.filter( id__in=ids, ) I then … -
How to define headers for authorization in django testing?
I want to write a test case for a function in my views in my Django project. I am just a beginner in this field, I have changed my settings.py and added the below line of code to the DATABASES dictionary, and also create a new user using MySQL shell based on this post: 'TEST': { 'NAME': 'test_sepantadb', } In function, there is a try/catch for checking the authorization using the request.headers. Here is the API code: @api_view(['GET']) def Get_users(request, **kwargs): try: user = request.headers['Authorization'] p = Profile.objects.get(username=user) except Exception as e: print(e) return Response(status=status.HTTP_401_UNAUTHORIZED) users = Device.objects.filter(owner=p) res = [] for u in users: user_inf = {} try: pdm = PersonDeviceMapper.objects.filter(device=u)[0] prof = pdm.person user_inf['name'] = prof.name user_inf['username'] = prof.username except Exception as e: print(e) user_inf['name'] = u.name user_inf['username'] = "default_" + str(u.id) user_inf['created_at'] = u.created_at user_inf['id'] = u.id user_inf['device_id'] = u.device_id res.append(user_inf) return Response(res) And here is the code in models.py for Profile class: class Profile(models.Model): GENDER_MALE = 1 GENDER_FEMALE = 2 GENDER_CHOICES = [ (GENDER_MALE, _("Male")), (GENDER_FEMALE, _("Female")), ] code = models.IntegerField(null=True, blank=True) username = models.CharField(max_length=128, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) lastname = models.CharField(max_length=50, null=True, blank=True) birthday = models.DateField(null=True, … -
How to make django_cron works in setted time
I have the following code: class ChangeStatusJob(CronJobBase): hours = [f"{str(el).zfill(2)}:30" if yel else f"{str(el).zfill(2)}:00" for el in range(0, 24) for yel in (0, 1)] schedule = Schedule(run_at_times=hours) code = "project.cron.ChangeStatusJob" def do(self): pass Cron doesn't work at a time which in run_at_times value and as a result, he works with a default 5 min delay. How to fix it? PS. cron should work every hour at **:00 and **:30 -
Unable to open unix socket in redis - Permission denied while firing up docker container
I am trying to fire up a separate redis container which will work as a broker for celery. Can someone help me with as to why the docker user is not able to open the UNIX socket. I have even tried making the user as root but it doesn't seem to work. Please find below the Dockerfile, docker-compose file and redis.conf file Dockerfile FROM centos/python-36-centos7 USER root ENV DockerHOME=/home/django RUN mkdir -p $DockerHOME ENV PYTHONWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH=/home/django/.local/bin:$PATH COPY ./oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm /home/django COPY ./oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm /home/django COPY ./oracle.conf /home/django RUN yum install -y dnf RUN dnf install -y libaio libaio-devel RUN rpm -i /home/django/oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm && \ cp /home/django/oracle.conf /etc/ld.so.conf.d/ && \ ldconfig && \ ldconfig -p | grep client64 COPY ./requirements /home/django/requirements WORKDIR /home/django RUN pip install --upgrade pip RUN pip install --no-cache-dir -r ./requirements/development.txt COPY . . RUN chmod 777 /home/django EXPOSE 8000 ENTRYPOINT ["/bin/bash", "-e", "docker-entrypoint.sh"] Docker-compose file version : '3.8' services: app: build: . volumes: - .:/django - cache:/var/run/redis image: app_name:django container_name: app_name ports: - 8000:8000 depends_on: - db - redis db: image: postgres:10.0-alpine volumes: - postgres_data:/var/lib/postgresql/data ports: - 5432:5432 environment: - POSTGRES_USER=app_name - POSTGRES_PASSWORD=app_password - POSTGRES_DB=app_db labels: description : "Postgres Database" container_name: app_name-db-1 redis: image: … -
A state mutation was detected between dispatches
I've got this issue which I do not understand. I am getting an invariant error that says a state mutation has occurred, but at a very awkward place. Basically I've got this page: import React, { useState, useEffect } from "react"; import { Link, useLocation, useNavigate, useSearchParams, } from "react-router-dom"; import { Form, Button, Row, Col, Table } from "react-bootstrap"; import { LinkContainer } from "react-router-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loader from "../components/Loader"; import Message from "../components/Message"; import FormContainer from "../components/FormContainer"; import { register } from "../actions/userActions"; import { getUserDetails, updateUserProfile } from "../actions/userActions"; import { USER_UPDATE_PROFILE_RESET } from "../constants/userConstants"; import { listMyOrders } from "../actions/orderActions"; function ProfileScreen() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [message, setMessage] = useState(""); const dispatch = useDispatch(); const location = useLocation(); const userDetails = useSelector((state) => state.userDetails); const navigate = useNavigate(); const { error, loading, user } = userDetails; const userLogin = useSelector((state) => state.userLogin); const { userInfo } = userLogin; const userUpdateProfile = useSelector((state) => state.userUpdateProfile); const { success } = userUpdateProfile; const orderListMy = useSelector((state) => state.orderListMy); const { loading: loadingOrders, error: errorOrders, … -
How to test dynamically changing parameters within an sql query to the database using pytest
Function to test def get_adgroups_not_taked_share( campaign_ids: List[str], src_table: str, spend_src_table: str ) -> List[Tuple[str, str]]: start_date = ( date.today() - timedelta(days=get_redshift_query_param_value('start_date')) ).strftime('%Y-%m-%d') end_date = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d') loses_adgroups: List[Tuple[str, str]] = [] with RedshiftCursor() as cursor: cursor.execute( """ SELECT ad_group, spends.campaign_id, ad_spend FROM ( SELECT ... SUM(spend_eur) AS ad_spend FROM %(src_table)s WHERE ...... ) as spends LEFT JOIN (SELECT ... AS total_spend FROM %(spend_src_table)s GROUP BY campaign_id, spend_eur ) AS sg ON ... WHERE ad_spend * 100 / %(cutoff_percent)s < total_spend """, { 'campaign_ids': tuple(campaign_ids), 'start_date': start_date, 'end_date': end_date, 'cutoff_percent': get_redshift_query_param_value('cutoff_percent'), 'src_table': AsIs(src_table), 'spend_src_table': AsIs(spend_src_table), }, ) for row in cursor.fetchall(): loses_adgroups.append((row[0], str(row[1]))) return loses_adgroups Within it, the function get_redshift_query_param_value is called def get_redshift_query_param_value(param: str) -> int: params = { 'cutoff_percent': RedshiftQuery.CUTOFF_PERCENT, 'min_place': RedshiftQuery.MIN_PLACE, 'start_date': RedshiftQuery.START_DATE, } return int(RedshiftQueryParam.objects.get(name=params[param]).value) which retrieves a numeric value from the databases based on the key passed in. Wrote a test that wets the database access and the return value test.py import pytest from google_panel.logic.clean_creative import get_adgroups_not_taked_share @pytest.fixture def campaigns_redshift_cursor_mock(mocker): cursor_mock = mocker.MagicMock() cursor_mock.fetchall.return_value = [ ('hs_video544', '123123123', 100), ('hs_video547', '123123123', 50), ] rs_cursor_creator = mocker.patch('google_panel.logic.clean_creative.RedshiftCursor') rs_cursor_creator.return_value.__enter__.return_value = cursor_mock return rs_cursor_creator @pytest.fixture def get_redshift_query_param_value_mock(mocker): return mocker.patch('google_panel.logic.clean_creative.get_redshift_query_param_value') @pytest.mark.django_db def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, get_redshift_query_param_value_mock): campaign_ids = ['1111', '2222', … -
Django storages: Need authenticated way of reading static files from google cloud storage
I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public. Developer console: Networks tab And because of which I am getting a broken Django admin UI. Broken Django admin UI Here's my static file settings in settings.py file. STATIC_URL = "/static/" if DEPLOYED_URL: DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = env("GS_BUCKET_NAME") GS_CREDENTIALS = service_account.Credentials.from_service_account_info( json.loads(get_secret(PROJECT_NAME, "service_account_json")) ) GS_DEFAULT_ACL = "projectPrivate" My restrictions are I have Fine-grained: Object-level ACLs enabled bucket on which public access cannot be given. PS: Since there are restrictions to the project I cannot use a public bucket. Alternate ways other than the usage of django-storages package are also appreciated. The only condition is reads should be authenticated and not public. -
How to refresh page for new request in Django
I want to receive a request.POST values N times, where N is a number entered by the user. The views.py is: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): form=Form(request.POST) c = int(request.POST.get('peso_u')) d = int(request.POST.get('preco_u')) peso_unitario.append(c) preco_unitario.append(d) return render(request, 'valores.html') return render(request, 'pacote_m.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) In this code in the end I have two returns, where the first is inside the for loop because I want to receive the values N times and return them to the template "valores.html". The last return is in the end, after the for loop will redirect to a new template, this template "pacote.html" will show the values calculated according to I programmed, but it isn't the problem. The template valores.html is: {% extends 'basic.html' %} {% block content %} <form action="page2" method="GET"> {% csrf_token %} <h1>Digitados:</h1> numero de objetos={{n_objetos}}<br> peso peso maximo={{peso_maximo}}<br> <!--- Peso unitario: <input type="text" name="peso_u"><br><br> Preco unitario: <input type="text" name="preco_u"><br><br> ---> <table> <thead> <tr> <th>Peso unitario</th> <th>Preco unitario</th> </tr> </thead> <tbody> <tr> <td><input type="text" name="peso_u"></td> {{form.peso_u}} <td><input type="text" name="preco_u"></td> {{form.preco_u}} </tr> </table> <input type="submit"> </form> {% endblock %} My forms.py is: class Form(forms.Form): peso_u=forms.CharField(max_length=50) preco_u=forms.CharField(max_length=50) The problem is I can't get the N … -
can we use prefetch_related with many-to-many relationship in django
hey guys let's say i have models like this class CouponCode(models.Model): ...... class Product(models.Model): codes = models.ManyToManyField(CouponCode) how can I use perefetch_related with reverse many to many relationships I did this and I looked at the queries and I found i didn't make a query for the second table CouponCode.objects.all().perefetch_related('product_set') -
how to stop ajax waiting for its response after sending request
def openFile(request): record = Verification.objects.filter(farmRegNo= request.POST['farmRegNo']) filepath = os.path.join('', str(record[0].certificate)) # not working line #return FileResponse(open(filepath, 'rb'), content_type='application/pdf') return HttpResponse(Respon) This is code using django, since i call this openFile() by ajax, i cant work for FileResponse, it only expects HttpResponse, I want to open this file....is there any way to do this??? -
Incorrect display of children's models on the form in django
I tried to make a creation form for vacancy on my job search site, but i faced with problem. I have User model, company model and vacancy model. They are inherited by foreignkeys. And the problem is that user can use all companies for creation a vacancy instead of created by this user companies(User can create several companies). I tried to change creation form and view by filtering, but it didn't work out for me. I am new at django and i dint find anything to resolve my problem. Model of company: class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(('Title of Shop'), blank=True, max_length=255) info = models.TextField(('Information about Shop'), null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) Model of vacancy: class Vacancies(models.Model): title = models.CharField(('Title of Vacancy'), blank=True, max_length=255) city = models.ForeignKey(City, on_delete=models.CASCADE, default='363') description = models.TextField(('Information about Vacancy'), null=True, blank=True) employer = models.ForeignKey(Company, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return str(self.title) Create vacancy view: @login_required(login_url='login') def createVacancy(request): form = VacanciesForm() cities = City.objects.all() if request.method == 'POST': form = VacanciesForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form, 'cities': cities} return render(request, 'vacancy_form.html', context) … -
can't get data from Django to html
//views.py def index(request): if request.method == 'POST': data = request.POST['data'] context = {'mydata': data} return render(request, 'home/index.html', context) else: html_template = loader.get_template('home/index.html') HttpResponse(html_template.render(request)) //index.html <form method = 'POST' id = 'post-form'> <select name = 'data' id = 'data'> <option> 1 </option> <option> 2 </option> </select> <button type="submit" name = 'post-form'> submit </button> </form> <h2> {{ mydata}} </h2> // this line print nothing. When I click the submit button, I can access data from html submit in views.py. However, I can't access 'mydata ' from dajngo in html. how can i solve it?