Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO ADMIN ACTIONS
kindly anyone say ans to my query: (http://127.0.0.1:8000/admin/certificates/usercertificates/->) in thiz link , if i select some list it should be generate and show as pdf in django admin actions -
How to use django url in ajax?
How to call django function using ajax with id (or pk). $.ajax({ url: '{% url app:order_edit %}', type:"POST", async:false, data: {order:order, product:product, customer:customer, qty:qty, uom:uom, des:des}, success:function(data){ } }); views.py def order_edit(request, obj_id): print("Obj Id is:",obj_id) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): #operations return render(request, 'order_view.html', {'form': form}) return render(request, 'order_view.html', {'form': form}) return render(request, 'order_view.html', {}) urls.py path('orderedit/<int:obj_id>/', views.order_edit, name="order_edit"), how to call this function Anyone Help me in this issu. Thanks in advance -
Getting attribute error ='NoneType' object has no attribute 'content'
I am adding api to my views.py in my app. and facing some attribute error from django.shortcuts import render def home(request): import requests import json api_request = request.POST.get("https://min-api.cryptocompare.com/data/v2/news/?lang=EN") api = json.loads(api_request.content) return render(request, 'home.html', {"api": api}) Expected output is the data which is being fetch from the api. Getting error AttributeError at / 'NoneType' object has no attribute 'content' -
How to send notification from admin to user in Django
I am building an online shopping website using Django framework. I want to implement an order approval system where Django Admin will approve the order request from the user and at that time a notification or message will be sent to the user. Currently I have an order request model with an order status field. When the value of that field will be set approved by the admin a notification will be sent to that user. I want a push notification system here. How can I implement this in Django? -
500 internal server error when changing the db from sqlite to postgres with django and nginx
I am wondering about some things, i followed this tutorials setting up server I am currently using django 2.2, psycopg2 2.8.3, uwsgi 2.0.18. I am able to migrate models to db but the nginx server failed to communicate with it. I added local host with port 5432 to cors header. does this a permission issue, as nginx runs with a user? or it is something else? should i use https for local host in cors header allowed hosts as it is only allowed by nginx and django? -
Error when upload file CVS file in django
When I upload CSV file appeared this error enter image description here -
How to access form element in javascript function?
I'm trying to access an element in javascript function so as to autocomplete the user search, using autocomplete API. My javascript code: <script> $(function() { $("#q").autocomplete({ source: "/api/get_drugs/", minLength: 2, }); }); </script> My reference for search. My Form: <form id = "myForm" method="GET" action="{% url 'search' %}"> <input style="width:340px;height:37px;" size="30" type="text" id = 'q' name = 'q' placeholder="Search products or categories"/> <input type="submit" value="Search" > </form> Here the input target field has id and name- 'q'. -
Django: Access images via templates, stored on AWS S3
To keep performance I outsourced a machine learning task to AWS Lambda. The result are images saved in an S3 bucket. My challenge is now: How can I access these images through my .html templates? My framework is Django. <img src="s3://BUCKET_NAME/188.png" alt=""> So far I only get access denied. I could make the file public, but my initial goal was to only let my page access these files. Is there a simple solution to grant access without setting up S3Storage (I already have that, but I use a separate account for this machine learning task). -
Wagtail/Django translations not showing
I am trying to develop bilingual Wagtail site, and having problems getting translations work. Translations compiled fine to myproject/myproject/locale/fi/LC_MESSAGES/django.mo however, translations in my templates don't show. also when i do, >>> from django.utils.translation import activate >>> from django.utils.translation import get_language >>> get_language() 'en-us' >>> activate("fi") >>> get_language() 'fi' >>> ugettext("PHOTOS") 'PHOTOS' settings file: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] LANGUAGES = ( ('en', _('English')), ('fi', _('Finnish')), ) LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(PROJECT_DIR, 'locale'), ) django.po: #: .\mysite\templates\base.html:63 msgid "PHOTOS" msgstr "KUVIA" base.html: {% trans "PHOTOS" %} any ideas how to troubleshoot further? -
ImproperlyConfigured at /admin/aldryn_newsblog/article/add/
Trying to follow the tutorial for integrating Django CMS into an existing application, Im also using cookiecutter. (the "project" is my homework) After installing aldryn-newsblog I have been stuck on the following error for quite some time : ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Exception Type: ImproperlyConfigured Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Here is my backlog : Environment: Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Python Version: 3.6.8 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_awesome_project.users.apps.UsersConfig', 'djangocms_admin_style', 'django.contrib.admin', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'polls', 'polls_cms_integration', 'aldryn_apphooks_config', 'aldryn_boilerplates', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'parler', 'sortedm2m', 'taggit', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: Exception Type: ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Running : django-cms 3.6.0 Django 2.1.5 alabaster 0.7.12 aldryn-apphooks-config 0.5.2 aldryn-boilerplates 0.8.0 aldryn-categories 1.2.0 aldryn-common 1.0.5 aldryn-newsblog 2.2.1 aldryn-people 2.2.0 aldryn-translation-tools 0.3.0 … -
How to delete the current profile Image while uploading the new image of a authenticated user in django
I want to delete the existing profile image( named as profile_pic in models.py) while uploading the new profile pic of a authenticated user.. Below is the code samples of views.py , forms.py and models.py How to implement the functionality to delete the existing image while uploading new one in views.py or forms.py views.py class UpdateUserProfilePic(UpdateView): template_name = 'accounts/signup.html' form_class = forms.UserProfilePicUpdateForm success_url = reverse_lazy('test') def get_object(self): return self.request.user ---------x-------------------------------------------- forms.py class UserProfilePicUpdateForm(forms.ModelForm): class Meta: model = User fields = ('profile_pic',) ---------x-------------------------------------------- models.py class User(AbstractBaseUser): ....... ....... profile_pic = models.ImageField( upload_to='profile_pics', default='default-profile.png') ....... -
How do I send a value of a variable from view to form in django?
I want a customized dropdown list as a choice field for a variable. This list depends on another variable in form How can I send a variable value to the variable in forms views.py z= somelist class HomeView(TemplateView): template_name='charts.html' form = HomeForm(z = z) def get(self, request): form = HomeForm() return render(request, self.template_name, {'form':form}) def post(self,request): form=HomeForm(request.POST) if form.is_valid(): text_11 = form.cleaned_data['post11'] global e e=text_11 text_1 = form.cleaned_data['post_1'] global z z=text_1 text = form.cleaned_data['post'] global b b=text text1 = form.cleaned_data['post1'] global c c=text1 text2 = form.cleaned_data['post2'] global d d=text2 args = {'form':form, 'text_11':text_11,'text_1':text_1,'text':text, 'text1':text1, 'text2':text2} return render(request, self.template_name, args) my forms.py class HomeForm(forms.Form): post11=forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'))) post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'))) post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'))) post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'))) I want the variable to be here post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) Thanks in advance :) -
Django save aggregation in master/detail (many to one relationship)?
I have two models, Order and OrderRow (1:n). What I would like is when something changes on the OrderRow (added, removed, price change, etc.) that that "effect" is calculated to the parent Order. In this case, sum the total of all the OrderRow in Order. The OrderRow (a admin.TabularInline subclass) is setup as inlines on Order. I did implement the django.db.models.signals.post_save but the problem here is that the Order post_save is fired before the OrderRow updates. Is there any nice way (besides implementing a db trigger) for updating this the 'django-way' ? All this under Django Admin -
How can I create a model in django that has a foreign key to one of multiple models?
I want to create a foreign key that can have a reference to exactly one of three other models. example: user fav_animal: foreign_key(bear, cat, dog) bear name cat name dog name How can I achieve this in django? Do I just create 3 nullable foreign keys? Then how do I enforce that always exactly one of them is set? -
How can I generate a rest viewset for all child models based on a parent model
I have the following models based on a shared base model: class Pet(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey('auth.User', related_name='pet', on_delete=models.CASCADE) name=models.CharField(max=100) class Meta: abstract = True ordering = ['-created'] def __str__(self): return str(self.id) class Dog(Pet): legs = models.BigIntegerField() class Bird(Pet): wings = models.BigIntegerField() cage = models.BigIntegerField() Now I would like to get a rest ViewSet that looks like this when I ask for a User: { username: "PeterSchmidt" email:"ps@gmail.com" pets{ { name="shaggy" type="dog" legs=4 } { name="Jaques" type="bird" wings=2 cage=1 } } } Basicly I want a way of having a baseclass model that has its own viewset (multiple serilizers are fine) that I can just use to get all the pets no matter what type they are. Can this be done within standard django rest? -
Why do i get an error when creating a charge with Stripe API in django?
I have a e-commerce app, where after a checkout i handle a payment with the following class-based payment view. But every time i submit a form and create a charge in a try block, it results in the Exception. Stripe secret and public keys are provided in settings, before a view i have '''stripe.api_key = settings.STRIPE_SECRET_KEY''' line. HTML, CSS and JS code was copied from Stripe documentation. class PaymentView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) except Order.DoesNotExist: messages.error(self.request, "You do not have an active order") return redirect('cart') context = { 'payment_option': self.kwargs['payment_option'] } return render(self.request, "payment2.html", context) def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST['stripeToken'] amount = int(order.get_total_price() * 100) # cents user = self.request.user try: charge = stripe.Charge.create( amount=amount, currency='usd', description='Example charge', source=token, ) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total_price() payment.save() order.ordered = True order.ordered_date = datetime.datetime.now().date() order.payment = payment order.save() messages.success(self.request, "Your order was successful") return redirect("/") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, … -
Django in docker cookiecutter - can't send email
I have following docker file version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_caddy: {} ghotel_cc_production_static_vol: {} services: django: &django restart: always build: context: . dockerfile: ./compose/production/django/Dockerfile image: ghotel_cc_api_production_django volumes: - production_static_vol:/app/static depends_on: - postgres env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: restart: always build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: api_production_postgres volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres caddy: restart: always build: context: . dockerfile: ./compose/production/caddy/Dockerfile image: api_production_caddy depends_on: - django volumes: - production_caddy:/root/.caddy - ghotel_cc_production_static_vol:/app/static env_file: - ./.envs/.production/.caddy ports: - "0.0.0.0:8550:80" The problem is that email cannot be sent. There is no errors, Django part works well - i see correct output in console. But after Django sends email it is just lost - never arrives to recipient. How to correctly configure docker so the email can be sent ? -
drf-yasg - testproj - how to silent all the debug output
How can I silent the debug statements for drf-yasg - testproj ? https://github.com/axnsan12/drf-yasg This is how I set it up: $ git clone https://github.com/axnsan12/drf-yasg.git $ cd drf-yasg $ virtualenv venv $ source venv/bin/activate (venv) $ cd testproj (venv) $ python -m pip install -U pip setuptools (venv) $ pip install -U -r requirements.txt (venv) $ python manage.py migrate (venv) $ python manage.py runserver (venv) $ firefox localhost:8000/swagger/ But it keeps producing a lot of debug prints which makes it difficult for me test certain features. How do I silent these debug prints ? Thanks. Here are the debug prints: 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/exceptions.py first seen with mtime 1568447198.368635 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/relations.py first seen with mtime 1568447200.446008 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/requests/certs.py first seen with mtime 1568447203.023515 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/compat.py first seen with mtime 1568447198.368073 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/utils/model_meta.py first seen with mtime 1568447200.529353 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/django/contrib/auth/middleware.py first seen with mtime 1568447201.356465 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/renderers.py first seen with mtime 1568447200.446478 -
Django Pyinstaller .EXE gives me ModuleNotFoundError: No module named 'app.urls'
I am trying to run a Django project using an EXE file compiled using Pyinstaller. But when I run the compiled .EXE file using this command I get ModuleNotFoundError: No module named 'app.urls' and another OsError: [WinError 123]. I will explain how I setup this stuff later. Here is the full error when I run the .EXE file: C:\Users\omen\Desktop\dist\dj>dj.exe runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "threading.py", line 917, in _bootstrap_inner File "threading.py", line 865, in run File "site-packages\django\utils\autoreload.py", line 54, in wrapper File "C:\Users\omen\Desktop\dist\dj\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "site-packages\django\core\management\base.py", line 390, in check File "site-packages\django\core\management\base.py", line 377, in _run_checks File "site-packages\django\core\checks\registry.py", line 72, in run_checks File "site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique File "site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces File "site-packages\django\utils\functional.py", line 80, in __get__ File "site-packages\django\urls\resolvers.py", line 584, in url_patterns File "site-packages\django\utils\functional.py", line 80, in __get__ File "site-packages\django\urls\resolvers.py", line 577, in urlconf_module File "importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "C:\Users\omen\Anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module exec(bytecode, module.__dict__) File … -
Angular: differentiate between sessions in different tabs
I'm developing a web application. The front end is with Angular and back-end is a Rest API with django rest framework. For some customer requirements, I need that the django rest api is able to differentiate between polling requests with a sessionid. After some searches I found that I can identify the session in the REST API side with the value of: request.session.session_key But that isn't the best choice, because for two different tabs I get the same session_key and the desired sessionId that the rest api receives in the request should identify session for specific tab. So not sessionid for different PCs and host IP address, or browsers only, but also it should get two different sessionids for two different tabs. Does django request object contain other id to identify host tabs? I guess that the solution can be found in Angular side. Is there a way in Angular and typescript to identify tabs sessions? -
Django annotation with multiple rows in Subquery , is it possible?
I have a a question regarding annotation. Firstly, I have 2 related models, that are used in annotation subquery. Secondary model. class UserBriefcaseAttribute(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_briefcase_attributes') briefcase_attribute = models.ForeignKey( BriefcaseAttribute, on_delete=models.CASCADE, related_name='+' ) amount = models.IntegerField(default=0) and primary mode for this one class BriefcaseAttribute(models.Model): code = models.CharField(max_length=45) display_name = models.CharField(max_length=45) basically I want to do something like this: SomeModel.objects.filter(**filtering).annotate( result = Subquery(UserBriefcaseAttribute.objects.filter(user=self.request.user, briefcase_attribute__code__in=('silver', 'gold', 'black')).values(‘amount’)) ) Obviously, it doesn't work as subquery returns 3 rows instead of one. I dont know how to deal with it, tried a lot of things already. Expected result should be something like: {‘silver’: 30, ‘gold’: 20, ‘black’: 8} for example or any structure that would be possible to use in DRF serializer Dictfield, or JsonField or Lisfiled or any appropriate field that would be able to render pairs of code: amount (read_only=True). It is possible to do it in separate query but I would prefer to do it via annotation somehow to have only one query. Thanks. -
Wrong url in pagination. Django
I want to search by two fields (q1 and q2): home.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>RU</option> <option>Ukraine</option> <option>USA</option> </select> <button> Search </button> </form> When I click "search" I go to http://127.0.0.1:8001/search/?q=mos&q2=RU (it's OK) Then I click "next". I go to http://127.0.0.1:8001/search/?city=2&q=mos&q2=%20RU (ERROR: "Page not found) but I want http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU How can I fix it? Why do I have "%20" ??? search results.html <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}&q={{ query }}&q2= {{query2}}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query2}}">next</a> {% endif %} </span> </div> models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) COUNTRY = ( ('RU', 'Russia'), ('UKR', 'Ukraine'), ('US', 'USA'), ) category = models.CharField(max_length=100, choices=COUNTRY, default='RU') class Meta: verbose_name_plural = "cities" def __str__(self): return self.name urls.py urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] views.py class HomePageView(ListView): model = City template_name = 'cities/home.html' … -
Error in Dockerizing Django react app together
I have successfully dockerized my Django app but going through the trouble to dockerized my react app that connected with Django apps. this is my Dockerfile below # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and this is my docker-compose.yml file version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /djangobackend/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/djangobackend ports: - 8000:8000 depends_on: - db volumes: postgres_data: Above everything working fine. Later, I tried to dockerize react like below: Dockerfile below: # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ # Use an official node runtime as a parent … -
How to fix this attribute object has no attribute error in django?
i am trying to learn django from https://docs.djangoproject.com/en/2.2/intro/tutorial02/ and i got an attribute error AttributeError: 'Question' object has no attribute 'question_text' as i typed Question.objects.all() the models.py is from django.db import models class Question(models.Model): # ... def __str__(self): return self.question_text class Choice(models.Model): # ... ``def __str__(self): return self.choice_text please help me to solve this issue and i coded as same as Playing with api -
How to update foreign keys in a nested resource with django?
I have two resources in a Django rest framework. Author and books. An author can have up to 3 books in a nested resource. Both resources are created independently and an author can later be assigned to book. My question is how to i represent this assign relationship? I have two main endpoints "author": "http://127.0.0.1:8100/author/", "books": "http://127.0.0.1:8100/book/" For basic CRUD operations. I'm currently trying to assign books to authors like this "author": "http://127.0.0.1:8100/author/{pk}/books" #views.py class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer @action(detail=True, methods=['post'], url_name='books', url_path='books') def assign(self, request, pk=None): author = self.get_object() serializer = Author(data=request.data) if serializer.is_valid(): author.assign_worker(serializer.data['books']) author.save() return Response({'status': 'books assigned'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And i have the following models class Books(models.Model): title = models.CharField(max_length=225) description = models.TextField() author = models.ForeignKey( 'Author', blank=True, null=True, on_delete=models.CASCADE, related_name='books') class Author(models.Model): name = models.CharField(max_length=225) Bio = models.TextField() birthday = models.DateField() Serializers class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Books fields = ("title", "description", "authors") class Author(serializers.HyperlinkedModelSerializer): books = serializers.PrimaryKeyRelatedField(queryset=Books.objects.all(), many= True) class Meta: model = Author fields = ("name", "bio", "birthday", "books") I created an author with this { # "id":"4" "name":"John Smith", "bio":"He was a good man", "birthday":"1970-12-12" } And i created a book with this { #"id":"2" "title":"The …