Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting an error while trying to run docker-compose to configure a django project and mysql database, on Ubuntu 22.04
I am new to docker and still learnig it, so I was coding along this youtube tutorial but when I try to run the docker compose file I'm getting these errors on my machine which I can't seem to understand. Here is the docker-compose.yml contents: version: "3.8" services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: mysql:5.7 environment: MYSQL_DATABASE: 'django-app-db' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/db:/var/lib/mysql Dockerfile: FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt Requirements.txt file: asgiref==3.5.2 Django==4.1.3 pytz==2022.6 sqlparse==0.4.3 psycopg2-binary>=2.9 mysqlclient>=2.1 Now when I run docker-compose build or the next commnad docker-compose run --rm app django-admin startproject core ., thats when I'm getting these errors: Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] mysql_config --version /bin/sh: 1: mysql_config: not found mariadb_config --version /bin/sh: 1: mariadb_config: not found mysql_config --libs /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-lbql0nv5/mysqlclient_b1015c8235e44329ba5248fc9f64b86b/setup.py", line 15, in … -
'NoneType' object is not subscriptable in Django
I'm writing tests for views.py and check that the context of the main page, that it is formed correctly, and when checking, such an error crashes def test_index_page_show_correct_context(self): """Шаблон index сформирован с правильным контекстом.""" response = self.guest_client.get(reverse('posts:index')) excepted_object = Post.objects.all()[:TEST_NUM] > self.assertEqual(response.context['page_obj'], excepted_object) E TypeError: 'NoneType' object is not subscriptable Code: class PostViewsTest(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create_user(username='auth') cls.group = Group.objects.create( title='Тестовая группа', slug='test-slug', description='Тестовое описание', ) cls.post = Post.objects.create( author=cls.user, text='Тестовый пост', group=cls.group ) cls.comment = Comment.objects.create( text='Тестовый комментарий', author=cls.user ) def setUp(self): self.guest_client = Client() self.authorized_client = Client() self.authorized_client.force_login(PostViewsTest.post.author) def test_index_page_show_correct_context(self): """Шаблон index сформирован с правильным контекстом.""" response = self.guest_client.get(reverse('posts:index')) excepted_object = list(Post.objects.all()[:TEST_NUM]) self.assertEqual(list(response.context['page_obj']), excepted_object) -
How to hide/show a register with djangoadmin?
I have a model with customers in my front I have a combobox with the list of my customers. how I can in djangoadmin hide or show this customers? I think it could be a checkbox like "this customer is active/inactive" but how can I solve this with djangoAdmin? I think it could be a checkbox like "this customer is active/inactive" but how can I solve this with djangoAdmin? -
How to Create a Pandas DataFrame from multiple list of dictionaries
I want to create a pandas dataframe using the two list of dictionaries below: "country_codes": [ { "id": 92, "name": "93", "position": 1, "description": "Afghanistan" }, { "id": 93, "name": "355", "position": 2, "description": "Albania" }, { "id": 94, "name": "213", "position": 3, "description": "Algeria" }, { "id": 95, "name": "1-684", "position": 4, "description": "American Samoa" } ] gender = [ { "id": 1, "name": "Female" }, { "id": 3 "name": "Male" } ] The dataframe should have two columns: Gender and Country Code. The values for gender will be from the gender variable while the value for country code will be from the country code variable. I have tried: df = pd.DataFrame(list( zip( gender, country_codes ) ), columns=[ "name" "description" ] ).rename({ "name": "Gender", "description": "Country" })) writer = pd.ExcelWriter('my_excel_file.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name="sample_sheet", index=False) writer.save() But after running the script, the excel file was not populated. -
How to get reference table fields with django model query
When I am trying to fetch foreign key table using django model I am only unable to get the referenced table details. I have two models TblVersion and TblProject defined below class TblVersion(models.Model): version_id = models.AutoField(primary_key=True) project = models.ForeignKey(TblProject, models.DO_NOTHING) version_major = models.PositiveSmallIntegerField() version_minor = models.PositiveSmallIntegerField() class Meta: managed = False db_table = 'tbl_version' class TblProject(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=32) class Meta: managed = False db_table = 'tbl_project' My current code implementation: result= TblVersion.objects.all().select_related() data = serializers.serialize('json', result) print(data) Code Result: `[{"model": "CCM_API.tblversion", "pk": 1, "fields": {"project": 1, "version_major": 1000, "version_minor": 0}}, {"model": "CCM_API.tblversion", "pk": 2, "fields": {"project": 2, "version_major": 1000, "version_minor": 0}}, {"model": "CCM_API.tblversion", "pk": 3, "fields": {"project": 2, "version_major": 1000, "version_minor": 2}}]` The code output lacks the foreign key fields (Project Name). I want a list of version numbers with their respective projects like this. | Version Id | Major Version | Minor Version | Project Id | Project Name| | -------- | -------- |-------- |-------- |-------- | | 1 | 1000 |1 | 1| PROJ_1 | | 2 | 1000 |1 | 2| PROJ_2 | | 3 | 1000 |2 | 1| PROJ_1 | -
Django can not connect to PostgreSQL DB
When I`m trying to connect Django Server to PostgreSQL db there is an error: " port 5433 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? " I`m using Windows 10, Pycharm, Debian Settings in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ps_store_db', 'USER': 'zesshi', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5433', } } Tried to check connection with DBeaver and all`s good there, but still cant connect with Django Dbeaver connection My firewall is off, i was trying to change from 5432 to 5433 -
Django query to return percentage of a users with a post
Two models Users (built-in) and Posts: class Post(models.Model): post_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='user_post') post = models.CharField(max_length=100) I want to have an API endpoint that returns the percentage of users that have posted. Basically I want SUM(unique users who have posted) / total_users I have been trying to play around with annotate and aggregate, but I am getting the sum of posts for each users, or the sum of users per post (which is one...). How can I get the sum of posts returned with unique users, divide that by user.count and return? I feel like I am missing something silly but my brain has gone to mush staring at this. class PostParticipationAPIView(generics.ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') # How can I take something like this, divide it by User.objects.all().count() * 100, and assign it to something to return as the queryset? queryset = Post.objects.filter(post_date__gte=start_date, post_date__lte=end_date).distinct('user').count() return queryset My goal is to end up with the endpoint like: { total_participation: 97.3 } Thanks for any guidance. BCBB -
DJango How to select certain item from database table in html
I have a store page that gets entries from a Products table. This shows products in order in the same format infinitely for how many are in the table. ` {% for product in products %} <div class="container2"> <div href="item" class= 'product-item'> <div class= 'image-cont'> <a href="item"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a> </div> {% if product.offer != 0 %} <div class= 'offer-banner' > <a href="item">Special Offer</a> </div> {% endif %} </div> <div href="item" class="product-content"> <div href="item" class="product-title"> <a href="item" >{{product.name}}</a> </div> <div class="product-price"> <a href="item" >${{product.price}}</a> </div> <br> <div class="product-desc"> <a href="item" >{{product.desc}}</a> </div> <br> <div class="product-userpfp"> <a href="#" ><img src='{{product.userpfp.url}}'></a> </div> <br> <div class="product-poster-name"> <a href="#" >{{product.username}}</a> </div> <br> </div> </div> </div> </div> {% endfor %} ` I want to be able to click on any product from products and get a page with the specific item I clicked on. This is my Item page. ` {`% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href= "{% static 'css\item.css' %}" > {% endblock %} {%block content%} {% load static %} <h1>Item</h1> <h3>{{item.name}}</h3> {% endblock %}` ` The problem should be inside the view.py file ` def item(request): item = Product.objects.select_related() return render(request, "item.html", {"item": … -
createsuperuser is not working with custom user model
I know this question is a repeat (I've looked at similar posts here and here although the I still couldn't anywhere with the solutions. I've created a custom user model for my application but when I create a superuser I can't seem to sign in on the admin panel. What have I done wrong? user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must provide an email to create an account') if not username: raise ValueError('Users must provide a username to create an account') 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), username=username, password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=True) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserAccountManager() def __str__(self): return f'email: {self.email}\nusername: {self.username}' def has_perm(self, perm, obj=None): return self.is_admin def has_module_perm(self, app_label): return True my settings from pathlib import Path # Build paths inside the project like … -
How do I make a post request work after using get_queryset?
I would like to have a list of a user's devices with a checkbox next to each one. The user can select the devices they want to view on a map by clicking on the corresponding checkboxes then clicking a submit button. I am not including the mapping portion in this question, because I plan to work that out later. The step that is causing problems right now is trying to use a post request. To have the user only be able to see the devices that are assigned to them I am using the get_queryset method. I have seen a couple questions regarding using a post request along with the get_queryset method, but they do not seem to work for me. Using the view below, when I select a checkbox and then click submit, it looks like a post request happens followed immediately by a get request and the result is my table is empty when the page loads. Portion of my views.py file: class DeviceListView(LoginRequiredMixin, ListView): model = Device template_name = 'tracking/home.html' context_object_name = 'devices' # ordering = ['-date_added'] def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(who_added=self.request.user) def post(self, request): form = SelectForm(request.POST) # if form.is_valid(): # text = … -
Foreign Key Constraint Failed Django with UUID
Trying to save to a table with a foreign key but come up with a IntegrityError: Foreign Key Constraint failed. I have checked to make sure I am getting the correct data for my foreign key and it seems to be there. I am not sure why I am getting this error. Models.py class IPHold(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) CHOICES = [ ('1', 'Book'), ('2', 'Documentary'), ('3', 'Graphic Novel/Comic'), ('4', 'Journalism'), ('5', 'Merchandise'), ('6', 'Podcast'), ('7', 'Stage Play/Musical'), ('8', 'Video Game'), ] media_type = models.CharField(max_length=1, choices=CHOICES, blank=False) title = models.CharField(max_length=255, blank=False) author_creator = models.CharField(max_length=255, blank=True) production_company = models.CharField(max_length=255, blank=True) class RoleHold(models.Model): ip = models.ForeignKey(IPHold, on_delete=models.CASCADE, related_name='ip_role') name = models.CharField(max_length=128, blank=False) TYPE = [ ('1', 'Lead'), ('2', 'Supporting'), ] role_type = models.CharField(max_length=1, choices=TYPE, blank=True) age_min = models.PositiveSmallIntegerField(blank=True) age_max = models.PositiveSmallIntegerField(blank=True) ETHNICITY = [ ('1', 'American Indian or Alaska Native'), ('2', 'Asian'), ('3', 'Black or African American'), ('4', 'Hispanic or Latino'), ('5', 'Native Hawaiian or Other Pacific Islander'), ('6', 'White'), ('7', 'Unknown/Irrelevant'), ] race = models.CharField(max_length=1, choices=ETHNICITY, blank=True) GENDEROPTIONS = [ ('1', 'Male'), ('2', 'Female'), ('3', 'N/A'), ('4', 'Unknown/Irrelevant'), ] gender = models.CharField(max_length=1, choices=GENDEROPTIONS, blank=True) description = models.TextField(blank=True) Views.py def add_characters(request): id = request.GET.get('id') ips = IPHold.objects.get(uuid=id) form = forms.AddCharacter context … -
local variable 'product' referenced before assignment
I am trying to create a django view which will let users to create a new product on the website. class CreateProductView(APIView): serializer_class = CreateProductSerializer def post(self, request, format = None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.data.name content = serializer.data.content category = serializer.data.category product = Product(name=name, content=content, category=category) product.save() return Response(ProductSerializer(product).data, status=status.HTTP_201_CREATED) But it is giving this error: UnboundLocalError at /api/create-product local variable 'product' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/api/create-product Django Version: 4.0.5 Exception Type: UnboundLocalError Exception Value: local variable 'product' referenced before assignment Exception Location: H:\Extension Drive (H)\My Software Applications\DeCluttered_Life\declutterd_life\api\views.py, line 42, in post Python Executable: C:\Python310\python.exe Python Version: 3.10.5 Python Path: ['H:\\Extension Drive (H)\\My Software ' 'Applications\\DeCluttered_Life\\declutterd_life', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Fri, 02 Dec 2022 17:26:24 +0000 I tried to look other issues similar to this, but couldn't find the solution. -
Ignore a line of Javascript if the element isn't present on the page and skip to the next line?
Working on a django web app and running into an issue with my javascript. The web application is multiple different html pages, so the elements my js code is searching for are present on some pages but not others. If the second line is not present on the current page, the script stops running and the final function will not work. I have a "plan" page where you can add additional tags to your plan and then a separate page to filter results. If I'm on the plan page then the "#filterBtn" element is not present so my createNewTagField function doesn't work. If I switch the two lines of code, the opposite happens. I can't get them both to work since the elements javascript is searching for are on two different pages and not present at the same time. These are the lines causing problems. document.addEventListener('DOMContentLoaded', function() { document.querySelector('#mobile-menu').onclick = toggleMobileMenu; document.querySelector('#filterBtn').onclick = toggleFiltersMenu; document.querySelector('#addTag').onclick = createNewTagField; }); I've rearranged the lines of code and it just fixes it for one page while still having the problem on the other page. I'm thinking it needs to be something like if null then continue to the next line, but haven't been … -
Does OpenXML SDK only work with Visual Studio?
I am creating a Django application to be run on an IIS server. I need to update an Excel file automatically on the server. Given that the interactive update using COM (pywin32.com) is not supported by Microsoft (https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2) I need to use the Microsoft recommended approach which involves using OpenXML SDK. In the following link, https://learn.microsoft.com/en-us/office/open-xml/getting-started, it mentions this is used with Visual Studio. My question is whether this is the only way of using OpenXML SDK to edit Office documents. I do not use Visual Studio. Thank you for any help provided I have searched the internet but have not found a suitable answer. -
Django form send emails in console but not to my mailbox
I'm getting some practice using Django and now I'm stuck trying to get a contact form to work. What I'm trying to do is: once the "Submit" button is clicked, I should receive the form data in an email arriving at the email address linked to my website. Instead what happens is: once I clicked on the "Submit" button, the page loads for some time and at the end I get a SMTPServerDisconnected error. Can you tell me if I made a mistake in writing some logic or if it is a problem that I have to solve with my hosting service? This is forms.py: from django import forms class ContactForm(forms.Form): name = forms.CharField(label='Your name', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'name'})) from_email = forms.EmailField(label='Your email', max_length=200, widget=forms.TextInput( attrs={'class': 'form-control', 'id': 'email'})) subject = forms.CharField(label='Enter a subject', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'subject'})) message = forms.CharField(label='Write here your message', max_length=500, widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'message'})) This is view.py (I replaced each address with dummy addresses): def home(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] body = { 'first_name': form.cleaned_data['name'], 'email_from': form.cleaned_data['from_email'], 'message': form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'example@example.com', ['mydomainemail@example.net'], fail_silently=True) except BadHeaderError: return HttpResponse('Invalid header found') … -
Django LoginView can not authenticate the user
I have a LoginView and a registration form. this registration form is working properly, users are flying to the database, but LoginView gives an incorrect login or password when trying to log in, although all the data is correct, why can this be? CustomUser from models.py class CustomUser(AbstractUser): objects = UserManager() username = models.CharField( unique=True, max_length=150, error_messages={ 'unique': "Пользователь с таким ником уже есть"},) email = models.EmailField( 'почта', unique=True, blank=False) password = models.CharField( 'пароль', max_length=128) first_name = models.CharField( 'имя', max_length=30, blank=True) second_name = models.CharField( 'фамилия', max_length=30, blank=True) birthday = models.DateField( 'день рождения', blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' urls.py path('login/', LoginView.as_view( template_name='user/login.html'), name='login'), register def registrations(request): form = RegistrationForm(request.POST or None) if request.method == 'POST' and form.is_valid(): CustomUser.objects.create(**form.cleaned_data).save() messages.success(request, 'Вы успешно зарегестрировались') context = { 'form': form, } return render(request, 'user/reg.html', context) It is necessary for LoginView to work properly -
Use two different REST API back-end systems for one app/front-end [closed]
So basically I currently have a web app project with the front-end being Next.js (React/JS) and the back-end being Laravel (PHP). When development started Laravel was chosen by the developers and I was okay with that, since I was not really into back-ends, and heard that Laravel is alright. But from there on, along with them developing the project I started learning Javascript, React etc, and right now I am working on the project mostly by myself, because with my current skill I am now capable of doing most front-end related things, and I am also a bit familiar with Laravel at this point. Though currently I want to take a deeper dive into Node.js or Django and here comes my question with that. I would like to build to extend my web app with another integrated area in it, with some completely other functionality that is completely decoupled from the existing Laravel REST API. The current REST API just sends Json to the front-end, requested through axios with a simple rest url. As a practice project I wanted to build a new REST API for this new part of the web app in Django/Node all by myself, and the … -
Django: How to specify a URL as a slug in django template?
I am trying to create a django template that has links to other pages (in particular static images, each with their own html template), but I am trying to move away from hardcoding a url and view for each one, instead I want to capture them all with a general slug URL, and a view that takes the slug as input. My slug URL in urls.py is working fine, when I manually input the slug field in the full URL it links to the correct template and directs me to the correct page. However when I try to reference any of links as slugs from the 'cside' template I keep getting the error: NoReverseMatch at /plots/cside Reverse for '2E_C' not found. '2E_C' is not a valid view function or pattern name. Basically, I want the 'cside' page to have links that are slugs. Can anyone tell me what I am missing, I have tried everything! Here is my urls.py from django.urls import re_path, path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views from .views import mode urlpatterns = [ re_path(r'^cside$', views.cside, name='cside'), re_path(r'^lside$', views.lside, name='lside'), re_path(r'^home$', views.home, name='home'), #re_path(r'^2E_C$', views.m2E_C), re_path(r'^4M_C$', views.m4M_C), re_path(r'^6E_C$', views.m6E_C), re_path(r'^6M_C$', views.m6M_C), re_path(r'^8E_C$', views.m8E_C), re_path(r'^2E_L$', views.m2E_L), … -
__init__.py issue in django test
I have an issue with running a test in my Django project, using the command python manage.py test. It shows: user:~/workspace/connector$ docker-compose run --rm app sh -c "python manage.py test" Creating connector_app_run ... done Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK I was debugging it and I know that it's probably a "init.py" file. If I'm deleting file init.py from app.app (I have read somewhere that it can help) then I'm receiving an error: ====================================================================== ERROR: app.tests.test_secrets (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: app.tests.test_secrets Traceback (most recent call last): File "/usr/local/lib/python3.9/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/lib/python3.9/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/app/app/tests/test_secrets.py", line 12, in <module> from app.app import secrets ModuleNotFoundError: No module named 'app.app' why did this error occur? Pycharm projects normally see import and what I know from version 3.4 it's not obligatory to put init.py into folders to make the package. This is the github link: https://github.com/MrHarvvey/connector.git Can you explain me what I'm I doing wrong here? -
how to add a profile object by using objects.create method
simply my error is this Exception has occurred: TypeError User() got an unexpected keyword argument 'User' here is the data I receive from the post request in view.py if request.method == "POST": student_surname = request.POST.get('student_surname') student_initials = request.POST.get('student_initials') student_birthday = request.POST.get('student_birthday') student_username = request.POST.get('student_username') student_email = request.POST.get('student_email') student_entrance = request.POST.get('student_entrance') student_contact = request.POST.get('student_contact') student_residence = request.POST.get('student_residence') student_father = request.POST.get('student_father') student_other_skills = request.POST.get('student_skills') student_sports = request.POST.get('student_sports') student_password = request.POST.get('student_password') I can create user object it's working in view.py user = User.objects.create_user( username=student_username, email=student_email, password=student_password ) some data is related to profile in view.py student_profile = User.objects.create( User=user, #Error line surname=student_surname, initials=student_initials, entrance_number=student_entrance, email=student_email, father=student_father, skills=student_other_skills, sports=student_sports, birthday=student_birthday, contact=student_contact, address=student_residence, ) student_profile.save() profile definition in models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) surname = models.CharField(max_length=50) initials = models.CharField(max_length=10, blank=True) entrance_number = models.CharField(max_length=10, blank=True) email = models.EmailField(max_length=254, blank=True) father = models.CharField(max_length=50, blank=True) skills = models.CharField(max_length=50, blank=True) sports = models.CharField(max_length=50, blank=True) birthday = models.DateField(null=True, blank=True) contact = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) # other fields here def __str__(self): return self.user.username I believe the error is in User = user line can somebody tell me how to initialize this profile object correctly AND save record in the database at the time of … -
Django Rest Framework ignores default value
Any idea why does Django Rest Framework ignore default values? class MyClass(models.Model): some_field = models.CharField(default='Yes') class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyCLass fields = ['some_field'] class MyClassListCreateAPIView(ListCreateAPIView): queryset = MyClass.objects.all() serializer_class = MyClassSerializer When I send {'some_field': None} /null/something like this. I always get: Bad Request: /myurl/ [02/Dec/2022 16:44:59] "POST /myurl/ HTTP/1.1" 400 114 When changed to: class MyClass(models.Model): some_field = models.CharField(default='Yes', blank=True, null=True) it works but always sets the NULL value. Is this expected behaviour? Should I change the mechanics of my POST request to include changing value to default when user doesn't provide one? -
django_quill modelform QuillField does not render in form
I cannot seem to get QuillField to render in my form. Every other field renders just fine. I cannot find what I am missing here. I have gone over django_quill_editor oficial docs and scoured google. I am at a loss. Here are the files. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'blog', 'django_quill', forms.py from .models import UserPost class UserPostForm(forms.ModelForm): class Meta: model = UserPost fields = ('title', 'image', 'content') models.py from django_quill.fields import QuillField class UserPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) image = models.ImageField(upload_to='images/', blank=True, null=True) categories = models.ManyToManyField('Category', related_name='userposts') content = QuillField() date_published = models.DateField(auto_now_add=True) url = models.SlugField(max_length=500, unique=True, blank=True, editable=False) def save(self, *args, **kwargs): self.url = slugify(self.title) super(UserPost, self).save(*args, **kwargs) views.py from .forms import UserPostForm def userposts_create_view(request): form = UserPostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect("landingpage:home") context= {'form': form,} return render(request, 'userpost_create.html', context) -
Django, looping through openweather icons always displays the last icon instead of appended city icon
I am trying to build out a weather app using openweather api and what I want to do is replace the icon png's with my own customized icon set. In order to do this, I have referenced the openweather api png codes as seen here: https://openweathermap.org/weather-conditions. I have written some code that states if this code equals '01d' then replace the icon code with my custom data image src. The issue is when looping through (after I have added a city), I am always appending the last image which in this case is the data code for '50n' rather than the correct weather code for that city. here is the code in my views.py: def weather(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=<MYAPPKEY>' cities = City.objects.all() weather_data = [] for city in cities: city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'], } icon = weather['icon'] if icon == '01d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/01d.svg' elif icon == '01n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/01n.svg' elif icon == '02d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/02d.svg' elif icon == '02n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/02n.svg' elif icon == '03d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/03d.svg' elif icon == '03n': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/03n.svg' elif icon == '04d': icon = 'https://dar-group-150-holborn.s3.eu-west-2.amazonaws.com/images/04d.svg' … -
JSON API not displaying all values on my HTML
Good day all, I am a newbie programmer, I am working on a website using Django where I use a JSON API I generated online to print the prices of cryptocurrencies. I am having a challenge as my API is not displaying all the values I want it to display on my html. please note that I've checked with console to ensure the API is working correctly and I confirmed it does but the challenge is I cannot seem to understand why I cannot print it out on my HTML. Below is my code that I am using to print the prices. The prices that is showing on my HTML is from Bitcoin to Uniswap while the remaining is not showing. My JAVASCRIPT CODE var btc = document.getElementById("bitcoin"); var eth = document.getElementById("ethereum"); var doge = document.getElementById("dogecoin"); var lite = document.getElementById("litecoin"); var bin = document.getElementById("binancecoin"); var card = document.getElementById("cardano"); var xrp = document.getElementById("ripple"); var pol = document.getElementById("polkadot"); var uni = document.getElementById("uniswap"); var btc_cas = document.getElementById("bitcoin-cash"); var sol = document.getElementById("solana"); var chain = document.getElementById("chainlink"); var poly = document.getElementById("matic-network"); var theta = document.getElementById("theta-token"); var shiba = document.getElementById("shiba-inu"); var vec = document.getElementById("vechain"); var stel = document.getElementById("stellar"); var file = document.getElementById("filecoin"); var aav = document.getElementById("aave"); … -
In Django save multiple filenames (NOT files) for multiple FileFields
In Django I would like to save multiple filenames (NOT files) for multiple FileFields in a Model. I have: 2 Models: One to hold FileFields for different file types (there are identical numbers of files for each type being submitted); the other to hold relevant info of the files. 2 ModelForms: One for each Model. 1 view: To handle the logic for getting filenames from the files and saving them, and discarding the actual file. I have searched many Stack Overflow questions and have derived something that gets me close, but is incorrect. In localhost:8000/admin/ I can see my broken attempt gets me a record for each uploaded file, BUT each record has the same data (the name of the last file in the list for each field). models.py from django.db import models from decimal import Decimal from django.core.validators import FileExtensionValidator # Model for storing related info class RelatedInfo(models.Model): info_name = models.CharField("Name", max_length=255) some_value = models.DecimalField( default=Decimal(0.1), decimal_places=2, max_digits=5 ) X_path = models.CharField(max_length=255, null=True) Y_path = models.CharField(max_length=255, null=True) # Additional fields... # Model for storing filenames class FilesModel(models.Model): related_info = models.ForeignKey( RelatedInfo, on_delete=models.CASCADE ) X_name = models.CharField(max_length=255, blank=True, null=True) X_file = models.FileField( null=True, validators=[FileExtensionValidator(allowed_extensions=["txt"])] ) Y_name = models.CharField(max_length=255, blank=True, null=True) …