Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Style Django Form Field
I have a form which has one ChoiceField. I want to add 'form-control' class to this field.What i am doing is delivery_type = ChoiceField(choices=Student.DELIVERY_CHOICES, widget=Select(attrs={'class':'form-control'})) But I am getting this error TypeError: __init__() missing 1 required positional argument: 'master' Here is my models.py file: class Student(models.Model): DELIVERY_CHOICES = ( ('Normal', 'Normal (7 working days) (100 BDT Per Semester)'), ('Urgent', 'Urgent (3 working days) (200 BDT Per Semester)'), ) delivery_type = models.CharField(max_length=100, choices=DELIVERY_CHOICES) Can anyone help me with this? -
Querying a foreign key field in creation form django
i have 3 models, the first one is user a custom user model to handle permissions with two boolean fields, the second is lead with a foreign key of user , the third is event with date and customer foreign key fields, when creating an instance of event i want to see only leads related to the logged in user within the creation form. I tried some solutions like passing the query in the init function with user=None in parameters with an if user: condition, defining a function that returns the queryset that didn’t work it popped out the error« function object has no attribute » and this where i got with getting the error « View.init() takes 1 positional argument but 2 were given », any help will be appreciated #models class Lead(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, blank=True, on_delete=models.SET_NULL) class Event(models.Model): Lead = models.ForeignKey(Lead,null=True, on_delete=models.CASCADE) #views class EventCreateForUser(LoginRequiredMixin,CreateView): template_name = "leads/event_create.html" form_class = EventForm def get_form_kwargs(self): kwargs = super(EventForm, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_success_url(self): return reverse("leads:lead_list") def form_valid(self, form): event = form.save(commit=False) event.Lead.User = self.request.user form.save() messages.success(self.request, "You have successfully created a lead") return super(EventCreateForUser, self).form_valid(form) #forms class EventForm(ModelForm): class Meta: model = Event widgets = { … -
Script is not working in html for my django project
first of all. It's my first time asking a question here. So if I do sth wrong I'm sorry for that. As I am pretty new to programming I really don't get where the problem is with my html right now. Basically I want the Script to do aa new Textbox so that I can do more and more Questions. Kinda like in the image below. enter image description here The Code for my html right now looks like that. enter image description here I would be really grateful if somebody could help me because I really don't know why the script isn't working at all. -
Remote Access to Django's Internet Server
I have a remote (virtual) Ubuntu development station, on which I installed Django, and on which I'm running "manage runserver". Now, I need to browse my project's URLs, and debug their view functions line by line. But I fail to remotely use the web browser on the remote development station (there was time that I succeeded doing so, but it was horribly slow). I therefore would like to enable the web browser on my own laptop to connect the web server of Django that's running on the remote development station. Is there a way to do so? -
django test client returns 404, but works in the shell
This code works fine in the shell, but if you run it through python manage.py test it throws a 404 error, what could be the problem? test_urls.py from django.test import Client, TestCase class StaticURLTests(TestCase): def setUp(self): self.guest_client = Client() def test_homepage(self): response = self.guest_clientw.get("/") self.assertEqual(response.status_code, 200) error: ❯ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_homepage (posts.tests.test_urls.StaticURLTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/finegorko/Development/Yandex.Practicum/hw03_forms/yatube/posts/tests/test_urls.py", line 10, in test_homepage self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.003s FAILED (failures=1) Destroying test database for alias 'default'... -
age filter in django
I have products in my ecommerce. How can I group them in age groups like child, adult, senior? But one product can be on morethan one group. Example a cloth can be for both adult and senior. What method should I choose? -
Following error raised: TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist
I am trying to handle errors in my Django project and I keep receiving the following message: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/base.py", line 140, in get_response response = self._middleware_chain(request) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 57, in inner response = response_for_exception(request, exc) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 184, in handle_uncaught_exception return callback(request) File "/Users/Tom/Desktop/squeasy /tasks/views.py", line 31, in handler500 response = render(request, template_name) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: 500.html For my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR /'squeasy/tasks/templates/tasks'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I have also tried: 'DIRS': [], 'APP_DIRS': True, and 'DIRS': [os.path.join(BASE_DIR, 'templates')], and 'DIRS': [BASE_DIR/'templates'], I have no other errors when running templates normally, it is only when I force an error. I have the following views.py to handle 400, 403 and 404 error requests def handler400(request, exception, template_name = "400.html"): response = … -
an exception while running dockerized Django project locally which is hosted on google cloud run
I have cloned a dockerized GeoDjango project and want to run it locally which is hosted on google cloud run. I have also tried to run the project without docker by running python manage.py runserver but all in vain. This is the exception error which is occurring Exception: No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets were found. I created the image by using this command: docker build . -t your_image_name when I run this command: docker run -p 9090:8080 -e PORT=8080 my_image_name It gives the error traceback given below. Error traceback: [2022-07-24 08:16:45 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-07-24 08:16:45 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-07-24 08:16:45 +0000] [1] [INFO] Using worker: gthread [2022-07-24 08:16:45 +0000] [7] [INFO] Booting worker with pid: 7 [2022-07-24 08:16:49 +0000] [7] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 359, … -
How can I use Serializer for logout?
I'm very new to Django and preparing for the DRF Session. I have to write code in Serializers.py and views.py for Logout function but I don't know what to do and where to start. Can you please help? Here's some code for register and login Serialzers.py from rest_framework import serializers from .models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] def create(self, validated_data): user = User.objects.create( email=validated_data['email'], username=validated_data['username'],) user.set_password(validated_data['password']) user.save() return user class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=64) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) if not user.check_password(password): raise serializers.ValidationError() else: return user else: raise serializers.ValidationError() class UserLogoutSerializer(serializers.Serializer): # I have to do this part views.py from django.shortcuts import get_object_or_404, render from .serializers import * from .models import * from rest_framework import views from rest_framework.response import Response class SignUpView(views.APIView): def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': 'Success', 'data': serializer.data}) return Response({'message': 'Fail', 'error': serializer.errors}) class LoginView(views.APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): return Response({'message': "Success", 'data': serializer.data}) return Response({'message': "Fail", 'data': serializer.errors}) class LogoutView(views.APIView): -
Redux store not being updated after dispatching action
Hi all I am new to react and have been working on a project the last week I have been trying to build this login for django rest framework using react and redux toolkit. As I understand it, redux action creators create actions which then get dispatched to reducers for changing global state. If this is the case, why is my action creator for login not saving the access and refresh tokens to the store!!!???!!?!?!?!??! Below is my code. --Login.js ---Where most of the login logic is happeneing and the action creator for login is being used. import { useState } from "react" import {useDispatch, useSelector} from "react-redux" import {login} from '../features/auth/authSlice' import axios from "axios" const Login = () => { const userToken = useSelector((state)=>state.auth) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const dispatch = useDispatch() const authenticate = async ()=>{ // const resp = await axios.post('http://localhost:8000/auth/login', {formData}) const resp = await fetch('http://localhost:8000/auth/login', { method: 'POST', headers:{ 'Content-Type': 'application/json' }, body:JSON.stringify({username:username, password:password}) }) const data = await resp.json() console.log(data); dispatch(login({ accessToken: data.access, refreshToken: data.refresh })) return data } const handleSubmit = (e) =>{ e.preventDefault() console.log(username, password); // authenticate().then((data)=>{ }) authenticate() setTimeout(()=>{ console.log(userToken); }, 3000) console.log(userToken); } … -
ModelChoiceField fields are not saved, what should I do?
The site has the ability to create a post for a specific game. When you try to create a post, it is created but the ManyToManyField remain empty. How to fix it? **forms.py** class AddPost(forms.ModelForm): title = forms.CharField(label='Title', widget=forms.TextInput(attrs={'placeholder': 'Заголовок...'}), help_text='Максимум 100 символів.') games = forms.ModelChoiceField(queryset=Game.objects.filter(draft=False), widget=forms.Select, required=True) tags = forms.ModelMultipleChoiceField(queryset=Tags.objects.all(), widget=forms.SelectMultiple( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) foreword_description = forms.CharField(label='Small Description', widget=forms.Textarea(attrs={'placeholder': 'Коротке описання...'}), help_text='Максимум 335 символів.') description = forms.CharField(label='Description', widget=CKEditorUploadingWidget()) rank = forms.FloatField(label='Rank', widget=forms.TextInput(attrs={'placeholder': 'Оцінка...'})) good = forms.ModelChoiceField(queryset=Good.objects.all(), widget=forms.Select( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) bad = forms.ModelChoiceField(queryset=Bad.objects.all(), widget=forms.Select( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) url = forms.SlugField(label='Title', widget=forms.TextInput(attrs={'placeholder': 'Унікальний ідентифікатор...'}), help_text='Максимум 255 символів.') premiere = forms.DateField(label='Date', widget=forms.SelectDateWidget(attrs=({'style': 'width: 10%; display: inline-block;'})), help_text='У форматі: 24.03.2022.') class Meta: model = Post fields = ( 'title', 'games', 'tags', "foreword_description", "description", "rank", "good", "bad", "url", "premiere",) **views.py** def addpost(request): if request.method == "POST": form = AddPost(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('../blogs/') else: form = AddPost() data = { 'form': form, 'add': True } return render(request, 'gamelibs/user-post-manager.html', {'form': form}) **models.py** class Game(models.Model): title = models.CharField("Назва", max_length=100) tagline = models.CharField("Слоган", max_length=500, default='') description = models.TextField("Описання") description_small = models.CharField("Описання коротко", max_length=100, null=True) poster = models.ImageField("Постер", upload_to="games/poster/") banner = models.ImageField("Банер", upload_to="games/banner/", null=True) treiler = models.CharField("Трейлер", … -
ImportError: cannot import name 'last_traceback' from 'sys' (unknown location)(django)
I'm new to Django and Ubuntu. (i didnt have these problems on windows) I follow these steps to make Project in Django: 1.pip3 install pipenv 2.mkdir projectname 3.pipenv install Django or pip install Django(i use both Command) 4.code . 5.pipenv shell 6.django-admin startproject projectname(if i enter [django admin startproject projectname ] i get the error that --> django: command not found) 7.pipenv --venv (i use this command to use python interpreter inside the virtual enviroment 8.python manage.py startapp appname(after enter this Command i get the error) Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in … -
invalid json type when GET request send python requests?
My code: def get_authenticate(): header = { "login": username, "password": password, "db": db, "content-type": "application/json" } h_data = json.dumps(header, indent=4) get_tokens = requests.get(url="https://someurl.com/api/auth/token/", headers=json.loads(h_data)) return get_tokens get_ = get_authenticate() print(get_) for i in get_: print(i) Output: <Response [400]> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 400 Bad Request Bad Request Invalid JSON data -
How can I group products based on their age in django?
I have a django ecommerce site where I have products for 3 age groups. i.e. Child, Adult, Senior. The issue is one product can be on more than one age group. How can I arrange that with the product model? I tried using booleans and use select option but when I change pages it gives "keywords must be strings" error because of the filter. Here is my code: Templates <li class="age"><Form action="{% url 'get_products' %}" method="get"> <select style="text-transform: uppercase;" name="age_group" onchange="submit()"> <option value="" selected disabled>Gifts by Age</option> <option value="infant">Infant</option> <option value="toddler">Toddler</option> <option value="child">Child</option> <option value="teen">Teenager</option> <option value="adult">Adult</option> </select> </Form></li> Views def get_products(request): # getting the age group you passed via form age_group = request.GET.get("age_group") products = Product.objects.filter(**{age_group: True}) paginator = Paginator(products, 1) page_number = request.GET.get('page') products = paginator.get_page(page_number) context = {'products': products } return render(request, "age.html", context) -
Django admin conditional inline
I have a question model which can have different types like SINGLE_ANSWER, MULTIPLE_ANSWER , CODE , ... MODELS.PY : class Question(BaseModel): class QuestionType(models.IntegerChoices): SINGLE_ANSWER = 1 MULTIPLE_ANSWER = 2 ESSAY = 3 CODE = 4 VIDEO = 5 UPLOAD = 6 class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 question_text = models.TextField() type = models.IntegerField(choices=QuestionType.choices) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) ADMIN : @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): inlines = [ OptionInline, CodeInline, TestCaseInline, ] By this code all inlines(OptionInline,CodeInline,TestCaseInline) will be shown in admin page like the picture bellow: question admin panel pic but i want the inlines appear whenever the user choose the type, for example the OptionInline shows when user choose multiple_answer or CodeInline shows when user choose CODE from type dropdownlist what i did for this purpose is overriding the get_inlines method ADMIN : def get_inlines(self, request, obj: Question): if obj: if obj.type in [Question.QuestionType.SINGLE_ANSWER, Question.QuestionType.MULTIPLE_ANSWER]: return [OptionInline] elif obj.type == Question.QuestionType.CODE: return [CodeInline, TestCaseInline] else: return [] else: return [] but i have a problem when i want to change the type after saving the question this error appears : (Hidden field INITIAL_FORMS) This field is required. ManagementForm … -
How can I make a Django application connect to a minio server when both are behind an nginx proxy and inside individual docker containers?
Goal Access minio server via subdomain from Django server in docker environment (both minio server and Django server are behind nginx proxy) Expected result: Django can access minio server using the subdomain specified in nginx. Problem Django service can't connect properly. Docker logs: api | Traceback (most recent call last): api | File "manage.py", line 22, in <module> api | main() api | File "manage.py", line 18, in main api | execute_from_command_line(sys.argv) api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line api | utility.execute() api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 386, in execute api | settings.INSTALLED_APPS api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ api | self._setup(name) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup api | self._wrapped = Settings(settings_module) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ api | mod = importlib.import_module(self.SETTINGS_MODULE) api | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module api | return _bootstrap._gcd_import(name[level:], package, level) api | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import api | File "<frozen importlib._bootstrap>", line 991, in _find_and_load api | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked api | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked api | File "<frozen importlib._bootstrap_external>", line 843, in exec_module api | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed api … -
Django cannot find path although it is not hardcoded
The background of this problem is that I am deploying a Django project on production server. Upon testing on production server I get the below error from my asgi.log 2022-07-24 07:03:12,962 ERROR Internal Server Error: /paymentWebhook Traceback (most recent call last): File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 482, in thread_handler raise exc_info[1] File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.10/asyncio/tasks.py", line 408, in wait_for return await fut File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 486, in thread_handler return func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 124, in payment_webhook paymentHandle = handlePostPayment(request = request) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 165, in handlePostPayment pdfReceipt = webshopUtils.generateReceipt(session_id = customer.session_id) File "/home/jianwu/DimsumBox_website/dimsumbox/./dimsumbox/Modules/webshopUtils.py", line 484, in generateReceipt return pdf.pdf.output() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 2929, in output self.close() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 672, in close self._enddoc() # close document File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3672, in _enddoc self._putresources() # trace_size is performed inside File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3565, in _putresources self._putfonts() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3205, in … -
How to deploy django project on aws ec2 using bitbucket ci/cd?
I am looking for any documents or step by step tutorial on how to deploy Django project on AWS ec2 using bitbucket ci/cd?. I have gone through many docs but unable to get the proper workflow on deploying the project. I'm learning ci/cd pipelines. Thanks!! -
Django: unable to loaddata, UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I'm new to Django, I'm encounter an error during loaddata. I had completely dump my data in seed_data.json, but when I attempt to loaddata, it came out UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte At first I dump my data into python manage.py dumpdata > seed_data.json Then I removed db.sqlite3 rm db.sqlite3 Make migrations python manage.py migrate Now I loaddata seed_data.json, it came out error python manage.py loaddata seed_data.json error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Seed_data.json [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, "fields": {"name": "Can delete log entry", "content_type": 1, "codename": "delete_logentry"}}, {"model": "auth.permission", "pk": 4, "fields": {"name": "Can view log entry", "content_type": 1, "codename": "view_logentry"}}, {"model": "auth.permission", "pk": 5, "fields": {"name": "Can add permission", "content_type": 2, "codename": "add_permission"}}, {"model": "auth.permission", "pk": 6, "fields": {"name": "Can change permission", "content_type": 2, "codename": "change_permission"}}, {"model": "auth.permission", "pk": 7, "fields": {"name": "Can delete permission", "content_type": 2, "codename": "delete_permission"}}, {"model": "auth.permission", "pk": 8, "fields": {"name": "Can view permission", "content_type": 2, "codename": "view_permission"}}, {"model": "auth.permission", … -
How do I add Page in this my code? django
I want to add paging function in my code. This socre_by function line up by score. But A lot of Movie and TV line up. I want to page Movie and TV. How can I add paging functionality while preserving the functionality of this code? def Score_by(request): query_min = 0 query_max = 10 if request.GET.get('min') and request.GET.get('max'): query_min = request.GET.get('min') query_max = request.GET.get('max') movies = Movie.objects.order_by('-stars') movie_list= [] Ranking = 1 if movies.exists(): for obj in movies: if (float(query_min) <= float(obj.average_stars())) and (float(query_max) >= float(obj.average_stars())): data = requests.get(f"https://api.themoviedb.org/3/movie/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") data_movie = data.json() data_movie['score'] = obj.average_stars() data_movie['Ranking'] = Ranking movie_list.append(data_movie) Ranking += 1 # print(movie_list) tv = TV.objects.order_by('-stars') tv_list = [] Ranking = 1 if tv.exists(): for obj in tv: if (float(query_min) <= float(obj.average_stars())) and (float(query_max) >= float(obj.average_stars())): data = requests.get(f"https://api.themoviedb.org/3/tv/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") data_tv = data.json() data_tv['score'] = obj.stars data_movie['Ranking'] = Ranking tv_list.append(data_tv) Ranking += 1 context = { 'movie':movie_list, 'tv' :tv_list } return render(request, 'Movie/score_by.html', context) -
Why my custom script processing data just fine on local development Django server but not on Digital Ocean App?
Does anyone know why when I upload a CSV file locally to the Django development server, my code does work as plan as in processing the CSV file and adding data to the database correctly, but when I try the same thing with the production server on Digital Ocean using App service - the CSV file just uploaded without having getting processed? I notice this because no new product is being added when uploading the CSV file to the production server on Digital Ocean. By the way, the local development server is also using S3 storage - so the same file got uploaded to Amazon S3 all the same - but the code processes the file in the development server but not on the production server - the development server is on my laptop. The production server is on Digital Ocean's App. I did something like this in the code: from django.core.files.storage import default_storage def upload_csvs(request): current_page_bread_crumb_title = 'upload csv' form = CsvsModelForm(request.POST or None, request.FILES or None) random_category = None if form.is_valid(): form.save() # reset form after save form = CsvsModelForm() # Only getting csv file that isn't activated or being used already. get_csv_data = Csvs.objects.filter(activated=False).order_by('-id').first() with default_storage.open(get_csv_data.file_name.name, mode='r') … -
How to query a dropdown in a Django ModelForm field based on current logged in user
I have a django model form were a user can submit their budget information. One of the fields in the form is a Category which is a foreign key from a Category Model. Unfortunately all users can see each other category's. How can I query the Category Field in the model form to only show logged in user. This is my Model.py from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank =True) TYPE = ( ('Income', 'Income'), ('Expense', 'Expense'),) category_feild = models.CharField(max_length = 100,unique = True) income_or_expense = models.CharField(default =" ",max_length=200, choices=TYPE) def __str__(self): return self.category_feild class Budget(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=False) budget_amt = models.FloatField(default= 0) comments = models.CharField(max_length = 140,default="") def __str__(self): return self.category.category_feild +' - ' + str(self.date.strftime('%b %Y')) This is my forms.py class budget_form(ModelForm): class Meta: model = Budget fields = ['category','date','budget_amt','comments' ] widgets = { 'category' : forms.Select(attrs={'class':'form-control'}), 'date' : forms.DateInput(attrs={'class':'form-control'}), 'budget_amt' : forms.NumberInput(attrs={'class':'form-control'}), 'comments' : forms.TextInput(attrs={'class':'form-control'}), } This is the view.py where I have attempted a query to filter for category of logged in users. def add_budget(request): b_form = budget_form if request.method == 'POST' and "budgetForminfo" in request.POST: budget_form.fields["category"].queryset= Category.objects.filter(user=request.user) b_form = budget_form(request.POST or None) if b_form.is_valid(): b_form.save() b_form = budget_form() return redirect('add_budget') … -
Connect Django to SQL database in Google Cloud's Compute Engine
My Django app has been working successfully using Google's App Engine standard environment. However I need to use Compute Engine for more power. I am testing a single VM instance running the app, however it has issues connecting to the POSTGRES database. The compute engine service account has all the same permissions as the app engine service account. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloudsql/myproject:us-central1:mypostgresname', 'NAME': 'mydatabasename', 'USER': 'myusername', 'PASSWORD': 'mypassword', } } -
How to replace empty values from api query to a number
I have a piece of code that pulls api data from an external website. The issue I am having is that during the pull it also saves the data to the database if it does not exist. Well some of the values from the json data I pull are empty and the database is expecting an integer when saving. How do I convert he json data empty strings to default 0? The Error ValueError at / Field 'he_displaced_threshold_ft' expected a number but got ''. services.py def get_runways(): params = { "apiToken": "SECRET", } api_base = "https://airportdb.io/api/v1/airport/KMIA" api_result = requests.get(api_base, params) api_response = api_result.json() for runway in api_response["runways"]: runway_data, created = Runway.objects.update_or_create( airport_ident=Airport.objects.get(ident=runway["airport_ident"]), length_ft=runway["length_ft"], width_ft=runway["width_ft"], surface=runway["surface"], lighted=runway["lighted"], closed=runway["closed"], le_ident=runway["le_ident"], le_latitude_deg=runway["le_latitude_deg"], le_longitude_deg=runway["le_longitude_deg"], le_elevation_ft=runway["le_elevation_ft"], le_heading_degT=runway["le_heading_degT"], le_displaced_threshold_ft=runway["le_displaced_threshold_ft"], he_ident=runway["he_ident"], he_latitude_deg=runway["he_latitude_deg"], he_longitude_deg=runway["he_longitude_deg"], he_elevation_ft=runway["he_elevation_ft"], he_heading_degT=runway["he_heading_degT"], he_displaced_threshold_ft=runway["he_displaced_threshold_ft"], ) runway_data.save() return runway models.py class Runway(models.Model): airport_ident = models.ForeignKey(Airport, on_delete=models.CASCADE) length_ft = models.IntegerField(default=None, blank=True, null=True) width_ft = models.IntegerField(default=None, blank=True, null=True) surface = models.CharField(max_length=50, blank=True, null=True) lighted = models.IntegerField(default=None, blank=True, null=True) closed = models.PositiveBigIntegerField(default=None, blank=True, null=True) le_ident = models.CharField(max_length=5, blank=True, null=True) le_latitude_deg = models.FloatField(default=None, blank=True, null=True) le_longitude_deg = models.FloatField(default=None, blank=True, null=True) le_elevation_ft = models.IntegerField(default=None, blank=True, null=True) le_heading_degT = models.FloatField(default=None, blank=True, null=True) le_displaced_threshold_ft = models.IntegerField(blank=True, null=True) he_ident = models.CharField(max_length=5, blank=True, null=True) he_latitude_deg … -
Get data belongs to a field of model in select_related to a list and create a dataframe
I'm trying to query two related tables and create a pandas dataframe then use it for rule mining. The dataframe should look like this, order products ---------------- 1 ['product1', 'product2'] 2 ['product1', 'product3', 'product10'] ... My models, class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(Product, through='OrderedProduct', related_name='orders') class OrderedProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) quantity = models.IntegerField(default=1) class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) I've done the dataframe creating part as follows in views, and it works but needs preprocessing to get end result and feels it's inefficient for a larger dataset. orders = OrderedProduct.objects.all().values('order__id', 'product__name') df = pd.DataFrame.from_records(orders) df = df.groupby(['order__id'])['product__name'].apply(list).to_list() So, my question is 'Is there a more direct and efficient approach to do this?'. Any advice is highly appreciated.