Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to open postgres db and see the tables (Django+Postgres+Docker)
I start learning docker with Django+PostgreSQL, I did all steps from there https://docs.docker.com/samples/django/ How can I open created database on terminal or pgAdmin to see tables and change them? I use: Ubuntu 22.04 / Docker Engine 20.10.17 / Docker Compose version v2.6.1 / psycopg2-binary==2.9.3 / Django==4.0.6 / psql (13.7 (Ubuntu 13.7-1.pgdg22.04+1)) my 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" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } some info if needed, postgres file created are owned by root: postgres file 1/2 postgres file 2/2 Thanks for answers! -
Django convert image to webp
I have service in my Django project's app, that upload images, and I need to convert all images to webp to optimize further work with these files on the frontend side. Draft of _convert_to_webp method: # imports from pathlib import Path from django.core.files import temp as tempfile from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image # some service class ... def _convert_to_webp(self, f_object: InMemoryUploadedFile): new_file_name = str(Path(f_object._name).with_suffix('.webp')) temp_file = tempfile.NamedTemporaryFile(suffix='.temp.webp') # FIXME: on other OS may cause FileNotFoundError with open(temp_file 'wb') as f: for line in f_object.file.readlines(): ... # will it works good? new_file = ... new_f_object = InMemoryUploadedFile( new_file, f_object.field_name, new_file_name, f_object.content_type, f_object.size, f_object.charset, f_object.content_type_extra ) return new_file_name, new_f_object ... f_object is InMemoryUploadedFile instance from POST request body (Django automatically create it). My idea is to create a temporary file, write data from f_object.file.readlines() to it, open this file with PIL.Image.open and save with format="webp". Is this idea a good one or there is another way to make file converting? -
ModuleNotFoundError: No module named 'winreg' on Mac? (But winreg is a windows thing)
I am receiving the following error when I try to run a django shell. I am on a Mac though and everything that I can find says that this is associated with Windows and that winreg should be installed by default. Suggestions as to what I should be looking at? Traceback (most recent call last): File "/Users/j/code/myproject/core/manage.py", line 22, in <module> main() File "/Users/j/code/myproject/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/shell.py", line 127, in handle exec(sys.stdin.read(), globals()) File "<string>", line 5, in <module> ModuleNotFoundError: No module named 'winreg' -
Why can't I use "profile" as an app name?
I need a profile to extend the Django User object, so I thought to create an app to contain the profile object and related views then proceed as per the Django doc, but I get ./manage.py startapp profile CommandError: 'profile' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I don't have an app called profile in INSTALLED_APPS and I don't know what context this message should be interpreted in. Can anybody help? (Yes, I could call it userprofile or xxx_profile instead, but I'd like to understand why I need to) -
Unable to view database object in django in html
The object in the database is not visible in the html. Model class OutFormatTemplate(models.Model): title = models.CharField(max_length=80) template = models.FileField(upload_to='out_put_temp/') def __str__(self): return f"{self.title}" View def upload_form(request): out_form = OutFormatTemplate.objects.all() for i in out_form: print(i.id, i.title) form = UploadBookForm() context = { 'form': form, 'outform': out_form } return render(request, 'file_uploader.html', context) HTML {% if outfrom %} <p>Out Form Exist</p> {% else %} <p>Not Exist</p> {% endif %} <div class="mt-2" id="out-template"> <label for="template-out" class="form-label">Select Output Template</label> <select class="form-select" aria-label="Default out select example" name="out_template_id" id="template-out"> <option value="0" selected></option> {% for out in outfrom %} <option value="{{ out.id }}">{{ out.title }}</option> {% endfor %} </select> </div> The database value Table values But in the webpage these values are not shown Form Iam new to django, I need help. Have i done anything wrong here. -
python decimal place changes after 0
hello, i am new one in programming i am sending a request from postman with payload {"member_id":10,"value": 30.00} but when i receiving it in api by using request.data {'member_id': 10, 'value': 30.0} the decimal place changes to 1 position after zero but i need same decimal values as sending in request which i need to verify signature. thanks -
How to update foreign key value django
Let say I have following models: models.py First of all I have to do a subtraction between quantity_in_store (from stockList models) and shipping_qty(from stockout models) and to get the final quantity that left in store. However, I have get the final quantity but I would like to update the value of final quantity into the quantity_in_store(from stockList models) How would I go about doing this? Thanks admin.py -
how can you display data from three related tables in django?
I'm new to django and I'm having trouble displaying related data from three related databases in a table. I hope you can help me. Models.py class recursos (models.Model): gruporecurso= models.CharField (max_length=50, choices=TIPORECURSO, default=TIPODEFAULT) descripcion = models.CharField(max_length=100) estado_disponible =models.BooleanField(default= True) inventario = models.CharField(max_length=40,blank= True, null=True) observacion = models.TextField(blank= True, null=True) def __str__(self): return self.descripcion class remito (models.Model): fecha = models.DateField() hora = models.TimeField() responsable = models. ForeignKey(personas, null=True, blank= True, verbose_name='Responsable',on_delete=models.CASCADE) area_pedido = models.CharField(max_length=20, verbose_name='Área del pedido') operador = models.CharField(max_length=40, choices=OPERADOR,verbose_name='Entregado por') lugardeuso = models.CharField(max_length=40,verbose_name='Lugar uso') observacion = models.TextField(blank= True, null=True) class detalle_remito (models.Model): id_remito = models.ForeignKey(remito, null=True, blank=False, on_delete=models.CASCADE) id_recurso = models.ForeignKey(recursos, null=True, blank=False, on_delete=models.CASCADE) cantidad = models.IntegerField(default=1) def __str__(self): return f' {self.id_recurso.descripcion}' Views.py def home (request): remitos= remito.objects.all() recursolist= detalle_remito.objects.all() page= request.GET.get('page',1) try: paginator = Paginator(remitos,5) remitos=paginator.page(page) except: raise Http404 return render(request,"RemitoTicapp/home.html",{'entity': remitos ,'recursolist':recursolist,'paginator': paginator}) home.html {% extends "RemitoTicapp/base.html" %} {% load static %} {% block content %} <!-- Heading <section class="page-section clearfix"> <div class="container"> </div> </div> </section> --> <!-- Message --> <section class="page-section cta"> <div class="container mx-auto"> <div class="row"> <!--<div class="col-xl-9 mx-auto"> --> <div class="cta-inner text-center rounded"> <h2 class="section-heading mb-2"> <span class="section-heading-upper">Sistema de Gestión de pedidos</span> <span class="section-heading-lower"> Elementos cedidos</span> </h2> <!--<p class="mb-0"> --> <table class="table table-striped" bg … -
What is the best way to orchestrate AWS Step Functions, AWS Lambda, and a Django Backend hosted on EC2?
Our team is currently investigating data pipeline construction with AWS Step Functions for a Django backend project which is on EC2. I see that almost any documentation with Step Functions relies on Lambda Function invocation for performing pipeline tasks. These raise a few questions. Can you use regular python functions or run modules as part of Step Functions? If we try to use AWS Lambda for this functionality, it requires having a .zip copy of our source deployed on Lambda. Doesn't this result in both duplicate code and code maintainability issues? Isn't using another tool like Apache Airflow seem to be a better solution, as calling python scripts seem to be a natural part of the workflow? Finally, does using AWS lambda make much more sense when the function code only relies on the built-in libraries and is not heavily dependent on external libraries / project-specific imports, which as mentioned again may result in code duplication? We currently have no intention of deploying our backend on Lambda. If I am missing something please clarify. Thanks in advance. -
How can I see Django created reverse relation items, in vscode, or in mysql-workbench
I want to use Django auto created items in workbench but they are not there, is it possible to access them in mysql-workbench, and how can I see them in vscode. -
Local field 'email' in class 'Colaborador' clashes with field of the same name from base class 'User', but there is no email field in class
I am a beginner at python and django, I'm using for the first time to collaborate in a college's project and I just run into an error a little odd Whenever I try to make the migrations of my files, it keeps warning me "Local field 'email' in class 'Colaborador' clashes with field of the same name from base class 'User'" The weird thing is that, there is no local field at Colaborador class my class at models.py class Colaborador(User): nome = models.CharField(max_length=100) ddd = models.CharField(max_length=2, verbose_name='DDD') telefone = models.CharField(max_length=9) administrador_sistema = models.BooleanField(default=False) class Meta: ordering = ['nome'] def get_absolute_url(self): return reverse('colaborador-detail', args=[str(self.id)]) def __str__(self): return self.nome What could it be? Does someone has some idea? -
How to see objects of manytomany field by related_name in admin page?
I have these two models: class User(AbstractUser): is_teacher = models.BooleanField(default=False, null=False) class Course(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacher_courses') students = models.ManyToManyField(User, blank=True, related_name='student_courses') Course model has a ManyToMany field and a ForeignKey to User model. In django's admin page, you are able to see a course's student/teacher. Is there a way to make it as you can have a user's courses in admin page? -
DRF get_serializer_class doesn't pass
Here I have a viewset: class TenderViewSet(viewsets.ModelViewSet): """ API ViewSet for Propopsition """ queryset = models.Tender.objects.all() serializer_class = serializers.TenderGetSerializer def get_serializer_class(self): print('get_serializer_class passed') if self.action == 'map': self.serializer_class = serializers.TenderMapSerializer print('if passed') return super().get_serializer_class() @action(detail=True, methods=['get']) def map(self, request): print('action map passed') print(self.serializer_class) tenders = self.serializer_class.setup_eager_loading(models.Tender.objects.all()) serializer = serializers.TenderGetSerializer(tenders, many=True) return Response(serializer.data, status.HTTP_200_OK) I'm getting data with TenderGetSerializer instead of TenderMapSerializer and get_serializer_class method doesn't pass. Output is: action map passed <class 'tender.serializers.TenderGetSerializer'> HTTP GET /api/tenders/map/ 200 [0.19, 127.0.0.1:55247] Difference of serializers: TenderGetSerializer returns all fields (about 20) and TenderMapSerializer returns 5 fields. Hope for you help. Have a nice day! -
Django Extend User Admin Site with a ManyToMany field
So, I'm not being able to add this countries field into the User Admin Site trying not to go with the CustomUser model option. # models.py: class Country(models.Model): name = models.CharField(max_length=50) users = models.ManyToManyField(User, related_name='countries') My idea was to add a widget under the permissions section in the user admin site. To do that, I'm trying to extend the "fieldset" or "inline" parameter of UserAdmin in the admin.py file but I'm not getting any result from it. # admin.py class CountriesInline(admin.StackedInline): model = Tenant filter_horizontal = ('countries',) class CustomUserAdmin(UserAdmin): def __init__(self, *args, **kwargs): super(UserAdmin,self).__init__(*args, **kwargs) # admin_visible_fields = UserAdmin.fieldsets[2][1]['fields'] + ('countries',) # UserAdmin.fieldsets[2][1]['fields'] = admin_visible_fields # inlines = [CountriesInline] UserAdmin.filter_horizontal = list(UserAdmin.filter_horizontal) + ['countries'] Any idea how to extend this admin template? -
generateDS issue when using gends_generate_django.py
I would like to use the python script gends_generate_django.py from the generateDS toolbox to generate Django models from an initial XSD file. According to the documentation (point 16.1) I would like to go through the following three steps: Generate bindings -- Run generateDS.py. ExtractsimpleType definitions from schema -- Run gends_extract_simple_types.py. Generate models.py and forms.py -- Run gends_generate_django.py. Steps 1+2 could be completed successfully. In step 3 the following error message appears: Traceback (most recent call last): File "/generateds_code_2_40_12/gends_generate_django.py", line 208, in main() File "/generateds_code_2_40_12/gends_generate_django.py", line 202, in main generate_model(options, module_name) File "/generateds_code_2_40_12/gends_generate_django.py", line 96, in generate_model supermod = importlib.import_module(module_name) File "C:\ProgramData\Miniforge3\envs\gends_ws\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named '/generateds_definedsimpletypes' Where generateds_definedsimpletypes.py is the output from running gends_extract_simple_types.py. I have tried running the script both in the Conda environment and underself-installed Python. Moreover, I have used generateDS version 2.40.12. and Python 3.9.13. What is my mistake when executing the script? Many thanks for your … -
Django and React return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Getting decoding error when trying to send an image request from React to Django, I think Django fail to interpret the request, thus the error showing up : class ImageModel(models.Model): image = models.ImageField(upload_to='media') views.py class ImgView(viewsets.ModelViewSet) data = serializer.ImgSerializer(data=request.data) if data.is_valid(): img = request.FILES['img'] imgmodel = ImageModel.objects.create(image=img) return Response("Success") return Response("fail") serializer.py class ImgSerializer(serializers.Serializer): class Meta: fields = '__all__' model = models.ImageModel in frontend side: function ComponentImage(){ let [img,setImg] = useState('') let handleChange = (key,content)=>{ setImg({ ...img, [key]:content } ) } let submitChange = (e)=>{ e.preventDefault() let formData = new FormData() formData.append('img',img) axios.post('http://127.0.0.1:8000/',formData) } return( <div> <form method='submit' onSubmit = (e)=>submitChange(e) encType='multipart/form-data'> <div class='divlbl'><label for="upload" className='imglbl'>Upload An Image</label></div> <input id='upload' required type='file' name='img' accept="image/*" onChange ={(e)=>handleChange(e.target.name,e.target.files[0])}></input> <div> </form> </div> ) } -
Django Dropdown not coming
I am trying to get a django dropdown in shopping CRUD project with models Categories and Subcategories connected via foreign keys and I am using serializers,the problem is that in the EDIT page the dropdown are empty despite the fact that I am calling them by thier values in html below are the models class Categories(models.Model): category_name = models.CharField(max_length=10) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) edit function def edit_sub_categories(request,id): if request.method == 'GET': editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) hm = {"SUBCategories":s.data} return render(request,'polls/edit_sub_categories.html',hm) editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: return redirect("sub_categories:show_sub_categories") html page of edit_sub_categories <form method="POST" > {% csrf_token %} <table> <!--content-table--> <thead> <tr> <td>Sub Categories ID</td> <td><input type="text" name="id" value="{{SUBCategories.id}}" readonly></td> </tr> <tr> <td>Categories Name</td> <td> <!-- <input type="text" name="category_name" value="{{SUBCategories.category_name}}"> --> <select name="category_name" id=""> {% for c in SUBCategories %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" value="{{SUBCategories.sub_categories_name}}"></td> </tr> <tr> <td>Sub Categories Description</td> <td><input type="text" name="sub_categories_description" value="{{SUBCategories.sub_categories_description}}"></td> </tr> <tr> <td> <!-- <input type="submit" value="update record"> --> … -
Not allow same email to register multiple times
I would like my newsletter signup to only allow diffrent emails to signup and not allow the same email to sign up multiple times with a message email is allready in use. I cant seem to figure it out any help would be appreciated. The code is below i added the code i thought was usefull if u need more to figure it out i can post it, its a small app in a bigger project just for the email newsletter signup. newsletter template {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} <div id="delivery-banner" class="row text-center"> <div class="col bg-success text-white"> <h4 class="logo-font my-1">Sign up to Newsletter and get 5% discount</h4> </div> <div class="content-wrapper text-center bg-warning container-fluid" id="newsletter-wrapper"> <form v-on:submit.prevent="onSubmit"> <div class="card text-black bg-warning mb-3"> <div class="card-footer"> <div class="alert alert-success" role="alert" v-if="showSuccess"> You are Subscribed to our Newsletter! </div> <h2>Subscribe to our newsletter</h2> <div class="form-group"> <input type="email" class="" v-model="email" name="email" class="input" placeholder="e-mail address" required> </div> <div class="form-group"> <button class="btn btn-success ">Submit</button> </div> </div> <div class="social"> <a target="_blank" rel="noopener noreferrer" href="https://facebook.com/" class="btn btn-social-icon btn btn-primary btn-outline-facebook "><i class="fa fa-facebook"></i></a> <a target="_blank" rel="noopener noreferrer" href="https://youtube.com/" class="btn btn-social-icon btn btn-danger btn-outline-youtube"><i class="fa … -
i want to get data from async function butt it returns me a promise
first function used to get data form django server and return to second fucnction butt it return promise async function gname(sender){ const u={ user:sender, }; const s=await Axios.post("http://127.0.0.1:8000/api/getname",u).then((res)=>{return res.data}); return s; } second function function getName(sender){ const nme=gname(sender); return nme; } now the second function should return data but it returns promise i want to show this name inside a div butt it shows up an error! -
Django sequentially link tables through ForeignKey
I have a User Following Django Models system based on one posted here. How can I get all Post objects of that a user follows, having two models: Post and UserFollowings pointing at User model via ForeignKey but User model not pointing back? I need QuerySet of Posts objects to later call serializer that I have added Posts model Models: class User(AbstractUser): pass class Post(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name='posts') body = models.TextField() def serialize(self): return { "id": self.id, "author": self.user.first_name +" " + self.user.last_name } class UserFollowing(models.Model): user_id = models.ForeignKey("User", on_delete=models.CASCADE, related_name ='following', null=True) following_user_id = models.ForeignKey("User", on_delete=models.CASCADE, related_name='followers', null=True) I have tried using select_related but I think it cannot work with those models. Basically, I am looking for something like this: u = User.object.get(id=num) followers = u.followers followers_posts = followers.posts.all() Last line returns: 'RelatedManager' object has no attribute 'posts' -
django AWS S3 download optimisation
I work on some django + DRF project, that has application for media files upload to and download from AWS S3 (application is something like proxy, using to not access frontend to download images directly from AWS S3). I noticed, that my download requests work not so fast (500ms +/- 100ms), and in production it probably will be a problem, so my question is following: "Is there a way to make these requests faster or separate download logic to some async microservice or multiprocess task? What is the best practice?" Service, that download images for me in current project state (for context): # media_app/services/download/image.py class ImageDownloadService(FileDownloadServiceBase): model = Image # media_app/services/download/base.py class FileDownloadServiceBase: model = ... def __init__(self, instance: str) -> None: self.instance = instance def _get_file(self, presigned_url): response = requests.get(url=presigned_url, stream=True) return response def download(self) -> Tuple[file_data, status_code]: s3 = boto3.resource( service_name='s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name=settings.AWS_S3_REGION_NAME, ) url = s3.meta.client.generate_presigned_url( ClientMethod="get_object", ExpiresIn=3600, Params={ "Bucket": settings.AWS_STORAGE_BUCKET_NAME, "Key": f'media/public/{self.instance.file_name}', }, ) response = self._get_file(url) return response.content, response.status_code -
Is it possible to enforce a manager filter based on a variable in django?
We would like to enforce a specific filter in a django application as a way to prevent accidental data leaking (and to require developers to be explicit about intention). Lets say we have a Project model and a Book model, and we want to prevent Book.objects.all() without filtering on a project. I would like something like this: Book.objects.for_project(project) -> Should return a QuerySet with all books for a specific project Book.objects.all_projects() -> Should return a QuerySet with all books, i.e. for usage in data migration commands Book.objects.all_projects().filter() -> Should be chainable Book.objects.all() -> Should throw a DataLeakError() Book.objects.filter() -> Should throw a DataLeakError() Book.objects.exclude() -> Should throw a DataLeakError() Book.objects.only() -> Should throw a DataLeakError() ....etc Is there a standard pattern for something like this, or is this an anti-pattern? -
how to track user in real time ? User online/offline Django
here is my codes. https://github.com/niyaziozydn/userchannels how can i use 'ASYNC' in this project. Can someone help me ? Codes are working but i want to track in real time. -
How to use select_related in save method of a admin model
I would like to get the specific information from different model therefore I have use the method of select_related to fetch the data but I unable to save the record into db. How to use select_related in save method? Let say I have following models models.py Now I would like to get the product_quantity from stocklist and do a subtraction between product_quantity and shipping_qty(from stockOut models) to get the final quantity that remain. admin.py But when I get the value with using the method of select_related but I unable to save it into db. How would I go about doing this? Thanks. -
Why django not work with sentence transformer
Why django not execute this part of python code .. any one coutd tell me if sentence transformer work with django modelPath = "D:/pythonProject/pars" model = SentenceTransformer('cross-encoder/mmarco-mMiniLMv2-L12-H384-v1') model.save(modelPath) model = SentenceTransformer(modelPath) print("done")``` > Why django not execute this part of python code .. any one coutd tell me if sentence transformer work with django