Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Imported images in csv file not working in webpage
I imported csv file with multiple columns, one of them is for images and it's in this format <div class="parent"><img class="img" title="" src=" {% static 'assets/images/thumb/1537.png' %} "width="64" height="64"></div> Everything works when I include the model on my index.html, but the image line becomes like a string and not an image models.py class Account(models.Model): Code = models.IntegerField(__("Code")) Crystls= models.IntegerField(__("Crystls")) Price = models.IntegerField(__("Price")) Detail = models.CharField(__("Detail"), max_length=255) Image = models.ImageField(__("Image"), max_length=255) index.html {% for account in account %} <td style="text-align:center;vertical-align:middle;">{{account.Code}}</td> <td style="text-align:center;vertical-align:middle;"><img src=" {% static 'assets/images/assets/crystls.png' %} " width="22" height="22" style="padding-bottom:3px;" />{{account.Crystls}}</td> <td style="text-align:center;vertical-align:middle;">{{account.Price}}</td> <td style="text-align:center;vertical-align:middle;"><a target="_blank" href=" {% static 'account61f3.html?id_xml=001660' %} " ><input type="button" class="btn btn-success btn-sm" value={{account.Detail}} /></a></td> </tr> <tr> <td colspan="5"> {{account.Image}} </td> {% endfor %} </tr><tr > -
How to bind two models in __init__ via related_name when calling only parent, creating an empty object
I have two models, as below, linked by the OneToOneField relationship. How can I check by related_name that there is a link to x.RelName before I use x.save (). Everything below ... models.py class Parent(models.Model): name = models.CharField(max_length=255) member = models.ForeignKey(User, related_name="MemberUsr", blank=True, null=True, default=None, on_delete=models.CASCADE) class Child(models.Model): child_name = models.CharField(max_length=255, null=True, blank=True) parent_name = models.OneToOneField(Parent, related_name='RelName', null=True, on_delete=models.CASCADE) py manage.py shell >>> from app1.models import Parent, Child >>> x = Parent() And at this point there should be an artificial connection in _ _ init _ _ >>> x.RelName Should return that it is artificially bound to Child. If I run x.save () it obviously creates linkages. But I would like to be able to check with related_name before save () that there is a binding. -
A way in Django to have one model's parameters be a dropdown selection from another model
I'm creating a recipe app, and to avoid duplication I want to store the tools without using foreign keys to avoid duplicates. Currently, each ingredient uses a recipe as a foreign key, as ingredients can come in different measurements, but I'd like to have the tools only able to be in the database once. Here are the relevant models: class Recipe(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) servings = models.IntegerField(default=1, blank=False) def __str__(self): return self.name class Instruction(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) description = models.CharField(max_length=400) def __str__(self): return f"Step #{self.id} - {self.description[:20]}" class Tool(models.Model, unique=True): name = models.CharField(max_length=50) description = models.CharField(max_length=200) def __str__(self): return self.name For ingredients, I'm using a forloop to create a table (below), but I'm unsure how to do the same for tools related to a recipe without having multiple entries in the database for tools be the same, apart from the related recipe, i.e "Frying pan" more than once. <h3>Ingredients:</h3> <table id ="ingredients"> <tr> <th>Ingredient</th> <th>Quantity</th> </tr> <tr> {% for ingredient in recipe.ingredient_set.all %} </tr> <tr> <td> {{ ingredient.name }} </td> <td>{{ ingredient.quantity}} {% if ingredient.units == "UN" %}{% else %}{{ ingredient.get_units_display.title }}{% endif %}</td> </tr> {% endfor %} </table> <h3>Tools:</h3> Table for tools goes here -
Django Property to generate a list of tuples of field and its value but return forienkey value if it is a relation
Here are the models class Category(BaseModel): title = models.CharField(max_length=128) description = models.TextField() class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return str(self.title) class Service(BaseModel): category = models.ForeignKey(Category, limit_choices_to={"is_active": True}, on_delete=models.PROTECT) title = models.CharField(max_length=128) class Meta: verbose_name = "Service" verbose_name_plural = "Services" def __str__(self): return str(self.title) def get_absolute_url(self): return reverse_lazy("services:service_detail", kwargs={"pk": self.pk}) def get_fields(self): return [ ( field.verbose_name.title(), field.value_from_object(self) if field.is_relation else field.value_from_object(self), ) for field in self._meta.fields ] the get_fields model method will return the following list [ ('Id', UUID('3bde9003-32cb-44ed-89c2-0d7b962d41a9')), ('Category', UUID('cc2ecdf8-c8e5-4cfe-998b-906d12cbccf9')), ('Title', 'Baby sitters'), ] The result can be listed on template as follows {% for name, value in object.get_fields %} {% if value %} <strong> {{name}} : {{ value }} </strong> {% endif %} {% endfor %} Now I want the model method to return a list like follows [ ('Id', UUID('3bde9003-32cb-44ed-89c2-0d7b962d41a9')), ('Category', 'Cleaning'), ('Title', 'Car Wash'), ] That is, return the value of __str__ definition of the model the forienkey referring to, if the model field is a forienkey. The purpose is to create a reusable detail page compatible for every models -
Django channel or Django signals which one should i use to allow user to get notify when some action occur
I created an app where user's can be able to post Questions and get an Answers from some user's like how we do this in stackoverflow. I don't want user to refresh page just let him know that someone answers his question i want to implement the connections functions between these user. My models class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) My views: class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user form.instance.post_id = self.kwargs['pk'] return super (My_Answer, self).form_valid(form) def viewQuestion(request, pk): question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) I want to implement Notifications Function so that when a User answer a question, the author of that Question will get notify that will redirected He/She … -
HTML5 Page: Make all divs completly visible in browser without scrolling (Django)
I would like to create one indexview which content is completely visible with any browser (mobile and desktop) without the need of scrolling. So I need any function which scale the content of the page (shrink html5 elements) so that all elements have their place on the screen. At the moment I try to go with CSS. I tried to set the max-height: 94vh (6vh are for my navbar) of my main container. But sadly that not works. the included elements of the maincontainer are overlapping... So I have to scroll Maybe this has something to the with the bootstrap cards? The result looks like this: I have the undesirable scrollbar on the right (I would like to see all six cards without scroll, so the cards must be smaller...depending on the screensize): Here my django templates: Base template <!-- Load nessessary static files--> <!-- ===============================================================================================================================================--> {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/base_style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="//cdn.jsdelivr.net/npm/round-slider@1.5.1/dist/roundslider.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <script src="https://cdn.jsdelivr.net/npm/round-slider@1.5.1/dist/roundslider.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#"> <img src="{% static 'img/greencube2.png' %}" width="30" height="30" … -
Unable to upload multiple images with Django Rest Framework
I'm trying to create a view where I can upload images at to a single model which has a foreign key to another model. The below given API works but however it only uploads 1 image. What am I doing wrong that it only takes the first image from the list and uploads in the media folder? models.py class RoofImages(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) job = models.ForeignKey(JobDetails, on_delete=models.PROTECT) image = models.ImageField(upload_to=current_user_id) image_type = models.CharField(max_length=15, choices=ROOF_VIEW_TYPES) helpers.py def modify_input_for_multiple_files(user, job, image, image_type): image_dict = {} image_dict['user'] = user image_dict['job'] = job image_dict['image'] = image image_dict['image_type'] = image_type return image_dict views.py class RoofImagesView(APIView): serializer_class = RoofImagesSerializer parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): user = Token.objects.get(key=request.auth.key).user job = request.data['job'] images = dict((request.data).lists())['image'] image_type = request.data['image_type'] flag = True arr = [] for img_name in images: modified_data = modify_input_for_multiple_files(user.user_uid, job, img_name, image_type) serializer = RoofImagesSerializer(data=modified_data) if serializer.is_valid(): serializer.save() arr.append(serializer.data) else: flag = False if flag: response_content = { 'status': True, 'message': 'Images uploaded successfully.', 'result': arr } return Response(response_content, status=status.HTTP_201_CREATED) else: response_content = { 'status': False, 'message': 'Unable to upload images.', 'result': serializer.errors } return Response(response_content, status=status.HTTP_400_BAD_REQUEST) -
password_reset_confirm is not rendering
I have used Django's built-in password reset functionality. everything is working fine but when I open the password reset link it redirects me to Django's built-in "password_reset_confime " template instead of my custom template usrl.py Code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] And I also want to implement a feature while entering an email id into the input field, I want to check if the user's entered email exists or not, if do not exist I want to show an error message "this email id is not exist" please help me to implement this feature and provide a solution for rendering my custom password_reset_confirm.html and password_reset_complete.html pages -
How to integrate an authenticated user profile data into Django Model
Hello Friendly People, I want to create an API which is able to serve the data using Django Rest framework. The objective is to create a model which can add the authenticated user profile data into custom model, so far I am able to serve the data using the views.py but it should have to be done implicitly like from the Models views.py class MessageView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request,*args, **kwargs): all_messages = Message.objects.all() message_serializer = MessageSerializers(data = all_messages, many=True) message_serializer.is_valid() current_user = request.user data = { 'user_id': current_user.id, 'messages': message_serializer.data, 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'email': current_user.email, } return Response(data , status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): message_data = request.data current_user = request.user data = { 'user_id': current_user.id, 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'email': current_user.email, } create_message = Message.objects.create(message=message_data['message'] , created_by_id=current_user.id) create_message.save() # serializer = MessageSerializers(create_message) data={ 'message': 'success', 'status': status.HTTP_201_CREATED } return Response(data ,status=status.HTTP_201_CREATED) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Message(models.Model): id = models.AutoField(primary_key=True) message = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.message Output that I am getting { "user_id": 2, "messages": [ { "id": 1, "message": "Testing message … -
MultiValueDictKeyError django, views.py error
I'm getting MultiValueDictKeyError while using the POST method with Django. this is my views.py submit function. it seems like there is an error with the candidateId field and I don't understand why. def submit_dept_member_application(request, application_id): cv = request.FILES['cv'] letter = request.FILES['letter'] candidate_id = request.data['candidateId'] rank_id = request.data['requestedRankId'] application_state = { 'candidate_id': candidate_id, 'rank_id': rank_id, 'cv_filename': cv.name, 'letter_filename': letter.name, } creator = Profile.objects.get(user=request.user.id) department = creator.department applicant = Profile.objects.get(user=candidate_id) rank = Rank.objects.get(id=rank_id) try: application = Application.objects.get(id=application_id) # TODO - update application except Application.DoesNotExist: application = None if application is None: application = Application(creator=creator, applicant=applicant, desired_rank=rank, application_state=application_state, department=department ) application.save() create_application_directory(application.id) ApplicationStep.objects.update_or_create( application=application, step_name=Step.STEP_1, defaults={'can_update': True, 'can_cancel': True, 'currentStep': True} ) copy_to_application_directory(cv, application.id) copy_to_application_directory(letter, application.id) addresee = 'devasap08@gmail.com' # TODO: change email to admin address email_headline = 'New Application Created' wanted_action = 'application_created' sendEmail(addresee, email_headline, wanted_action, creator) addresee = 'devasap08@gmail.com' # TODO: change email to creator address email_headline = 'Application Successfully Created' wanted_action = 'application_received' sendEmail(addresee, email_headline, wanted_action, applicant) return Response(application.id, status=status.HTTP_200_OK) any suggestions on how to solve it? Thank you! -
Django Rest API project architecture/design - What would a good design for my API be?
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. The API must have the following: API with employees CRUD: - GET: /employees/ (employee list) - POST: /employees/ (employee create) - UPDATE /employees/ID/ (employee update) - DELETE /employees/ID/ (employee delete) - GET /employees/ID/ (employee detail) API with reports: - GET /reports/employees/salary/ (salary report) - GET /reports/employees/age/ (age report) Endpoint to employee list: curl -H "Content-Type: application/json" localhost:8000/employees/ Endpoint to salary range report:: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/salary/ It must persist data in a database and use authentication to access. How do I structure this project in terms of apps, folders, etc? So far I've figured I'd have something like this: root ├───backend (folder) │ │ manage.py │ │ │ ├───api (app) │ ├───django_project │ ├───employees (app) │ ├───reports (app) │ └───users (app) └───client my_client.py --> will consume the api Or maybe something like this?: root ├───backend (folder) │ │ manage.py │ │ │ ├───api (app) │ ├───applications (folder) │ │ ├───employees (app) │ │ ├───reports (app) │ │ └───users (app) │ └───django_project │ settings.py │ └───client (folder) my_client.py Obs: Just ignore the missing files for now. It's not a … -
How implement Hesh Id in Djnago RESTFRAMEWORK?
I'm trying to hide the id of my objects, but I don't know how to implement it in the correct way. What I did was this: hashids = Hashids(settings.HASHIDS_SALT, min_length=32) def parse_result(result) -> Union[int, None]: if result: if isinstance(result[0], int): return result[0] try: result = int(result[0]) return result except Exception as error: print("Couldn't parse the decodification!") print(error) def h_encode(id: int): return hashids.encode(id) def h_decode(h: str) -> Union[int, None]: return parse_result(hashids.decode(h)) class HashIdField(serializers.CharField): def to_representation(self, value): value = h_encode(value) return super(HashIdField, self).to_representation(value) def to_internal_value(self, data): data = h_decode(data) return int(super(HashIdField, self).to_internal_value(data)) class ProducerSerializer(serializers.HyperlinkedModelSerializer): id = HashIdField(read_only=True) class Meta: model = Producer view_name = 'api:producer-detail' fields = ( 'id', 'name',) Although it works, I can still access the objects by their integer ID. Obs: I'm using viewset. -
Why does the Django admin prompts "a LIST of values" for a DateTimeField with a DateTimeInput widget?
I'm trying to add an ability to edit DateTime fields "start" and "end" in Django admin with a microsecond resolution. I've tried an approach from this post : class SomeAdmin(ModelAdminWithJsonFields): """...""" list_display = ('id', ... , 'start', 'end') exclude = ['created_by', ... ] readonly_fields = ('created_by', 'created_on', ...) ... formfield_overrides = { models.DateTimeField: {'widget': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f')}, } Upon opening an admin page to edit the existing model that had permissible "start" and "end" values, I see a text field with pre-filled microseconds in seemingly correct format 2022-05-13 16:41:24.000000, proving that the model field works. Though, when clicking "save", the red font prompt above these models appears, saying Enter a list of values.. The same error happens with an approach from another SO answer: class DateTime(forms.DateTimeInput): start = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S.%f'], widget=forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f') ) end = forms.DateTimeField( input_formats=['%Y-%m-%d %H:%M:%S.%f'], widget=forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f') ) class Meta: model = MachineAssignment fields = ['start', 'end'] class SomeAdmin(ModelAdminWithJsonFields): """...""" list_display = ('id', ... , 'start', 'end') exclude = ['created_by', ... ] readonly_fields = ('created_by', 'created_on', ...) ... formfield_overrides = { models.DateTimeField: {'widget': DateTime}, } -
Official celery project for django is not working
I am using the official celery project for django, but it is not working on my machine. I have installed all the necessary modules, and am using the example given in the link: Example Django project using Celery. I have already searched for the same error and used some solutions, but no solution fixed my problem. When I use the command: celery -A proj worker -l INFO, I get this response: --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2022-05-16 14:19:39 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: proj:0x230fa67a6a0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . demoapp.tasks.add . demoapp.tasks.count_widgets . demoapp.tasks.mul . demoapp.tasks.rename_widget . demoapp.tasks.xsum . proj.celery.debug_task [2022-05-16 14:19:40,464: INFO/SpawnPoolWorker-4] child process 7240 calling self.run() [2022-05-16 14:19:40,481: INFO/SpawnPoolWorker-3] child process 6960 calling self.run() [2022-05-16 14:19:40,493: INFO/SpawnPoolWorker-2] child process 10964 calling self.run() [2022-05-16 14:19:40,516: INFO/SpawnPoolWorker-1] child process 6272 calling self.run() [2022-05-16 14:19:41,978: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061]``` As I said I am using … -
What design pattern are class-based views in Django?
There are usually special attributes defined in class-based views, I call them special because they can be configured from multiple places: as_view(), setting these attributes on derived classes, setting these attributes on instances of the class-based views. Is it some kind of design pattern? If so what pattern? Also, a class-based view is instantiated on every request. It is really useful because one can encapsulate a lot of response-generating logic in mixins, and the final view class can be very neat and clean with just a bunch of inherited classes and the special attributes set. Is it als o some kind of design pattern? If so what pattern? I suspect that this is the Command pattern. -
Transfer a django project to another machine
This is a beginner question, but I haven't found the answer. I'd like to transfer my django project from virtual machine with Ubuntu 18.04 to another virtual machine with Ubuntu 18.04. This is the example directory structure pd_videowebapp/ ├── db.sqlite3 ├── env │ ├── bin │ ├── lib │ └── pyvenv.cfg ├── manage.py ├── media │ ├── images │ └── video ├── mysite │ ├── core │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── templates │ ├── urls.py │ └── wsgi.py ├── Pipfile ├── requirements.txt └── static ├── admin ├── style2.css └── style3.css In env directory there is a Python virtual environment. Before I transfer it I would run $ pip freeze > requirements.txt Then I would zip all the directory structure except for db.sqlite3 and media directory. Then unzip it on another VM. Then copy the db.sqlite3 and media directory to the right place. Then create a virtual environment on another VM. Then run $ pip install -r requirements.txt Or should I rather copy the whole project with env directory in the beginning? What is better? Did I omit something? Or is there a better approach? -
Creating Trigger using javascript and django
I want to make a trigger using javascript. This is my trigger in js : setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'update_state' %}", success: function(response){ console.log('Updated'); }, error: function(response){ console.log('An error occured') } }); },60000); And this is my view : def update_state(request): requests = Request.objects.all() for req in requests: d = Request.objects.filter(id=req.id) dd = d.get() if dd.delay == timedelta(minutes=0): pass else: d_del = dd.delay - timedelta(minutes=1) d.update(delay=d_del) return HttpResponse('ok') In my db sometimes the delay decrease but some time don't decrease. I don't know where is the problem. -
DJANGO_API_SECRET_KEY is missing
I am trying to launch github project in docker, but when I'm using command python manage.py migrate I get an error DJANGO_API_SECRET_KEY is missing. It is said that I need to copy .env.example file into .env.development file but there is no such file. The error I'm getting is from my settings.py file: val = os.environ.get(name) assert val, f"{name} is missing" return val # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = required_env("DJANGO_API_SECRET_KEY") I am trying to run this project on my Windows system. -
Update django list page total items based on query done
Django admin calculates total number of items before it query for items. Due to realtime changes, count is less than the actual number of items. Is it possible to update total count after query is completed -
Large media uploads to azure blob service for authenticated users
I am new to azure and attempting to create a REST API that uploads large media files (4gb) to azure blob service. I'm using Django to create the API. The API should only allow authenticated users to upload files. I would like the upload to be handled by the front end because I am running my Django instance in a container on Azure and would like to reduce memory / compute load on it to reduce cost. I was wondering if I could dynamically generate a time-sensitive token that is sent to the front end to allow users to upload directly to my Azure blob instance. Any suggestions on how I can achieve this in a production-safe manner? Thanks! -
Converting data with a function before it's added to the database with Django and Python
File structure of the project: - Site - common - __init__.py - utils.py - App Inside utils.py, we have a function that converts any unit of measurement input by the user in a form to a unified unit - i.e lbs -> kg, ounces -> kg. How do we pass the data a user inputs from the |form -> through the function -> to the database| in a way that it is converted before being added to the database? For example: User enters 1000 grams as the weight of a product and submits the data. The function changes 1000 grams into kilograms. The weight is entered into the database as 1 kilogram. The function is already written, we are just unsure how to "plug" this into our code to achieve functionality. -
Django Export Excel Save File In Server (Celery + RabbitMQ)
I have a Django view that exports an Excel File and prompts a Download Dialog when the file is ready. I am installing Celery and RabbitMQ to make this task a background task. This means that the excel file will not be prompted to be downloaded, but I would like to save it somewhere in the machine, so the user can later go to a page and download it. Example: Go to List page -> Click on Export -> Get a message: "Your file will be ready soon" -> User goes to "Downloads" Page -> Finds the file in a list -> Clicks to download. So the process for me now is to create a new model: class Export(models.Model): dossier = models.ForeignKey( Dossier, related_name="Export", on_delete=models.CASCADE, default=None, editable=False, ) timestamp = models.DateTimeField(auto_now_add=True, editable=False) file = models.FileField( upload_to=get_rapport_filename, verbose_name="Fichiers Excel" ) def __str__(self): return "%s - %s" % (self.dossier, self.timestamp) class Meta: verbose_name = "Excel Report" verbose_name_plural = "Excel Reports" And this is the code I have that generates the Excel file: @shared_task def export_dossiers_factures(request): dossier_queryset = Dossier.objects.filter(status_admin="Facturé") today = str(date.today()) response = HttpResponse( content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = ( "attachment; filename=" + today + "-dossiers_factures.xlsx" ) workbook = Workbook() # Get active … -
My edit profile page is not displayed due to migrations
I have a doubt. It happens that I am making a page called "Edit Profile", to that page I added more fields than those that are pre-established for the edit profile. Everything was fine, I got this error: ValueError: The field Users.Profile.user was declared with a lazy reference to 'Usuarios.customuser', but app 'Usuarios' doesn't provide model 'customuser'. The field admin.LogEntry.user was declared with a lazy reference to 'Usuarios.customuser', but app 'Usuarios' doesn't provide model 'customuser' following various stack recommendations, just delete several files from my app folder and that's it, I was able to do my migrations but now the following error appears when I reload the page: django.db.utils.ProgrammingError: relation "Usuarios_customuser" does not exist LINE 1: ...omuser"."state", "Usuarios_customuser"."zip" FROM "Usuarios_... As if it had not been able to do the migrations or did not detect them. But that error seems strange to me because when placing makemigrations and migrate, no error appears, only when I reload the page html <span class="d-none d-xl-inline-block ms-1 fw-medium font-size-15">{{user.username}}</span> <i class="uil-angle-down d-none d-xl-inline-block font-size-15"></i> </button> <div class="dropdown-menu dropdown-menu-end"> <!-- item--> {% if user.is_authenticated %} <a class="dropdown-item" href="{% url 'profile' %}"><i class="uil uil-sign-out-alt font-size-18 align-middle me-1 text-muted"></i> <span class="align-middle">View Profile</span></a> <a class="dropdown-item" href="{% url 'logout' … -
How to replace special text with other special text - Python
How do I change my special string to a different value if value appears? My variables special_url = http://127.0.0.1:8000/ text = '...' special_symbol = {{URL}} Well i have text like this: It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- {{URL}} Or-less normal distribution of letters, as opposed to using 'Content here, content here', I need change above text to this when the value {{URL}} is in text It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more- http://127.0.0.1:8000/ Or-less normal distribution of letters, as opposed to using 'Content here, content here', I try this, bot now work: massage = re.sub('{{URL}}', obj.special_url, text) -
"This field is required." Django rest framework
I've looked every answer in stack I cant find an answer. I 've created an API with django rest framework with some measurements . Im trying to post a TreeSensor measurement through postman or django API .Weather measurements works just fine but on my TreeSensor i get the following error even though they are identical besides the fields. { "soil_moisture_depth_1": [ "This field is required." ], "soil_moisture_depth_2": [ "This field is required." ] } Serializers : class TreeSensorMeasurementSerializer(serializers.ModelSerializer): class Meta: model = TreeSensorMeasurement fields = ["sensor", "datetime", "soil_moisture_depth_1","soil_moisture_depth_2","soil_moisture_depth_1_filtered","soil_moisture_depth_2_filtered", "soil_temperature"] class WeatherStationMeasurementSerializer(serializers.ModelSerializer): class Meta: model = WeatherStationMeasurement fields = ["sensor", "datetime", "wind_speed", "current_rain", "wind_direction", "solar_radiation", "air_temperature", "air_humidity", "air_pressure", "luminosity", "battery", "dew_point"] API : ########### TreeSensorMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'soi_moisture_depth_1' : request.data.get('soil_moisture_depth_1'), 'soi_moisture_depth_2' : request.data.get('soil_moisture_depth_2'), 'soi_moisture_depth_1_filtered' : request.data.get('soil_moisture_depth_1_filtered'), 'soi_moisture_depth_2_filtered' : request.data.get('soil_moisture_depth_2_filtered'), 'soil_temperature' : request.data.get('soil_temperature'), } serializer = TreeSensorMeasurementSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ########### WeatherStationMeasurement Api ########### def post(self,request, *args, **kwargs): data = { 'sensor' : request.data.get('sensor'), 'datetime' : request.data.get('datetime'), 'wind_speed' : request.data.get('wind_speed'), 'current_rain' : request.data.get('current_rain'), 'wind_direction' : request.data.get('wind_direction'), 'solar_radiation' : request.data.get('solar_radiation'), 'air_temperature' : request.data.get('air_temperature'), 'air_humidity' : request.data.get('air_humidity'), 'air_pressure' : request.data.get('air_pressure'), 'luminosity' : request.data.get('luminosity'), …