Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: FileField' object has no attribute 'attrs' in class Meta
I have a simple problem. Inside a modelForm, in my Meta class, inside widgets={} i have specified: 'video' : forms.FileField(allow_empty_file=True) however django complains that 'FileField' object has no attribute 'attrs'. What could be the issue -
Form and inline-form at the same time in Django UpdateView
I have the following models: class Product(models.Model): name = models.CharField(max_length=100) class ProductList(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User) products = models.ManyToManyField(Product, through='ProductAssignment') class ProductAssignment(models.Model): count = models.PositiveIntegerField() product_list = models.ForeignKey(ProductList, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) I have created an admin page for it with class ProductAssignmentInlineAdmin(admin.TabularInline): model = ProductAssignment fields = ('count', 'product') extra = 2 class ProductListAdmin(admin.ModelAdmin): model = ProductList inlines = (ProductAssignmentInlineAdmin,) admin.site.register(ProductList, ProductListAdmin) Now I want to allow the user to edit the ProductList the same way. Therefore, I have created an UpdateView class ProductListUpdate(LoginRequiredMixin, UpdateView): model = ProductList fields = '__all__' but it only shows the fields for the ProductList and not the m2m values. I have replaced fields with form_class: ProductAssignmentForm = inlineformset_factory(ProductList, ProductAssignment, fields=('count', 'product'), extra=2) class ProductListUpdate(LoginRequiredMixin, UpdateView): model = ProductList form_class = ProductAssignmentForm and this only shows the m2m section of the form. How can I show both (the ProductList properties AND the m2m inline properties from the ProductAssignment model)? -
Starting Django's runserver in a Docker container through docker-compose
I would like to have Django's runserver command running when I call docker-compose up Here is what I tried, firstly, my image is starting from a Python image customized following this dockerfile: # Dockerfile FROM python:3.8 MAINTAINER geoffroy # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Ports exposure EXPOSE 8000 VOLUME /data # Install dependancies RUN apt-get update && apt-get install -y \ vim \ git \ && rm -rf /var/lib/apt/lists/* # Setup python dependancies RUN git clone https://github.com/blondelg/auto.git WORKDIR /auto RUN cd /auto RUN pip install --no-cache-dir -r requirements.txt # Build the secret key generator RUN echo "import random" > generate_key.py RUN echo "print(''.join(random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@$^&*(-_=+)') for i in range(50)))" >> generate_key.py # Setup environment configuration RUN cp auto/config_sample.ini auto/config.ini RUN sed -i "s/SECRET_KEY_PATTERN/$(python generate_key.py)/gI" auto/config.ini RUN sed -i "s/django.db.backends.sqlite3/django.db.backends.mysql/gI" auto/config.ini RUN sed -i 's|{BASE_DIR}/db.sqlite3|autodb|gI' auto/config.ini RUN sed -i "s/USER_PATTERN/root/gI" auto/config.ini RUN sed -i "s/PASSWORD_PATTERN/root/gI" auto/config.ini RUN sed -i "s/HOST_PATTERN/database/gI" auto/config.ini RUN sed -i "s/PORT_PATTERN/3306/gI" auto/config.ini Then, I have my docker-compose.yml designed as follow: # docker-compose.yml version: "3" services: database: image: mariadb container_name: database ports: - "3306:3306" environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=autodb hostname: 'database' runserver: build: . command: python /auto/manage.py runserver 0.0.0.0:8000 container_name: runserver ports: - "8000:8000" depends_on: … -
django: adding a form to formset in template causing issues
I know this kind of question are recurrent here and I have searched around for hours for an answer but nothing this seems to solve the issue. I have a formset where the user can dynamically add a form. The formset works well when there is only form, but when the user adds a form, this newly added form does not get saved in the database table which lead me to think that there is an issue with the adding button. My limited skills in programming and especially Javascript prevent me from going further in understanding what is going on here is my view: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) elif request.method == 'POST': formset = form(request.POST) if formset.is_valid(): for check_form in formset: quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) check_form.save() return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is the template: <form method="POST" class="form-validate" id="form_set"> {% csrf_token %} {{ formset.management_form }} <table id="form_set" class="form"> {% for form in formset.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> … -
Restrict updating fields if object is deactivated DRF
I have a model: class Trade(models.Model): name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField('Active', default=True) is_deleted = models.BooleanField('Deleted', default=False) And my view: class TradeViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() serializer_class = TradeSerializer permission_classes = [permissions.IsAuthenticated] def perform_destroy(self, instance): instance.is_deleted = True instance.save() serializer.py class TradeSerializer(serializers.ModelSerializer): class Meta: model = models.Trade fields = ( 'id', 'name', 'is_active', ) read_only_fields = ('id', 'is_deleted') And my question: how I can disable update and partial update all fields except is_deleted field if the value of is_deleted field of my object marked as True? I tried to override get_extra_kwargs, but it doesn't work Appreciate -
Can a file be converted with API before submitting the form?
I want to convert a PDF file using convertapi but I'm not sure if that can be done before the user clicks Submit on the django form i.e. before the file is saved through the form in Django. -
Use an app's model's object fields as form ChoiceField in another app
I have two apps,menu and table This is a model in app menu class Item(models.Model): name = models.CharField(verbose_name="Item Name", max_length=200, db_index=True) And in app table, I have a form.py as following: from django import forms class TableForm(forms.Form): item = forms.ChoiceField(choices= xxx) I would like to use the list of all object names in the model Item as a choicelist in the form. The objects of Item could be created both by admin and elsewhere in my project during runtime and updated in the database. Could someone advise? Thanks. -
How to customize the serializer data of an onetomany relationship in django
I define the serializer for the image model and call it up to the postserializer to give data at once when the postserializer is called. There is no problem with the operation, but I don't give json data as I want. Now I give it to you like this is it. { "pk": 0, "author": { "id": 0, "email": "", "username": "", "profile": "url", "following": 0, "followers": 0 }, "title": "", "text": "", "view": 0, "images": [ { "image": "url" }, { "image": "url" }, { "image": "url" }, { "image": "url" } ], "like_count": 0, "comment_count": 0, "liker": [ 0, 0 ], "tag": null, "created_at": "2020-10-06T21:46:48.039354+09:00" }, I want this. { "pk": 0, "author": { "id": 0, "email": "", "username": "", "profile": "url", "following": 0, "followers": 0 }, "title": "", "text": "", "view": 0, "images": [ url, url, url, url ], "like_count": 0, "comment_count": 0, "liker": [ 0, 0 ], "tag": null, "created_at": "2020-10-06T21:46:48.039354+09:00" }, How will json come out the way I want? Here is my code. serializers.py class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image', ) class CommentSerializer (serializers.ModelSerializer) : comments_author = userProfileSerializer(read_only=True) class Meta : model = Comment … -
Setting up tests to test API endpoint in DjangoRest
I am struggling setting up tests for a DjangoRest API endpoint. This is the model: class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) maps = models.ForeignKey(Restaurant, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My test: class CreateReviewTest(APITestCase): def setUp(self): self.user = User.objects.create_user(username="TotoBriac", password="verystrongpsw") self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIZATION="Token " + self.token.key) def test_create_review(self): self.data = {"maps": "ChIJd230zfzz5UcRz8XVIZjiVzY", "review_author": "TotoBriac"} response = self.client.post("/api/restaurant_review/", data = self.data ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) But my test fails and I get this error: AssertionError: 400 != 201 Since it's a 400, can it be also a 404 or a 403? I have another test testing user creation and it's working fine. So I don't think is db access related. Because I run my test this way python3 manage.py test --keepdb (I am testing a PostgrSql db deployed on heroku therefore I had to create another db just for testing), I can't use the verbose -vv and can't figure out was is the issue with my test. -
Triyng to slugify url from title posts in a Django blog
I have a blog in Django and realised that I would like to have the url of the articles in slug with the title's name. I don't really know how to proceed. Another problem is that I already have several posts done with article/int:pk. Tried to make a url camp in the database and a function in order to transform the title and slugify it, but I don't really know how to get it done or how to continue. Thank you for your time in advance. models.py: from django.utils.text import slugify class Post(models.Model): title=models.CharField(max_length=100) header_image = models.ImageField(null=True , blank=True, upload_to="images/") title_tag=models.CharField(max_length=100) author= models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) #body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=50, default='uncategorized') snippet = models.CharField(max_length=200) url = models.SlugField(default='', editable=False, max_length=255, null = False) likes = models.ManyToManyField(User, blank=True, related_name='blog_posts') def total_likes(self): return self.likes.count() class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['-post_date'] def __str__(self): return self.title + ' | ' + str(self.author) def save(self, *args, **kwargs): self.url = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('article-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments" ,on_delete=models.CASCADE) name = models.CharField(max_length=30) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) date_added = models.DateTimeField(auto_now_add=True) … -
Similar view to admin for normal users in django
How can I give a similar view to normal users so they can change some data for some models. My models file is: from django.db import models # Create your models here. class ObjetoChan(models.Model): name = models.CharField(max_length=30) street_name = models.CharField(max_length=30, default= "lil jhonny") description = models.CharField(max_length=30) num_stars = models.IntegerField(default=3) And I want to show to them a list of all the objects, in a way that for each one they can alter one particular value. Like in the admin when you have this: What I mean And when we have the list it should look like something like: this. However I just learning so I do not want to expose the admin to them, because I can be sure to make this safe. -
searching in a django models of vectors with a custom function
im using django for a face recogntion app and i need to save face descriptor in djangomodel and then retreive them and compare with the vectors of a new image and get the model in the database that have the nearest distance with the new vectore. so in short i have a model of persons each model have a textfield that represent a vector i have a function compare(vec1,vec2) that take two vectors as strings and return the distance between them i have a new vector (not in the database) i need to apply the compare function on the model and retrieve the person that his vector field have the minimum distance with the new vector -
Javascript cookie isn't saved
while working on my first django project I got stuck dealing with cookies on javascript. I'm building a kind of e-commerce website and trying to improve the guest user interaction. I tried to create to cookie that in the future will contain the guest user cart and can't see it when I check the browser cookie so I think the cookie is now saved at all: <head> <meta charset="utf-8"> <title>Webpage</title> <script type="text/javascript"> function getCookie(name){ var cookieArr = document.cookie.split(";"); for (var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); if (name == cookiePair[0].trim()){ return decodeURIComponent(cookiePair[1]); } } return null; } var cart = JSON.parse(getCookie('cart')); if (cart == undefined){ cart = {} console.log("Cart was created!") document.cookies = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"; } // console.log('Cart:',cart); </script> </head> Hope someone can help me, Thanks ahead. -
Many-To-Many Field remove deleting instance
I have the following code too add or delete votes from a particular article. However, whenever I send a delete request to the API endpoint, the entire article instance gets deleted. views.py class ArticleUpvoteAPIView(views.APIView): serializer_class = ArticleSerializer permission_classes = [IsAuthenticatedAndNotAuthor,] def post(self, request, slug): article = Article.objects.get(slug=slug) user = self.request.user article.voters.add(user) article.save() serializer_context = {"request": request} serializer = self.serializer_class(article, context = serializer_context) return Response(serializer.data, status=status.HTTP_200_OK) def delete(self, request, slug): article = Article.objects.get(slug=slug) user = self.request.user article.voters.remove(user) article.save() serializer_context = {"request": request} serializer = self.serializer_class(article, context = serializer_context) return Response(serializer.data, status=status.HTTP_200_OK) models.py class Article(models.Model): ... voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="votes") urls.py urlpatterns = [ path('<slug:slug>/like/',ArticleUpvoteAPIView.as_view(), name="article-upvote-view"), ] What could be the reason? How do I change this? -
Adding a Coupon System not working Properly for a Django Project
I have set a Coupon Payment System for my E-commerce project but I am facing some difficulties in showing the correct errors when different errors take place like using an expired coupon or invalid one which is all showing the same error "You can't use the same coupon again" How can I fix this error, I have started trying else but when an invalid coupon is added it shows "You can't use the same coupon again" How I add several conditional if Here is the models.py class Coupon(models.Model): code = models.CharField(max_length=15,unique=True) amount = models.DecimalField(decimal_places=2, max_digits=100) valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.code Here is the views.py class AddCouponView(View): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) coupon_qs = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now) order_coupon = Order.objects.filter(coupon=coupon_qs.first(), user=self.request.user) if order_coupon: messages.error(self.request, "You can't use same coupon again") return redirect('core:checkout') if coupon_qs: order.coupon = coupon_qs[0] order.save() messages.success(self.request, "Successfully added coupon") return redirect('core:checkout') else: messages.error(self.request, "Coupon Does not Exists") return redirect('core:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('core:checkout') Here is the forms.py class CouponForm(forms.Form): code = forms.CharField(widget=forms.TextInput(attrs={ … -
How can I import component from variable or props - Dynamic router
Context for a good solution (short question in bottom). I have a database (API) which generate list of data of apps like AppA, AppB, AppC, etc. with their name, path... With a map, I generate (react router) links to these apps based on this data list (in the main <App/>) and front. With another identical map (below), I have made the router which should call the App based on the route and app name: function(Router) { const [routes, setRoutes] = useState([]); useEffect(() => { fetch("MyAPI") .then(res => res.json()) .then((result) => {setRoutes(result.results)} ) }, []) // The route for each app and after the map, the route to the home with these links return ( <Switch>{ routes.map(result => <Route exact path={"/"+result.route} key={keygen(16)}> <AppCaller name={result.name} id={result.id} path={"/"+result.route}/> </Route> )} <Route exact path="/"> <App /> </Route> </Switch> ) } export default Router My first problem is I cannot neither give a component Name like <result.name/> from the API to call this component in the Router nor import dynamically this component. My first solution was to create another component <AppCaller/> with the name and path as Props to remove the component problem like this : import React from "react"; import Window from "./dashComponents" import … -
Django is not creating a new user
In my html I am see the form of registration but when I am trying to register in just restart the page and is not creating a new user. Sorry this question can fill like stupid, but I was trying to solve it for a long time. Here are my file codes. <form method="POST" name="signup"> <p>Sign Up</p> {% csrf_token %} {{ form|crispy }} <button type="submit">Sign Up</button> </form> views.py def index(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if 'signup' in request.POST: if form.is_valid(): form.supervalid() form.save() username = form.clened_data.get('username') messages.success(request, f'Dear {username} you have been created a new account!') return redirect('main') elif 'login' in request.POST: log_view = auth_views.LoginView.as_view(template_name='main/index.html') log_view(request) else: form = UserRegisterForm() formlog = AuthenticationForm(request) return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() name_and_surname = forms.CharField(min_length=5, max_length=30) def supervalid(self): expr_a = User.objects.filter(name_and_surname=self.cleaned_data['name_and_surname']).exists() expr_b = User.objects.filter(email=self.cleaned_data['email']).exists() if expr_b: raise ValidatioError(f'There already exists user with that email, use another one ;)') if expr_a: raise ValidatioError(f'This name is already used, sorry') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) -
(OpenCV, Apache2, Django, RPi3) I'm making a web server that can stream images from the RPi cam but it says NEON NOT AVAILIABLE
As the title says, Im running into a "fatal error' when I check the apache2 error logs. This is what it says: ****************************************************************** * FATAL ERROR: * * This OpenCV build doesn't support current CPU/HW configuration * * * * Use OPENCV_DUMP_CONFIG=1 environment variable for details * ****************************************************************** Required baseline features: NEON - NOT AVAILABLE terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(3.4.4) /home/pi/packaging/opencv-python/opencv/modules/core/src/system.cpp:538: error: (-215:Assertion failed) Missing support for required CPU baseline features. Check OpenCV build configuration and required CPU/HW setup. in function 'initialize' [Wed Oct 07 19:50:54.935323 2020] [wsgi:error] [pid 1975:tid 1972368432] [client 192.168.0.156:63619] Truncated or oversized response headers received from daemon process 'Rover': /home/pi/dev/Rover/src/Rover/wsgi.py I'm using a rpi3 for this budget rover project. The camera for it is very similar to this github repo, https://github.com/sawardekar/Django_VideoStream . My project does not have the ML/AI elements that are in this repo. It also does not have the webcam_feed(), livecam_feed(), mask_feed() in the streamapp/views.py file. I have no clue what a NEON is. I tried installing a fresh raspbian stretch file and it still gave me this error. I am also not able to sudo nano into the system.cpp file that this error mentions. pls halp. -
Django template: How to use values/values_list
In template I am trying to do something like this: {{ request.user.profile.following.all.values_list }} and I get <QuerySet [(7, 2, 1)]> , but I want to get <QuerySet [2]> like in Django values_list. For example: Follow.objects.filter(follow_by=self.request.user.profile).values_list('follow_to', flat=True) Can I pass argument like this in template? -
How to make Django 3, channels and uvicorn work together
I have been trying to switch from daphne to uvicorn for production with a project using django 3 and channels. I have been encountering errors while loading the classical asgi file for channels. Either I can't use it due to synchronous call to django.setup or get_application. I tried to tweak this file with the sync_to_async call without success. Has anyone managed to make it work ? Original asgi.py Code import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") django.setup() application = get_default_application() StackTrace Traceback (most recent call last): File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/lib/python3.8/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started target(sockets=sockets) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 407, in run loop.run_until_complete(self.serve(sockets=sockets)) File "/usr/local/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete return future.result() File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 414, in serve config.load() File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/config.py", line 300, in load self.loaded_app = import_from_string(self.app) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string module = importlib.import_module(module_str) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
What will Happen if i remove footer credit from colorlib html template(https://colorlib.com/preview/theme/dento/index.html) for django?
I am first time trying to use a readymade template for my website and I have downloaded the 'Dento'(https://colorlib.com/preview/theme/dento/index.html) template from Colorlib(https://colorlib.com/) and in the terms and condition is written that if I am using a free template I am not allowed to remove the footer credit so what will happen if I remove the footer credit ,will they be able to track me or find me or file a lawsuit or what ?? please tell me what can happen if I remove the footer credit and publish my website through heroku -
Django Rest Framework raise Validation Error Message
I am working on bus booking api where BoardingPoints and Location Model having ManytoMany Relations. I tried adding some validation while removing relation between location and boarding point. I want validation error in following format {'point': Boarding point: Manchester is not assigned to Location: London} My code is below class RemoveBoardingPointFromLocationUseCase(BaseUseCase): """ Use this to remove boarding point assigned to list """ def __init__(self, serializer: DeleteBoardingPointToLocationSerializer, location: Location): self._serializer = serializer self._data = serializer.validated_data self._location = location def execute(self): self._is_valid() self._factory() def _factory(self): self._location.point.remove(*self._data.get('point')) def _is_valid(self): boarding_points = self._location.point.all() if not set(self._data.get('point')).issubset(set(boarding_points)): _message = ("{point: Boarding point: %(boarding_point)s is not in %(location)s}" % { 'boarding_point': self._data.get('point')[0], 'location': self._location}) raise ValidationError(_message) I am getting message in following format if I try self._data.get('point')[0:] validation error message as "{point: Boarding point: [<BoardingPoint: Manchester>, <BoardingPoint: Oxford>] is not in London}" what should i do in my validation error message part? -
Django: Identical text not unique on binary level
I have a modal with a field my_field which has to be unique. I´ll check if a task has to be executed later onwards by checking if the entity already exists: class MyModel(models.Model): my_field = models.CharField(max_length=75, unique=True) And later: if MyModel.objects.filter(my_field=my_value).exists(): pass # execute task and save it under the value name in question else: pass The values I need to compare here are received via two different 3rd party apis. Now I have the problem, that the "human readable" same text is not detected as identical, which makes the unique attribute fail (in the sense of it does not let the save fail) and of course also the "does it exist? check". So after a while, I hacked into django shell and converted two of the values into binary code and that way they are not the same. So I read about normalization and came up with this: class MyModel(models.Model): ... def save(self, *args, **kwargs): if self.pk is None: self.my_field = unicodedata.normalize('NFC', self.my_field) ... And before I query the DB, I normalize the received value the same way. Still I get instances with the same "human readable text" but different binary code and the problem persists. How can I … -
Django: How to decide between class-based and function-based custom validators?
This is a beginner question. I'm working on a website that allows users to upload a video to a project model (via ModelForm) and I want to validate this file correctly. I originally declared the field in this way: from django.db import models from django.core.validators import FileExtensionValidator def user_directory_path(instance, filename): """ Code to return the path """ class Project(models.Model): """ """ # ...Some model fields... # Right now I'm only validating and testing with .mp4 files. video_file = models.FileField( upload_to=user_directory_path, validators=[FileExtensionValidator(allowed_extensions=['mp4'])] ) But I read in several places that it was better to use libmagic to check the file's magic numbers and make sure its contents match the extension and the MIME type. I'm very new to this, so I might get some things wrong. I followed the validators reference to write a custom validator that uses magic. The documentation also talks about "a class with a __cal__() method," and the most upvoted answer here uses a class-based validator. The documentation says that this can be done "for more complex or configurable validators," but I haven't understood what would be a specific example of that and if my function-based validator is just enough for what I'm trying to do. I … -
Reaching the fields in the data serialized over the table
With django, a json data comes as below. How can I access the fields in this incoming data? In other words, after serializing the data I query from the table, I need to access all of them one by one. [{ 'model': 'cryptoinfo.cryptoinfo', 'pk': 4, 'fields': {'createdDate': '2020-10-08T20:49:16.622Z', 'user': 2, 'created_userKey': '25301ba6-1ba9-4b46-801e-32fc51cb0bdc', 'customerKey': '61754ecf-39d3-47e0-a089-7109a07aca63', 'status': True, 'side': 'BUY', 'type': '1', 'symbol': 'NEOUSDT', 'quantity': '1', 'reversePosition': '1', 'stopMarketActive': '1', 'shortStopPercentage': '1', 'longStopPercentage': '1', 'takeProfit': '1', 'addPosition': '1', 'takeProfitPercentage': '1', 'longTakeProfitPercentage': '1', 'shortTakeProfitPercentage': '1', 'groupCode': '1453', 'apiKey': 'API_KEY', 'secretKey': 'SECRET_KEY'}}, { 'model': 'cryptoinfo.cryptoinfo', 'pk': 7, 'fields': {'createdDate': '2020-10-08T20:51:16.860Z', 'user': 1, 'created_userKey': '2f35f875-7ef6-4f17-b41e-9c192ff8d5df', 'customerKey': 'b1c8cee3-c703-4d27-ae74-ad61854f3539', 'status': True, 'side': 'BUY', 'type': '1', 'symbol': 'NEOUSDT', 'quantity': '1', 'reversePosition': '1', 'stopMarketActive': '1', 'shortStopPercentage': '1', 'longStopPercentage': '1', 'takeProfit': '1', 'addPosition': '1', 'takeProfitPercentage': '1', 'longTakeProfitPercentage': '1', 'shortTakeProfitPercentage': '1', 'groupCode': '1453', 'apiKey': '', 'secretKey': ''}} ] def webhook(request): queryset = CryptoInfo.objects.filter(status=True, symbol='NEOUSDT', side='BUY') data = serializers.serialize('json', queryset) for sym in data: print(sym.get('created_userKey')) sleep(1) return HttpResponse(data, content_type='text/json-comment-filtered')