Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'mongoengine.django'
I have been having a problem installing the dependencies from the social library. i have basically to install two dependencies, makemigrations, and migrate them normally. According to the docummentation, it states I have to run the two commands: pip install social-auth-app-django pip install social-auth-app-django-mongoengine And than add them to the INSTALLED_APPS in the settings.py file. Add in settings.py 'SOCIAL_AUTH_STORAGE = 'social_django_mongoengine.models.DjangoStorage'' Add in settings.py SOCIAL_AUTH_JSONFIELD_ENABLED = True than after all these five steps, makemigration and migrate. I'm executing the command 'docker compose exec web python manage.py makemigration` i'm also executing the command 'docker compose exec web python manage.py migrate' And the result is ALWAYS the same. ModuleNotFoundError: No module named 'mongoengine.django' The module is not being found! it is as i didn't put `'social_django_mongoengine' in the INSTALLED_APPS, which i certainly did. Tried to install diffrient versions, install it in docker container, and it didn't work. What to do? ` I have tried reinstalling the dependecies, rebuild docker containers, not it's not reading the module. Requirments.txt `asgiref==3.6.0 attrs==22.2.0 backports.zoneinfo==0.2.1 certifi==2022.12.7 cffi==1.15.1 charset-normalizer==2.1.1 cryptography==39.0.0 defusedxml==0.7.1 Django==4.1.4 dnspython==2.2.1 exceptiongroup==1.0.4 idna==3.4 iniconfig==1.1.1 oauthlib==3.2.2 packaging==22.0 pluggy==1.0.0 psycopg2-binary==2.9.5 pycparser==2.21 PyJWT==2.6.0 pymongo==4.3.3 pytest==7.2.0 pytest-django==4.5.2 python3-openid==3.2.0 requests==2.28.1 requests-oauthlib==1.3.1 six==1.16.0 social-auth-app-django==5.0.0 social-auth-app-django-mongoengine==1.0.0 social-auth-core==4.3.0 # social-auth-storage-mongoengine==1.0.0 sqlparse==0.4.3 tomli==2.0.1 urllib3==1.26.13 ` … -
rollup package splitting / code splitting
I am working on a components library (such as material-ui). I am using rollup for compiling. For the moment I can generate a single package, and to import a component such as a button, I can do it like that : import { Button } from "package-name"; Can I modify the rollup configuration to generate a separate package or chunk for each component. In other word, can I split the big-size package in separate small-size packages (one for each component) and use them in a way similar to this: import { Button } from "package-name/Button"; I start looking to the Code Splitting... But I am wandring if there is a known best practice to have this result? Is there a specific way to write the rollup.config file ? -
In Django, how can make an inline field editable only if it is null or empty?
I currently have a tabular inline that has an end_date field for a model. I want the field to only be editable if it is empty or null, and read only otherwise. Is there a way to achieve that? Currently, I have it editable regardless, but I want the data that already exists to be read only. Here is the code: class DeploymentInline(DecoratedTabularInline): model = Deployment readonly_fields = ['updated_at', 'updated_by', 'start_date', 'tool'] fields = ['tool', 'updated_at', 'updated_by', 'start_date', 'end_date', ] def has_add_permission(self, request, obj): return False I tried using get_readonly_field and checking the obj parameter, but it refers to the Project which is the admin.ModelAdmin the inline is in. -
New Angular poject in a devcontainer: Access Denied
I am developing in Visual Studio Code (Windows) using the .devcontainer. I am doing some testing using django and angular frameworks. Everything is working perfectly but when inside the container I run the command ng new angular-14-crud-example I have some problems: if after this I restart for any reason Visual Studio Code, the devcontainer does not restart anymore and returns the following error: failed to solve: error from sender: open C:\Users\user\project\angular-14-crud-example\node_modules\make-fetch-hap pen\node_modules\mkdirp: Access denied. Below are the details: Django_Dockerfile: FROM mcr.microsoft.com/devcontainers/anaconda:0-3 COPY environment.yml* .devcontainer/noop.txt /tmp/conda-tmp/ RUN if [ -f "/tmp/conda-tmp/environment.yml" ]; then umask 0002 && /opt/conda/bin/conda env update -n base -f /tmp/conda-tmp/environment.yml; fi \ && rm -rf /tmp/conda-tmp RUN pip install --upgrade pip RUN mkdir /workspace WORKDIR /workspace COPY requirements.txt /workspace/ RUN pip install -r requirements.txt COPY . /workspace/ docker-compose.yml version: '3.8' services: app: build: context: .. dockerfile: .devcontainer/Django_Dockerfile env_file: - .env volumes: - ../..:/workspaces:cached # Overrides default command so things don't shut down after the process ends. command: sleep infinity # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function. network_mode: service:db db: image: postgres:latest restart: unless-stopped volumes: - postgres-data:/var/lib/postgresql/data env_file: - .env volumes: postgres-data: devcontainer.json: { "name": "Anaconda (Python 3) & PostgreSQL", … -
How to create a subsection in django admin site of a model with some special filters?
I have a Law model and a custom command that amend Laws every 20 days. Now I want to email the admin that Laws are amended with a link redirecting to the admin site. In the admin section, I need a subsection of laws named LatestAmendedLaws that filters all the recently amended laws, so the admin can verify if laws are correctly amended. Here is the admin.py of Laws: @admin.register(Law) class LawAdmin(admin.ModelAdmin): list_display = ( 'id', 'rs_number', 'created' ) usually when a law is amended the created date updates. so we can filter with the created date. -
hi, I am using Django Framework I want to check if the mobile-no is in the database or not but I have error
I am using Django Framework I want to check if the mobile-no is in the database but I have error when I run the code it gives me only False even when the number is exist in database it gives me False can someone help me this is my code views.py @csrf_exempt def forget_password(request): mobile_no = request.POST.get('mobile_no') # verify = models.User.objects.all() # verify = models.User.objects.filter(mobile_no=mobile_no).first() verify = models.User.objects.filter(mobile_no=mobile_no).exists() if verify: return JsonResponse({'bool':True}) else: return JsonResponse({'bool':False,'msg' : 'mobile_no does not exist!!'}) -
i have one model which having foreign key with images feild and in that i have multiple images can i get them in single list like this :
Models.py class Cat_Breed_Detail(models.Model): id = models.AutoField(primary_key=True,verbose_name="id") key_name = models.CharField(max_length=35,default='',null=True,verbose_name="key_name") display_name= models.CharField(max_length=35,default='',null=True,verbose_name="display_name") def __str__(self): return self.key_name class Cat_Image(models.Model): image=models.ImageField(upload_to="ImagesCat/") cat=models.ForeignKey(Cat_Breed_Detail,on_delete=models.CASCADE,null=True,related_name='images') def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="150" height="150" />'.format(self.image.url)) else: return '(No image)' Selializer.py class CatImageSerializer(serializers.ModelSerializer): class Meta: model = Cat_Image fields = '__all__' class CatDataSerializer(serializers.ModelSerializer): class Meta: model = Cat_Breed_Detail fields = ['id','key_name','display_name','images'] response i am getting here i am getting nested response i dont want it i just want image url in images as a list not like the response i am currently getting : { "id": 9, "key_name": "abyssinian", "display_name": "Abyssinian", "image": [ { "id": 3, "image": "/media/Abyssinian_0006.jpg", "cat": 9 }, { "id": 4, "image": "/media/Abyssinian_0092.jpg", "cat": 9 } ] }, { "id": 18, "key_name": "american_bobtail", "display_name": "American Bobtail", "image": [ { "id": 5, "image": "/media/American_Bobtail_0004.jpg", "cat": 18 }, { "id": 6, "image": "/media/American_Bobtail_0057.png", "cat": 18 } ] }, { "id": 19, "key_name": "american_curl", "display_name": "American Curl", "image": [ { "id": 7, "image": "/media/American_Curl_0078.jpg", "cat": 19 }, { "id": 8, "image": "/media/American_Curl_0083.png", "cat": 19 } ] } i want to get all the images in one list not like image:{image:"...." ,image:"......"} i am new to djnago and still learning is there any way to make it done … -
Code is giving me an error: 'ManyToOneRel' object has no attribute 'related_model'
How can I retrieve a list of all foreign keys for a model in Django and access their corresponding models? I'm trying to loop through all the foreign keys for a model in Django and access the corresponding model for each foreign key. Here is my code: from django.db import models class MyModel(models.Model): # model fields for field in MyModel._meta.get_fields(): if isinstance(field, models.ForeignKey): related_model = field.related_model However, this code is giving me an error: 'ManyToOneRel' object has no attribute 'related_model'. How can I fix this and successfully retrieve a list of all foreign keys and their corresponding models for MyModel? -
check if the username in lowercase or uppercase now then get or create user if exist
check if the username in lowercase or uppercase now then get or create user if exist or firstly get or create then check if the username in lower or upper view.py def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'].lower(), email=form.cleaned_data['email']) user.set_password(form.cleaned_data['password']) user.save() if created: address = Address(label=form.cleaned_data['label'], city=form.cleaned_data['city'], area=form.cleaned_data['area'], long=form.cleaned_data['longitude'], lat=form.cleaned_data['latitude'], country=form.cleaned_data['country']) address.save() company = Company(owner=user, name=form.cleaned_data['name'], phone_number=form.cleaned_data['phone_number'], logo=form.cleaned_data['logo'], address=address, water_source=form.cleaned_data['water_source']) company.save() return super().form_valid(form) -
Django formset save() writes new object on database?
So I have MyModel: class MyModel(models.Model): name = models.CharField(_('Name'),max_length=80, unique=True) ... def save(self, *args, **kwargs): if MyModel.objects.count()>=5: raise ValidationError("Can not have more than 5 MyModels!") super().save(*args, **kwargs) # Call the "real" save() method. There are already 5 objects from MyModel on the database. I have a page where I can edit them all at the same time with a formset. When I change one or more of them, I will get the Validation Error "Can not have more than 5 MyModels!". Why is this happenning? I tought the formset was supposed to edit the existing objects, but it appears to be writing a new one and deleting the old one. What is really happening when I do a formset.save() on the database? Do I have to remove the save() method? -
Downloading dependent dropdown data in .txt file on clicking 'submit' button
I should be getting client and team as key value pair in data.txt when I hit the submit button but the file is blank. Any ideas/help/suggestions? -
How to move migrations files to outside of django project?
django-project/ migrations/ app1/ .../ src/ app1/ .../ config/ ... settings.py how to set the path in MIGRATION_MODULES in settings.py to make generated migration files appear in migrations/app1/ folder? I have tried MIGRATION_MODULES = {'contract': '..migrations.contract.db_migrations'} but got errors. -
Not able to run django app with Apache server in Mac Ventura
I am new to django app development. I am trying to use apache server for my django app in Mac OS Ventura. For this I am using mod_wsgi module to make the integration between Apache server and django app. I followed the required steps to do the setup, by making changes in httpd.conf and httpd-vhost.conf file. After the setup, I started the apache server but in the app log I am getting below error - [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Failed to exec Python script file '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752524 2023] [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Exception occurred processing WSGI script '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752667 2023] [wsgi:error] [pid 30317] [remote ::1:62168] Traceback (most recent call last): [Mon Jan 09 16:16:41.752707 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py", line 12, in [Mon Jan 09 16:16:41.752719 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.core.wsgi import get_wsgi_application [Mon Jan 09 16:16:41.752731 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/init.py", line 1, in [Mon Jan 09 16:16:41.752740 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.utils.version import get_version [Mon Jan 09 16:16:41.752751 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in [Mon Jan 09 16:16:41.752761 2023] … -
Django smart fiter transfers
I have a model Book and there are duplicated rows in that table. One of the duplicates was changed during duplicate operation. The differences between that rows are in two fields (special_id and state). E.g.: Name special_id state Idiot "0107" 1 Idiot "0106" 2 During filtering by state if i write Book.objects.filter(state=2), i'll get the books with value of state 2, So i want to exclude this book if there is the book with the same name and with the state 1 Is there any way to do this without for loop and looking by the name of every book in QuerySet? Now when quantity of books is not big the delay of for loop is not noticeable. But when they'll be enormous i think it's going to be really long delay. -
Have multiple fields from another model linked by a foreign key
I have multiple models : class Circuit(models.Model): name = models.CharField('Circuit', max_length=120) country = models.CharField('Pays', max_length=120, choices=country_choices) version = models.CharField('Version circuit', default='Grand-Prix', max_length=120, choices=circuit_version_choices) image = models.ImageField('Image noir/blanc', blank=True, upload_to='circuit_pics', default='circuit_pics/a2*1ùp6*ù.png') image_details = models.ImageField('Image détaillée', blank=True, upload_to='circuit_details', default='circuit_details/a2*1ùp6*ù.png') class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") A race event takes place in a circuit. This circuit can have multiple versions (the version field in the Circuit model gives "Version1", "Version2", as possible choices). How can I have this choice also in the Event model, so that, in the admin section, I also have the choice to pick the circuit version it will take place in. More generally, how do I add multiple fields in a model from another model linked with a foreign key ? -
Use a django template variable in django-crispy bootstrap AppendedText or PrependedText
I saw that a similar question was asked 10 years ago about buttons and that it was resolved. I was naive enough to think that maybe it was possible for other fields ^^ Have I missed something ? As said in the Title, I'm trying to use a django template variable {{ tetra }} in a Layout Fieldset AppendedText or PrependedText value, like this class AddObjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Some Text as Legend', AppendedText('userref', {{tetra}} ), but it won't work :-( I also tried with HTML tag like : PrependedText('userref', HTML("""{{tetra}}""") ), but in this case I also obtain : <crispy_forms.layout.HTML object at 0x7fb1997f8c70> Can anyone enlighten me, direct me or confirm that this is not possible? -
What is the right way to write test cases in django?
Unittest or Bultin test.Testcases or pytest I have these options. I have a socialmedia project where there is so many apis. should I only test apis with request methods or should I test every single views, serializers etc. Right now i m doing with django test.Testcases -
How to show if users already enable two-factor-auth on Django admin
Is there a way to show user two-factor-auth status on Django admin user list? From the documentation, I only found this manage.py two_factor_status user, which only show user OTP status on terminal. -
Django: How can I get the child element ListView and DetailView in the same Template?
I have a model for Letter_box and Letter. I want to display the "list of received letters" and "contents of the selected Letter" on the detail page of each Letter_box, but I don't know how. I can display the contents of the Letter_box and the list of Letter, but it is difficult for the letter contents. What I want to do is similar to this question (DJANGO: How to access data from ListView and DetailView on the same template?). However, the effect of pk on letter_box raised questions. Can you help me? models.py class LetterBox(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField("title", max_length=100) created_at = models.DateTimeField("create_date", auto_now_add=True) class Letter(models.Model): name = models.CharField("name", max_length=100) contents = models.TextField("cotents") created_at = models.DateTimeField("create_date", auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) letter_box = models.ForeignKey(LetterBox, on_delete=models.CASCADE) views.py class LikeLetterBoxDetail(LoginRequiredMixin,generic.ListView): template_name = "like_letter_box_detail.html" paginate_by = 2 def get_queryset(self): return Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") context['letterbox'] = get_object_or_404(LetterBox, pk=self.kwargs['pk']) return context class LikeLetterDetail(LoginRequiredMixin,generic.DetailView): model= Letter template_name = "like_letter_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']) return context -
Ajax form processing
After submitting a form to Django, it takes about 3 seconds to process I need an Ajax script that will redirect the user to an intermediate page where he will wait for a response from Django. Django got a new redirect after receiving the response I tried to solve this problem with Django, but I can't do 2 redirects in one view -
Save a model in the database with multilevel nested serializers in Django
i need help with my rest Api,with Django rest Framework and Django 4. My Api is for reading texts in foreign language, i'm trying to save a new MyTexts model in the database (Sqlite). I think the problem comes from the serializer TextSerializer. I have these models and serializers(correct them if they are wrong): #language/models.py from django.db import models # Model for a Language class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName #language/serializer.py from rest_framework import serializers from .models import Language class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' #learner/model.py from django.db import models from django.contrib.auth.models import AbstractUser from language.models import Language # Model for a Learner(a user) class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username #learner/serializer.py from django.contrib.auth import authenticate, get_user_model from rest_framework import serializers from language.models import Language from language.serializers import LanguageSerializer from .models import Learner User = get_user_model() class UserSerializer(serializers.ModelSerializer): SelLanguage=LanguageSerializer(many=False,read_only=True) def create(self, validated_data): SelLanguage = validated_data.pop('SelLanguage') user = Learner.objects.create(**validated_data) lg=Language.objects.get(Learner=user, **SelLanguage) user.SelLanguage=lg user.save() return user class Meta: model = Learner fields = '__all__' #myTags/models.py from tkinter import CASCADE from django.db import models from accounts.models import Learner from language.models import Language # Model for optional tags … -
How to integrate novnc client inside django project
I have a couple virtual machines running inside proxmox but I found out you can use the novnc client to connect to these virtual machines and use the console in a web browser. This is perfect for different clients I work with. I already have a small django project that shows the running nodes and vm's inside of them. Now I wanted to include de js library by novnc. However I can't really find a lot of information online and since my coding experience is not that high I don't really know what I am doing wrong. I used this outdated repo and tried to see if I can find out how to get it to work. https://github.com/missuor/novnc-proxy-django for now I have a view that call the api of proxmox. /api2/json/nodes/{node}/lxc/{vmid}/vncproxy to be precise. this returns a ticket, port, cert, user and upid. Now I am not sure if I just need to call the vncproxy or use these variable to open a websocket by /api2/json/nodes/{node}/lxc/{vmid}/vncwebsocket. The django view i currently have just call the vncproxy and sends the values to the rendered template. This template I used from the repo metioned above, but I just don't know why I … -
Queryset for search by username and display_name In Django Rest Framework
I'm trying to search users by their usernames and display names. I have used that for the starting match. search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name) | Q(username__istartswith=search_name) ).order_by('-created_on')[:10] I get the answer same as I want but the problem is if the display name is William Welch and I search for Welch It should return that user also, but it does not return that user. -
Calling a model's method inside a serializer and handling a received object
I'm supposed to write an API for the endpoints. It should be an application inside an existing project. I should work with its models and i'm not allowed to alter them in any way. The project consists of multiple application, and some application have their own models. There is an exempt from CategoryMetall/models.py in the CatalogNew application: class CategoryMetall(MPTTModel): position = models.ForeignKey( Menu, on_delete=models.CASCADE, verbose_name="foo", blank=True, null=True, ) subPosition = TreeForeignKey( "self", on_delete=models.CASCADE, verbose_name="bar", blank=True, null=True, ) def parent(self): if self.subPosition: return self.subPosition else: return self.position As i understood, the parent() method is supposed to return an object of either a CatalogNew model, or a Menu model. A Menu model is a model of another application from the project. Here is an exempt from it as well: Menu/models.py class Menu(models.Model): parent = models.ForeignKey( "self", on_delete=models.CASCADE, verbose_name="parent category", null=True, blank=True, ) So, i figured that in order to get a parent category i'm supposed to use the CategoryMetall.parent() method written by some other developer. The issue is, i'm also supposed to somehow serialize it. I have written a serializer in my serializers.py: class CategoryMetallSerializer(serializers.HyperlinkedModelSerializer): parentCategory = serializers.ReadOnlyField(source='parent') class Meta: model = CategoryMetall fields = ['id', 'name', 'parentCategory'] And a view for … -
Hosting Django Docker Postgres on DigitalOcean Droplets
I am new to deploying to DigitalOcean. I recently created a Droplet, into which I will put my Django API to serve my project. I saw that the droplet I rent has 25 GB of memory, and for the actual size of my project, it could be a good fit for the database. I run my entire code with Docker Compose, which handles Django and PostgreSQL. I was wondering if it is a good idea to store all the data in the PostgreSQL created by Docker Image, and stored in the local memory of the droplet, or do I need to set up an external Database in Digital Ocean? Technically I think that could work, but I don't know if it is safe to do, if I will be able to scale the droplets once the size scales, or if I will be able to migrate all the data into an external database, on digital ocean, a managed PostgreSQL all my data without too many problems. And if I save it all locally, what about redundancy? Or can I clone my database on a daily basis in some way? If someone knows about that and can help me, please I …