Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
need to get data for choice fields in Django form a loop?
The choice field required in django is in the following format new_choices = ( (1, 'Data 1'), (2, 'Data 2'), (3, 'Data 3'), (4, 'Data 4'), (5, 'Data 5'), (6, 'Data 6'), (7, 'Data 7'), ) I am trying to get the data from db but the data is not getting properly CHOICES = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1) test =([('(' + str(p.head) + '-' + p.detail + ')') for p in CHOICES]) len_of_test = len(test) new_choices =[] for n in range(len_of_test): new_choices = '(' + str(n) + "," + test[n] + ')' The output I am getting from the above code is new_choices = ['(0,(Data 0))','(1,(Data 1))','(2,(Data 2))',...] -
Compile twice in django_tex
I need to compile a .tex file twice with django_tex in order for the table of contents to load correctly. Is there a way to tell the interpreter in django_tex to run the compiler twice (I use pdflatex)?? Code: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \begin{document} \tableofcontents \section{Introduction} Introduction text. \section{Second section} Second section text. \end{document} -
if add new blog in database than sent mail to all subscriber to notified current blog in Django
Note: Add new blog only admin panell. model.py class blog(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) blog_id = models.AutoField(primary_key=True) blog_title=models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=500, blank=True) tags = TaggableManager() blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True) blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True) written_by = models.CharField(max_length=200, default='Prymus Brandcom') image_banner= models.ImageField(upload_to='image_banner') medium_thumbnail = models.ImageField(upload_to='medium_thumbnail') content = RichTextField() # RichTextField is used for paragraphs is_authentic=models.BooleanField(default=False) class Meta: # Plurizing the class name explicitly verbose_name_plural = 'blog' def __str__(self): # Dundar Method return self.blog_title def save(self, *args, **kwargs): # Saving Modefied Changes if not self.slug: self.slug = slugify(self.blog_title) #super(blog, self).save(*args, **kwargs) super(blog, self).save(*args, **kwargs) def snippet(self): return self.content[:300] and it's my subscriber table: class subscriber(models.Model): name=models.CharField(max_length=150,default="") email=models.EmailField(max_length=100) def __str__(self): # Dundar Method return self.name Add new blog in blog table than send mail to all registerd user in subscriber table ??? -
Django vs Django Rest framework , security concern
A traditional website using Django over HTPPS vs Same website using Django rest framework and React JS or other platforms to consume the API. Which would be more secure against DDOS,Spoofing,etc like security breaches ? I hope Rest API is on HTTP and its less secure. Does enabling HTTPS on the REST API server make its API Secure ? -
How can updatee manytomanyfield data
i am trying to update manytomany field data in django. Here is my view: def editRolesView(request, role_id, shop_id): shopId = get_object_or_404(Shop, pk=shop_id) roleId = get_object_or_404(Roles, pk=role_id) permissions = Permission.objects.filter( shop=shopId.id, ) if shopId.user == request.user: if request.method == "POST": permissions = request.POST.getlist("permissions") # cnv_pp = ''.join(permissions) roleId.role_title = request.POST.get("role_title") roleId.shop = Shop.objects.get(id=shopId.id) roleId.save() roleId.permissions = roleId.permissions.set(permissions) roleId.save() return HttpResponse("Edited") # roleId.permissions_set.all() args = { "shopId": shopId, "roleId": roleId, "permissions": permissions, } return render(request, "roles/edit-role.html", args) else: return redirect("warning") Here i tried to update manytomanyfield data. Here is my Model class Permission(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) permission_title = models.CharField(max_length=255) class Meta: ordering = ["-id"] def __str__(self): return self.permission_title class Roles(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) role_title = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) class Meta: ordering = ["-id"] def __str__(self): return self.role_title Whenever i try t save the data it says this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. The data is saving but its throwing this error. Is there any way to solve this issue ? Here is my template <form action="" method="POST"> {% csrf_token %} <label>Set Role Title</label></br> <input type="text" name="role_title" value="{{ roleId.role_title }}"><br> {% for p in roleId.permissions.all %} <input … -
How to return to previous version of pip install in django
I have recently downloaded a django project from github, and I downloaded all of the pip install requirements using: pip install -r requirements.txt However, I realised that I did not set a virtual env for this project, so it seems that the pip installs have affect the entire computer. I am now getting an error like below when I try to runserver my other django projects: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration leads.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') Traceback (most recent call last): File "C:\Users\jsooh\projects\Sevenenglish\11-3\manage.py", … -
How to retrieve all fields from a ForeignKey after a filter query in django
I have the following models using django class Action(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, db_index=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Concert(models.Model): action = models.ForeignKey(CoreAction, on_delete=models.SET_NULL, related_name="action_concert") is_live = models.BooleanField(default=False) name = models.CharField(max_length=100, unique=True) created = models.DateTimeField(auto_now_add=True) I am trying to display a list of Concert live, at the same time make sure that I get all the fields from the action table for each instance associated to it. concerts = Concert.objects.filter(is_live=True).values("id", "name") current result => All the concerts live This is the first step but i am stuck trying to join each instance of the list to it correspondent fields in Action. Any help would be helpful, thanks -
My GoDaddy domain serves a blank page when I connect it with my Heroku App
Recently, I built a Heroku app using Django and React. The app works wonderfully, however when connected to GoDaddy's domain, it serves a blank page. I won't say anything else, partly because I don't know what information is necessary, but request you to ask the right question for me to provide more information. Thanks. -
Django says: too many values to unpack (expected 2)
I'm using Django. In the upload_book function, I generate a 10-digit code for each book and I identify and distinguish two books from one another by their code, rather than their primary key. However, I get an error in the generate_code function: ValueError at /main/upload_book/ too many values to unpack (expected 2) Here is the generate_code() function with required imports: import random, string def generate_code(max_length): code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) while len(Book.objects.filter(code)) != 0: code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) return code I did the extra bit over there to prevent two books being of the same code, however low the probability of that might be with 629 possible combinations. And here's my upload_book() function: @login_required def upload_book(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('description') author = request.POST.get('author') code = generate_code(10) owner = request.user if 'thumbnail' in request.FILES: thumbnail = request.FILES['thumbnail'] book = Book(title=title, description=description, author=author, thumbnail=thumbnail, owner=owner, code=code) book.save() return redirect("/main/all_books/") else: return render(request, 'main/upload_book.html') And my Book model in models.py: class Book(models.Model): title = models.CharField(max_length=1000, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) description = models.TextField() author = models.CharField(max_length=1000, blank=True, null=True) thumbnail = models.ImageField(upload_to='book_thumbnails', blank=True) creation_date = models.DateTimeField(default=timezone.now) status = IntegerField(default=1) min_age = models.IntegerField(blank=True, null=True) … -
Add one field to User
After I switched my Abstract User my login page not on the admin gets a 500 server error. Also my admin gets a weird extension while logged in /pages/profile/. All I wanted to do was add a single field to the user so they can upload a file. models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='users/', null=True, blank=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Profile class CustomUserAdmin(UserAdmin): pass admin.site.register(Profile, CustomUserAdmin) settings.py # Extends default user with additional fields AUTH_USER_MODEL = 'pages.Profile' -
How to add fields with default values to the User model in Django
I need to add fields to the User model with default values that will not be displayed in the registration form but I am new to Django. How can I implement it and what am I doing wrong? models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): level = models.IntegerField(default=0) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import CustomUser class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите ваше имя'})) email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control', 'placeholder': 'введите вашу почту'})) password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите пароль'})) password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'подтвердите ваш пароль'})) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) for field_name in ['username', 'email', 'password1', 'password2']: self.fields[field_name].help_text = None class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') views.py: from django.contrib.auth import logout from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm, LoginUserForm class RegisterUser(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = 'users/register.html' -
django rest framework: building 2 separate auth and service system
how to implement 2 separate django rest framework system 1 for auth and 1 for service the goal is you get your auth from one api and use other api for services which use the auth for authentication and permission of it's services. my question is on Django rest framework and have 1 database is preferable for me but if you have answer and road to implementation such system with multiple database it would be appreciated too. i want to build entire system for authentication and permission. so i can integrated it with all of my other services -
How do I access the admin console in django application with elastic beanstalk?
So I am following the tutorial on “Deploying a Django application to Elastic Beanstalk”, but I am getting stuck on when I am trying to access the admin console. When I do go to the admin site(Ex: http://djang-env.p33kq46sfh.us-west-2.elasticbeanstalk.com/admin/), I do not see the styling applied even though I did add the static root under the settings.py file. What I see instead is a non-styled admin page, and when I try to log in, I get a Net gear block page telling me to go back. The things I am doing different from the tutorial are using the commands winpty python manage.py createsuperuser for creating the superuser and using source ./Scripts/activate. What I am using: django==3.2.9; python==3.7.9; git bash; windows machine Any help is greatly appreciated. -
Django backend on port 8083 can't parse AJAX CORS POST request served from gulp web page on port 8081
On Linux Debian Bullseye, I am running a gulp HTML server on port 8081, and a Django backend on port 8083. I am trying to POST a relatively large JSON document from a static page using JQuery's AJAX feature. After properly setting up the django-cors-headers module, with MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware" ] , CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS on settings.py, I coded the following HTML view on views.py, with the @csrf_exempt decorator in place since I'm running everything on localhost: from django.views.decorators.csrf import csrf_exempt @csrf_exempt def processOrder(request): leasing_order_unicode = request.body.decode("utf-8") print(request.POST.__dict__) print(request.POST["leasing_order"]) return HttpResponse(leasing_order_unicode, headers={ "Access-Control-Allow-Origin": "http://localhost:8081", "Content-Type": "application/json" }) Then I added it to urls.py as follows: path("processorder", processOrder, name="processorder") I expect my Django view to be able to access the JSON string with request.POST["leasing_order"]. Instead, I get errors and failures when attempting to access it. Let serializedata() be a function that takes care of gathering all my local data into an object and then serializing it. If I POST my form data with multipart/form-data encoding as follows: export function sendOrder_multipart() { let finalorder = serializedata(); let finalorder_postdata = new FormData(); finalorder_postdata.append("leasing_order", finalorder); $.ajax({ method: "POST", url: "http://localhost:8083/orderstable/processorder", data: finalorder_postdata, processData: false, contentType: "multipart/form-data" }); } I get the following error … -
How to pass true or false value in django rest framework serializer
here is my serializer code; class RegisterSerializer(serializers.ModelSerializer): password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) email = serializers.EmailField(required=True) is_company = serializers.BooleanField(required=False) class Meta: model = CustomUser fields = [ "email", "first_name", "last_name", "is_company", "profile_pic", "password1", "password2", ] def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( ("A user is already registered with this e-mail address.",) ) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data["password1"] != data["password2"]: raise serializers.ValidationError( ("The two password fields didn't match.",) ) return data def get_cleaned_data(self): return { "first_name": self.validated_data.get("first_name", ""), "last_name": self.validated_data.get("last_name", ""), "is_company": self.validated_data.get("is_company", ""), "profile_pic": self.validated_data.get("profile_pic", ""), "password1": self.validated_data.get("password1", ""), "email": self.validated_data.get("email", ""), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) if self.cleaned_data.get("profile_pic"): user.profile_pic = self.cleaned_data.get("profile_pic") setup_user_email(request, user, []) user.save() return user Basically what I am trying to do is, when I make a request with a json format in something like postman; { "first_name": firstname, "last_name": lastname, "email": myemail, "password1": password1, "password2": password2, "is_company": true } when I pass true to is_company, I want that to change is_company value to true; but I keep getting false. I have tried using form data, but still get false … -
Django - TypeError: unhashable type: 'SQLDecodeErrorDjango '
I had everything running perfectly but I had to reinstall windows and when I tried to run the code again, it started giving me errors on user registration. I followed Vitor Freitas guide to make implement multiple user types but only differed in views as he was using class based views and I had no idea what those were at that time. I have narrowed down the problem where I am creating User table (This line: user = User.objects.create(user=account) in forms.py). Models.py class MyAccountManager(BaseUserManager): def create_user(self , email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name,last_name, password): user = self.create_user( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email',max_length=50,unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_user = models.BooleanField(default=False) is_Manager = models.BooleanField(default=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return … -
Dictionary only adds in the last key value pair in for loop
I have a for loop that goes through a list of cities and assigns them each a total_city_value. I am trying to get each unique total_city_value created during the for loop added to the dictionary however it seems to be only keeping the final total_city_value in the for loop when I print the dictionary. for broad_variable in broad_variable_list: # check if the current broad variable is equal to the first broad variable the user chose if broad_variable == broad_variable1: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable1: city_variable1_value = 1 * weight_variable1 #print("city_variable1_value",city_variable1_value) # else assign a value of 0 else: city_variable1_value = 0 # check if the current broad variable is equal to the second broad variable the user chose if broad_variable == broad_variable2: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable2: city_variable2_value = 1 * weight_variable2 # else assign a value of 0 else: city_variable2_value = 0 total_city_value = city_variable1_value + city_variable2_value city_value_dictionary[cities] = … -
How to run Django tests in Docker using GitHub Actions
I am building my first full CI/CD pipeline for a Django/React.js project. It uses 2 workflows: build.yml and deploy.yml. The build.yml first builds the images then pushes them to the GH Packages. Then it pulls the images in a new job and runs tests (though I think this is wrong as I think jobs run in parallel - haven't got to this part yet). Build.yml name: Build and Test on: push: branches: - development env: BACKEND_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/backend NGINX_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/nginx jobs: build: name: Build Docker Images runs-on: ubuntu-latest steps: - name: Checkout master uses: actions/checkout@v1 - name: Add environment variables to .env run: | echo DEBUG=0 >> .env echo SQL_ENGINE=django.db.backends.postgresql >> .env echo DATABASE=postgres >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env echo SQL_DATABASE=${{ secrets.SQL_DATABASE }} >> .env echo SQL_USER=${{ secrets.SQL_USER }} >> .env echo SQL_PASSWORD=${{ secrets.SQL_PASSWORD }} >> .env echo SQL_HOST=${{ secrets.SQL_HOST }} >> .env echo SQL_PORT=${{ secrets.SQL_PORT }} >> .env - name: Set environment variables run: | echo "BACKEND_IMAGE=$(echo ${{env.BACKEND_IMAGE}} )" >> $GITHUB_ENV echo "NGINX_IMAGE=$(echo ${{env.NGINX_IMAGE}} )" >> $GITHUB_ENV - name: Log in to GitHub Packages run: echo ${PERSONAL_ACCESS_TOKEN} | docker login ghcr.io -u ${{ secrets.NAMESPACE }} --password-stdin env: … -
Django - How to annotate a single Django object
So Django has this cool feature where you can annotate a query set as in you can add attributes to each object in a query set. For example if I have a query set of users I can annotate it with number of followers which is another table with a foreign key reference to user. This can be done with the QuerySet.annotate() function. I was wondering if this is possible for a single Django object. I have a view function that gets user info, which given a unique user UUID I return the users info in the user table as well as the number of followers and followees. 1 way to do this is just query across all follower and followee table for the uuid and create a dictionary that gets returned or annotate a single object. Is it possible to do this? views.py @api_view(['GET']) def get_user_info(request, user_uuid): is_current_user = user_uuid == str(request.user.uuid) # Return all user info including # of followers and followees models.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) class FollowUser(AbstractSimpleModel): follower = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follower_id') followee = models.ForeignKey( … -
Accessing foreign key attributes for arithmetics in django rest framework
I'm trying to calculate the length of a house relative to some adjacent neighborhoods, such that, house_size / (neighborhood[0].length + neighborhood[1].length...): class House(models.Model): house_id = models.CharField(max_length=256, primary_key=True) size = models.IntegerField() neighborhood = models.ManyToManyField('neighborhood', through='HouseNeighborhoodLink') class Neighborhood(models.Model): length = models.IntegerField() I created a table to assign several neighborhoods with a house. Also, houses can be assigned to several adjacent neighborhoods: class HouseNeighborhoodLink(models.Model): house_id = models.ForeignKey(House, on_delete=models.DO_NOTHING) neighborhood = models.ForeignKey(Neighborhood, on_delete=models.DO_NOTHING) Serializers: class LengthFromNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = Neighborhood fields = ['length'] class HouseCoverageOfNeighborhood(serializers.ModelSerializer): Neighborhood = LengthFromNeighborhoodSerializer(read_only=True) class Meta: model = HouseNeighborhoodLink fields = ['house_id', 'Neighborhood'] I'm stuck in the three dots (...), where I want to access the length attribute of all neighborhoods and then calculate the proportion to a house. I'm not sure how to access the length of each neighborhood from HouseNeighborhoodLink table: class HouseCoverageDetail(generics.ListAPIView): queryset = HouseNeighborhoodLink.objects.all() serializer_class = HouseCoverageOfNeighborhood def get_queryset(self): house_id = self.kwargs['house_id'] neighborhood = self.queryset.filter(house_id=house_id) ... return result -
"Unknown pytest.mark.django_db" when trying to run test for django-treebeard
I'm trying to run the following test from django-treebeard: In case you know what you are doing, there is a test that is disabled by default that can tell you the optimal default alphabet in your enviroment. To run the test you must enable the TREEBEARD_TEST_ALPHABET enviroment variable: $ TREEBEARD_TEST_ALPHABET=1 py.test -k test_alphabet I have Django and PostgreSQL setup via Docker: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 ENV TREEBEARD_TEST_ALPHABET=1 ENV DATABASE_USER = "postgres" ENV DATABASE_PASSWORD = "postgres" ENV DATABASE_HOST = "db" ENV DATABASE_USER_POSTGRES = "postgres" ENV DATABASE_PORT_POSTGRES = 5432 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --dev --system COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "~=3.2" djangorestframework = "*" ulid2 = "*" psycopg2 = "*" django-lifecycle = "*" django-filter = "*" django-cors-headers = "*" djangorestframework-simplejwt = "*" django-allauth = "*" dj-rest-auth = "*" django-treebeard = "*" djangorestframework-recursive = "*" [dev-packages] black = "*" django-debug-toolbar = "*" drf-yasg = "*" coverage = … -
How do I reuse a ModelForm for a through model with an additional field?
I have a Model Example and corresponding ModelForm ExampleModelForm that I use in ModelFormset ExampleModelFormset = modelformset_factory(Example, form=ExampleModelForm) I have a many-to-many through Model with an additional property. class ExampleThrough(models.Model): batch = models.ForeignKey(Batch, on_delete=models.CASCADE) example = models.ForeignKey(Example, on_delete=models.CASCADE) property = models.FloatField() Is there a way to reuse the ExampleModelForm to create a ExampleThroughModelForm that I can also use in a ExampleThroughModelFormset? I want to have all of the same fields as the ExampleModelForm plus the one new property. I don't think I can inherit from the ExampleModelForm: class ExampleThroughModelForm(ExampleModelForm): class Meta: model = ExampleThrough fields = '__all__' because the documentation has this note: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child’s Meta, if it exists, otherwise the Meta of the first parent, etc. -
Desired Outcome: I want to dynamically create and render data from a One to Many Field to a template in Django
I have two models with One to Many relationship. The Models are Parent and Child respectively. I have managed to dynamically render data from the Parent Model, but now I want to be able to put a link to to each Parent Record, such that when clicked it will create a Child record and render out the child information to the respective parent. #Models class Parent(models.Model): surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, on_delete=SET_NULL) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) views.py def display(request, pk): parents = Parent.objects.get(id=pk) child = parents.child_set.all() context = {'parents':parents, 'child':child} return render(request, 'reg/info_page.html', context) I have tried to implement the reverse relation but when I try to display the child's information, it comes up blank. div class="col-md-4 col-sm-4 text-center"> <p class="text-purple">Child Name</p> <h1>{{child.first_name}}</h1> </div> -
Django - Error when changing from GET to POST
I have a react/django application that works fine when the request is a GET request. For example, in the React part I have the following sendRequestParameters(url) { axios({ url: url, method: 'get', headers: { 'X-CSRFToken': 'csrf_token', 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8', }, params:{ 'TECHNOLOGY': JSON.stringify(this.state.technologySelectedValue), // more parameters here, all in the same format }, paramsSerializer: function(params) { return qs.stringify(params, {arrayFormat: 'repeat'}) } }).then((response ) => { console.log(response.data); }).catch((error) => { console.log(error) }) } Then, in the backend, I get the parameters and return them (this function is called in another function where the returned parameters are used, that's why there is a return statement). def extractParameters(request): TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) # more parameters extracted here, same format return TECHNOLOGY etc. That all works fine. However, I need to change to POST requests, and when I make two small modifications to do this, I get an error. In the front end request with axios, I change the method: 'get' to method: 'post'. Then, in the backend, I change TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) to TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) This gives me the following error in the terminal TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object … -
Insert bulk data into postgresql with Django
I'm using heroku and trying to create a project that uses postgresql. I have a model like this: class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLDE = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLDE, 'Gold'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=14) birth_date = models.DateField(null=True, blank=True) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) I'll use a mock data like this: insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (1, 'Lissy', 'Rissen', 'lrissen0@bloglovin.com', '105-879-7972', '2000-11-07', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (2, 'Peterus', 'Caddens', 'pcaddens1@usda.gov', '471-936-4037', null, 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (3, 'Debee', 'Ceschini', 'dceschini2@cyberchimps.com', '526-812-6447', null, 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (4, 'Inessa', 'Blogg', 'iblogg3@mail.ru', '656-866-8989', '1985-10-21', 'S'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (5, 'Charline', 'Mayberry', 'cmayberry4@statcounter.com', '609-214-0294', '1999-09-20', 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (6, 'Bunni', 'Furness', 'bfurness5@webmd.com', '926-176-0613', '2018-07-02', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (7, 'Juana', 'Double', 'jdouble6@mysql.com', '873-793-8148', '2015-03-04', 'G'); insert into store_product (id, first_name, last_name, email, …