Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not running. Django not found error occurs
python3 Python 3.9.6 (default, May 7 2023, 23:32:44) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. import django django.file /Users/dc/Library/Python/3.9/lib/python/site-packages/django/init.py' django also works I installed Django from pip3 in Mac m1 but it is not running your text -
Hit DB only once while filtering a queryset in Django-rest-framework
I am filtering a model under some conditions say, qs = Model.objects.filter(category=value). I am send this queryset as a response using ListModelMixin. class ModelViewset(ListModelmixin): def get_queryset(self): return Model.objects.filter(category=value) The select statement was running n times for n items which seems reduntant, Somehow I want to hit db only once and use them as Response. I tried list, but it has too much overhead and has slowed down the performance. Is there any way to acheive this by not using list, bool or remaining things as they will also execute each items which results in n queries for n items in Model. -
Why can I not deploy django project with elastic beanstalk?
I have created a zip file with all my programs and it runs well locally. For some reason elastic beanstalk gives several errors when I deploy my zip file. Such as: "Warning: Configuration files cannot be extracted from the application version my_tennis_club2. Check that the application version is a valid zip or war file." "Error: The instance profile aws-elasticbeanstalk-ec2-role associated with the environment does not exist." "Error: Failed to launch environment" I followed the tutorial https://www.w3schools.com/django/django_deploy_eb.php where I always got the same result as the tutorial up until I was gonna upload the zip file containing my entire project to elastic beanstalk -
Nested serializer get_or_create unique constraint validation error
I Have a UserModelSerializer: class UserModelSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'date_joined', 'is_active', 'is_verified', 'is_superuser', 'is_staff', 'is_hidden', 'created_date'] read_only_fields = ['id', 'date_joined', 'is_active', 'is_verified', 'is_superuser', 'is_staff', 'is_hidden', 'created_date'] and a UserBanModelSerializer: class UserBanModelSerializer(ModelSerializer): user = UserModelSerializer() class Meta: model = UserBan fields = ['id', 'user', 'until', 'reason', 'description', 'created_date'] read_only_fields = ['id', 'created_date'] def create(self, validated_data): user_data = validated_data.pop('user') user, created = User.objects.get_or_create(**user_data) user_ban = UserBan.objects.create(user=user, **validated_data) return user_ban I want my representation to have complete User data and also i want the frontend developer to be able to send the represented data back to server without any problem(if I only add UserModelSerialzer to to_representation method of UserBanModelSerializer frontend developer needs to send user id instead of the whole user data But when I use is_valid method on serializer I get this exceptions: "username": [ "A user with that username already exists." ], "email": [ "A user with that email already exists." ] I dont want to create a User when I want to create a UserBan I only want it to be created if the User is not found -
How to connect Python and Next.js?
I have been working on django/next.js project. but I'm stuck in connection part between python and next.js. as I'm full stack developer, I have experienced to connect between laravel and react. but this case is first to me. please help me so that I can accomplish as soon as possible. I was just building basic python project. I wanna know detail steps because this is urgently task. -
What are the main differences between django and rest framework?
i have used rest framework, but i didn't know the difference between django and rest framework either. main difference between django and rest framework. i need the exact differences between django and rest framework. #django, #restframework. -
Editing or moving site-packages in django
In django ive installed the django-two-factor-auth package through my virtual environment, and it is installed in /env/Lib/site-packages/. What is best practice of editing such a package? If for example i want to edit the urls (or the views)? Do i move or copy the packages from the env/ into my django project as an app? My existing project setup is: /env/ /project/ -/app1/ -/app2/ As im quite new to django, im looking for best practices before i start making my own judgements. As my /env/ is not tracked by git, i cant imagine i should be editing the package directly within. I tried copying the entire django-two-factor-auth package into my project, but im not sure how to register it correct in settings.py (im also wary of having a copy of the same library in both /env/ and /project/). -
How to accept Ngrok connections on Docker Django
I'm trying to create tunnel connection and accept Stripe payment success requests. docker-compose.yml: ... django: ... ports: - '8000:8000' ngrok: container_name: ecommerce_ngrok_ctnr image: ngrok/ngrok:latest restart: unless-stopped command: start --all --config /etc/ngrok.yml ports: - 4040:4040 depends_on: - django volumes: - ./ngrok/ngrok.yml:/etc/ngrok.yml ngrok.yml: version: 2 authtoken: *** tunnels: django: proto: http addr: localhost:8000 inspect: true The error code is: ERR_NGROK_8012 dial tcp 127.0.0.1:8000: connect: connection refused -
Dockerized Django application cannot connect to native PostgreSQL. Ubuntu 22.04.3 DigitalOcean
On my DigitalOcean droplet, my running Django docker-compose container can easily connect to PostgreSQL if it's also a container, which is not the preferred way for me. I have tried many approaches to connect to my database from django conainer. First, I edited postgresql.conf: listen_addresses = '*'. Also I added my droplet's ip address to pg_hba.conf and even allowed all connections: host all all 0.0.0.0/0 md5 host all all 172.28.0.2/16 md5 Also I allowed all connections to 5432 port in firewall. It's for testing though. OpenSSH ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 5432 ALLOW Anywhere 5432/tcp ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) 5432 (v6) ALLOW Anywhere (v6) 5432/tcp (v6) ALLOW Anywhere (v6) In my django settings, I am setting my droplet's ip address as database host, and the port is 5432. What did I miss? What could be the reason? I've read that /16 in 172.28.0.2/16 is likely to be the reason, because you can set it to be 32 or 16 or even 8 and it's said to vary depending on the droplet's ip. I tried some of them but it didn't really help. I always … -
Render Serialized data in django rest framework
I'm new to django and web development and wanna know how to render html with serialized data which i use for my api's here's my files: Views.py class IngredientsViewSet(ModelViewSet): http_method_names = ['get','post','patch','delete','options','head'] permission_classes = [isAdminOrReadOnly] queryset = Ingredients.objects.all() def get_serializer_class(self): if self.request.method in ['POST','PATCH','delete']: return IngredientCreateSerializer return IngredientSerializer Models.py class Ingredients (models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, related_name='products') def __str__(self) -> str: return self.title Serializer.py class IngredientSerializer (serializers.ModelSerializer): class Meta: model = Ingredients fields = ['id','title','unit_price','description','collection'] class IngredientCreateSerializer (serializers.ModelSerializer): class Meta : model = Ingredients fields = ['id','title','slug','unit_price','description','collection','inventory'] class CollectionSerializer(serializers.ModelSerializer): # featured_ingredient = IngredientSerializer() class Meta : model = Collection fields = ['id','title','featured_ingredient'] I want to render a html file and pass my Ingredient model data to it. -
How to return to fetching if the route needs @login_required, after logging the user in
I am building a project using Django as a backend and JavaScript for the client-side, one of the implementation for this project is a like button, sending the data if the user clicked the like button. fetch(`/like/${like.dataset.post_id}`, { method: 'PUT' }) .then(response => { if (response.redirected) { window.location.href = response.url; return; } else { return response.json()} }) .then(message => { // error do nothing if (message.error) { // show the error to the user ... console.log(message.error); } else { if (message.liked) { like.className = "liked like"; } else { like.className = "not-liked like"; } // get the html tag where the number of like is inserted. const text = like.parentElement.querySelector('.like-number'); // then insert the number inside that text.innerHTML = message.like; // convert the number Ex. 10000 => 10K changeNumber(text); } }) .catch(error => console.log(error)) This is the route where it fetch the data @csrf_exempt @login_required(login_url='/login') def like(request, post_id): if request.method != 'PUT': return JsonResponse({"error": "Method not found!"}, status=405) # Get the post post = Post.objects.get(pk=post_id) # remove the user from the like list if post.like.contains(request.user): post.like.remove(request.user) post.save() like = post.like.all().count() # return message, no of like and boolean expression return JsonResponse({"success": f"{request.user} Liked post by { post.user }", "like": like, … -
Troubleshooting a Django collectstatic Error After Upgrading to Version 4.2
I'm encountering an issue with the collectstatic command, which persisted until I upgraded Django to version 4.2. When I execute ./manage.py collectstatic, it throws an error that says, my_path/myfile.map' could not be found with <project.assets.CustomStorage object at 0x7f1af8be4370> and I'm struggling to understand the cause. In my settings.py file, I've configured the STORAGES dictionary as follows: STORAGES["staticfiles"] = {"BACKEND": "project.assets.CustomStorage"} Where CustomStorage is a custom class defined as: class CustomStorage(ManifestFilesMixin, S3Boto3Storage): location = settings.AWS_ASSETS_BUCKET_FOLDER querystring_auth = False bucket_name = settings.AWS_ASSETS_BUCKET_NAME Would you be able to assist me in resolving this issue? -
Django queryset from url parameter issue
I have multi models, and I want to have one listview to display it. I would like to have something like this: model = self.kwargs['name'] queryset = model.objects.all() but seems not working.... any help please ? Regards, -
multilevel user admin in django
Need to create multi level users with roles having same validation for the models as that specified in admin.py, only that each of these users will have different roles.eg. Customer can have different custom_users with diff. roles. A customer can create multiple such custom users with different roles. Each customer can see only his own records in the admin panel. Models: Customer, Custom_user(customer f.key), Role(permission) , customer_customuser(custom_user_id,role_id), But I need to use the same permissions as available in the original django default admin panel for the diff.models like add,edit,delete, view. But have also customized it in admin.py such that each customer can administer using changelist_view and filtering the queryset objects accordingly. How can this be achieved. The models: class Role(models.Model): name = models.CharField(max_length=100, unique=True) permissions = models.ManyToManyField(Permission) def __str__(self): return self.name class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(username=username, email=email) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): user = self.create_user(username, email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # Specify a related_name below role … -
Adding WeasyPrint to Dockerfile - Django Cookiecutter
I am new to Docker and have never used WeasyPrint before. (I need to create Javascript charts.) I use the django Cookiecutter setup for Docker. So what do i need to change in this Dockerfile to include Weasy? I found this on Weasy setup page. https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#ubuntu-20-04 Not sure what to add or where? Or even if this is how to set up? Thank you. # define an alias for the specific python version used in this file. FROM python:3.11.5-slim-bullseye as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Python 'run' stage FROM python as python-run-stage ARG BUILD_ENVIRONMENT=local ARG APP_HOME=/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} # devcontainer dependencies and utils RUN apt-get update && apt-get install --no-install-recommends -y \ sudo git bash-completion nano ssh # Create devcontainer user and add it to sudoers RUN groupadd --gid 1000 … -
MacOs M2Crypto for Django error I don't know how to solve it
Raised when I execute 'python manage.py xxxx' in Django's virtual environment ImportError: Dlopen (/ Users/xieyang/Desktop/nagain shyun_virtualenr/lib/python3.8 / site - packages/M2Crypto / _m2crypto retaining - 38 - Darwin. S o, 0x0002): symbol not found in flat namespace (_X509_it) But I can start my project normally in the IDE, I don't know how to solve it. Please help me My environment is Mac m2,python is 3.8. I try not to use virtual environment but I still get the above problem. -
django-import-export Customize Admin Missing Field Error
I am using django-import-export to manage csv uploads. I have the following import working vanilla and now want to extract the 'league' and 'season' fields from the .csv and instead choose them via form fields in the admin interface. I am able to select values but when I submit I receive the following error: Line number: 1 - (1048, "Column 'league_id' cannot be null") I followed the code example here: https://django-import-export.readthedocs.io/en/latest/advanced_usage.html#customize-admin-import-forms Here's the relevant code: # admin.py class TeamsSeasonResource(resources.ModelResource): # https://django-import-export.readthedocs.io/en/stable/advanced_usage.html#importing-model-relations ballpark = fields.Field( column_name='ballpark', attribute='ballpark', widget=ForeignKeyWidget(Ballpark, field='park_name')) team = fields.Field( column_name='team', attribute='team', widget=ForeignKeyWidget(Team, field='team_acronym')) league = fields.Field( column_name='league', attribute='league', widget=ForeignKeyWidget(LeaguesSeason, field='id')) season = fields.Field( column_name='season', attribute='season', widget=ForeignKeyWidget(Season, field='season_year')) class Meta: model = TeamsSeason import_id_fields = ('ballpark', 'team', 'season', 'league') class TeamsSeasonAdmin(ImportMixin, admin.ModelAdmin): list_display = ('id', 'season','team') resource_classes = [TeamsSeasonResource] import_form_class = TeamSeasonImportForm confirm_form_class = TeamSeasonConfirmImportForm def get_confirm_form_initial(self, request, import_form): initial = super().get_confirm_form_initial(request, import_form) # Pass on the value from the import form to # the confirm form (if provided) if import_form: initial['league'] = import_form.cleaned_data['league'] initial['season'] = import_form.cleaned_data['season'] return initial pass admin.site.register(TeamsSeason, TeamsSeasonAdmin) # forms.py from django import forms from import_export.forms import ConfirmImportForm, ExportForm, ImportForm from .models import * class TeamSeasonImportForm(ImportForm): league = forms.ModelChoiceField( queryset=LeaguesSeason.objects.all(), required=True) season = forms.ModelChoiceField( queryset=Season.objects.all(), … -
How to effectively use django-sso for Single Sign On
Am using django-sso package for SSO(Single Sign On), i have installed it and set the configuration by following the documentation and everything seems to work well. But my questions now is According to the documentation, to get additional fields on the client side, we put this line of code in the Server settings.py . # SSO settings section in the gateway side are optional SSO = { # Timeout for the communication with subordinated services. (OPTIONAL) # This timeout is defined in seconds with a default value of 0.1s # (100ms) per registered service. 'SUBORDINATE_COMMUNICATION_TIMEOUT': 0.1, # Additional fields. (OPTIONAL). For more details look to part # named as "Send additional data to subordinated services" 'ADDITIONAL_FIELDS': ('first_name', 'last_name', 'phone_number'), } So my question is how can i get these first_name, last_name and phone_number on the client side How can i make the login page more secure by adding Multi factor Authentication like Kagi or django-mfa How can i add Social Auth to work with it **What i have tried ** In my server settings.py, i added # SSO settings section in the gateway side are optional SSO = { # Timeout for the communication with subordinated services. (OPTIONAL) # This … -
Codecov coverage considers wrong files on Django app
I have been using codecov on my projects to produce test coverage, among others, a Django app. I could upload by hand after each push, but there are GitHub actions to perform this automatic action for me, right!? I wrote the yml file below to perform such a pipeline. However, there are two problems, from my perspective: It must consider ONLY application folder src! On the current state, it considers folders setup, src and tests. Your help will make me help others develop nice apps in Django. name: Coverage CI on: [push, pull_request] jobs: poetry: runs-on: ubuntu-20.04 defaults: run: shell: bash strategy: max-parallel: 42 fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10"] steps: #---------------------------------------------- # check-out repo and set-up python #---------------------------------------------- - name: Check out repository uses: actions/checkout@v3 - name: Set up python id: setup-python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} #---------------------------------------------- # install & configure poetry #---------------------------------------------- - name: Install and configure Poetry uses: snok/install-poetry@v1 with: virtualenvs-create: true virtualenvs-in-project: true #---------------------------------------------- # load cached venv if cache exists #---------------------------------------------- - name: Load cached venv id: cached-poetry-dependencies uses: actions/cache@v3 with: path: .venv key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }} #---------------------------------------------- # install dependencies if cache does not exist #---------------------------------------------- … -
Rest Api not found in django application
I'm trying to do a simple app in django, I'm a beginner and I'm having some problems; My error is: AttributeError: 'function' object has no attribute 'get_extra_actions' My view: class UserViewSet(viewsets.ViewSet): serializer_class = UserSerializer def list(self, request): users = [ {'id': 1, 'name': 'John', 'phone': '3382496345','email': 'john@example.com'}, {'id': 2, 'name': 'Jane', 'phone': '3382496345','email': 'jane@example.com'}, ] serializer = self.serializer_class(users, many=True) return Response(serializer.data) router = routers.DefaultRouter() router.register('users',UserViewSet.as_view({'get':'users'}), basename='user') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] I don'know wher is my error -
error django.db.utils.ProgrammingError: cannot cast type bytea to boolean
i want to change bytea type to boolean in is_reply field and migrate it but i can not do it even i delete model. i registerd this model in admin panel. i use postgresql class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ucomments') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pcomments') reply = models.ForeignKey('self', on_delete=models.CASCADE, related_name='rcomments', blank=True, null=True) is_reply = models.BooleanField(default=False) body = models.TextField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' -
I used if form. is_valid() but it gives a typerror that says: any() takes exactly one argument (0 given)
def listing_view(request, listing_title): list_id = get_object_or_404(Listing, title=listing_title) form = BidForm() # Define the form outside of the if block if request.method == 'POST': form = BidForm(request.POST) if form.is_valid(): bid_input = form.cleaned_data['bid_input'] print(bid_input) if bid_input <= list_id.current_price: messages.error(request, 'Bid must be greater than the current price.') print(messages.error) return redirect('auctions:view', listing_title=listing_title) else: bidding_instance = Bidding() bidding_instance.bidder = request.user bidding_instance.bid = list_id bidding_instance.bid_amount = bid_input bidding_instance.save() messages.success(request, 'Bid Successfully Input') print(bidding_instance.objects.all()) return redirect('auctions:new', listing_title=listing_title) return render(request, 'auctions/view_listing.html', {"list_id": list_id, "form": form}) I am expecting for it to accept the bid_input then go to either a newpage or thesame page with a message but it gives a any() error instead..kindly help check it out -
Many-to-Many relationship saving on one form, not on the other
i'm at a loss, i have some code to save a modelform using the FilteredSelectMultiple widget on a many-to-many relationship. It does work on 2 out of the 4 forms. But i can't figure out why it wont work on the last 2. any help? Here is the code for one of the 2 that is working: forms.py: class SubDomainForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.required = False domains = forms.ModelMultipleChoiceField(queryset=Domain.objects.all(), label=('domains'), widget=FilteredSelectMultiple(('domains'), False, )) subdomains = forms.ModelMultipleChoiceField(queryset=SubDomain.objects.all(), label=('subdomains'), widget=FilteredSelectMultiple(('subdomains'), False, )) class Media: extend = False css = { 'all': [ '/static/admin/css/widgets.css' ] } js = ( '/static/assets/admin/js/django_global.js', '/static/assets/admin/js/jquery.init.js', '/static/assets/admin/js/core.js', '/static/assets/admin/js/prepopulate_init.js', '/static/assets/admin/js/prepopulate.js', '/static/assets/admin/js/SelectBox.js', '/static/assets/admin/js/SelectFilter2.js', '/static/assets/admin/js/admin/RelatedObjectLookups.js', ) class Meta: model = SubDomain fields = ('domains', 'subdomains', 'name', 'description') widgets = {'description': CKEditorWidget(),} models.py: class SubDomain(models.Model): domains = models.ManyToManyField(Domain, verbose_name='Link to Domain', blank=True) subdomains = models.ManyToManyField('self', verbose_name='Link to other SubDomain', blank=True) name = models.CharField(max_length=50) description = RichTextField() def __str__(self): return f"{self.name}" class Meta: verbose_name_plural = ' SubDomain' Html: <!--- api\formfiller\templates\subdomain_form.html --> {% load static %} {% block head %} <head> {{ form.media }} {{ form.media }} <style> .ck.ck-editor__main > .ck-editor__editable:not(.ck-focused) { width: 800px; height: 300px; } .ck-rounded-corners .ck.ck-editor__main > .ck-editor__editable, .ck.ck-editor__main > .ck-editor__editable.ck-rounded-corner { width: … -
How can I set a default value in an inline admin?
Let's say I have a NarratorAdmin page to display and change details of the Narrator model. It includes a BookInline where the narrator's Books can be changed, added or deleted. Not all of Book's fields are present in the BookInline-- only the most "important" ones. Let's further imagine that Book has a "category" field, with values like print, digital, hybrid, audiobook. When a Book is created from the NarratorAdmin page, I want to automatically set its "category" to "audiobook". "category" is NOT included in BookInline.fields. The user doesn't need to see it and it doesn't make sense for them to change it. I've tried the following methods (all suggested by AI): def get_formset(self, request, obj=None, **kwargs): formset = super().get_formset(request, obj, **kwargs) formset.form.base_fields['category'].initial = "audiobook" return formset (Doesn't work because "category" is not in base_fields) def save_model(self, request, obj, form, change): obj.category = 'audiobook' super().save_model(request, obj, form, change) (After adding some print statements, I don't think this method is actually being called) def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.category = 'audiobook' instance.save() formset.save_m2m() Similar to the above, this one doesn't seem to be getting called when I expected it to. -
Django allowing duplicate records despite having unique_together constraints
My django model has three fields, company_id jurisdiction businessStartDate I have added below constraints, class Meta: app_label = 'payroll' unique_together = ( 'Company_id', 'jurisdiction', 'businessStartDate', ) Despite adding these constraints and using get_or_create to add new records, I am seeing duplicate records being inserted in the table. Here is the snapshot of mysql table, mysql> select Company_id, jurisdiction, businessStartDate from companyjurisdiction; +--------------+--------------+-------------------+ | Company_id | jurisdiction | businessStartDate | +--------------+--------------+-------------------+ | 496395 | CA | NULL | | 496395 | CA | NULL | | 496395 | FED | NULL | | 496395 | MI | NULL | +--------------+--------------+-------------------+ Please suggest what I am doing wrong here? Does having NULL values in businessStartDate column creating this issue?