Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to call a function on a model field?
I have a model which has a FileField and I now need to call an API to convert the file. Not sure on how to implement the function and also, how to show the file to the user after it's converted. I was thinking of calling the function on each model object and then just changing the url in the model to the new file. Is there a way to call the function before the file is saved to the DB to make things easier? I'm not sure if this is possible because I'm guessing that the file must be saved before it's converted. -
Django views in modules in "views" package, call by module name - Namespacing problem
My views.py is getting large, and I'd like to organize different parts of my django website by functionality. I envision something like this: urls.py views ├── __init__.py ├── editor.py └── display.py In my urls.py I'd like to have seperated namespaces like this: url(r'^display_some_post/$', views.display.post, name="display_post"), url(r'^edit_some_post/$', views.editor.post, name="editor_post"), Note that every view is called by it's module name. But I can't quite figure out the correct way to set up init.py and / or import the modules into the urls.py. Any help is appreciated! -
Django with Angular - relative paths when font and back have different url
After two days I failed to setup (any form of) webpack working with django3 in the back and angular10 in the front, so I decided to just use gulp to start ng serve for frontend and python manage.py runserver for backend. I am new to this, so this is probably very stupid but really two days is a lot of time to give on setup and get nothing back .. Currently I am trying to call an API on the django server that is on http://127.0.0.1:8000 while ng serve is running on http://127.0.0.0:4200 @Injectable() export class EchoService { constructor(private httpClient: HttpClient) {} public makeCall(): Observable<any> { return this.httpClient.get<any>( 'http://127.0.0.1:8000/my-api/' ); } } ''' Is there a better way how to do this in Angular without using "http://127.0.0.1:8000" in every component call I do? How can I make it as close as possible to relative paths, that will be used in the prod version of this (for prod I will just put the bundles manually in the html, but I can not do that manually for dev) -
(1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'")
i have been making some changes on my model 'lesson' and suddenly i couldn't use my model on my django website with MySql data base. when i try to use it on a view i got this error (1054, "Unknown column 'leçon_lesson.subject_id' in 'field list'") the commands makemigrations and migrate works fine but this error occurs when using the model only this is the model.py from django.db import models from .validators import * from scolarité.models.level import Level from scolarité.models.subject import Subject class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) def __str__(self): return self.lesson views.py #=========================== view lessons ===================== @login_required #use this to make the view accessible for logged in users only def view_lessons_list(request,subject_id): request.session['subject_id']= subject_id #assign subject id value to session level = Level.objects.get(id=request.session['level_id']) #getting the level model subject = Subject.objects.get(id=request.session['subject_id']) #getting the subject model lessons = Lesson.objects.filter(subject=subject ,level=level) #filtering the lesson based on the chosen level and subject context={'lessons':lessons,} return render(request,'leçon/view_lessons_list.html',context) the traceback Traceback (most recent call last): File "C:\Users\YAHYA-PC\Desktop\CourseCode\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File … -
Comment section in django blog won't show up under each individual post?
The comment successfully saves in the django admin but won't show up on the actual site. Here is the comment model: class comment(models.Model): linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE) commentauthor = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) This the html code for the blog home. the post for loop goes through all the post objects and prints them out. I created a comment loop to loop through all the comments for the linked post and print. Is the problem in my html code? {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div> <h2>Comments</h2> {% for cmnts in linkedpost.postcomments %} #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a> <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small> <p class="article-content">{{ cmnts.body }}</p> {% endfor %} </div> </div> </article> {% endfor %} -
How to set a maximum no. for a Coupon can be used in Django Project
I have set a Coupon Payment System for my E-commerce project but I want to set a maximum no. of usage for this coupon for maximum 10 times. How do I do that? 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,active=True) 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={ 'class': 'form-control', 'placeholder': 'Promo code', 'aria-label': "Recipient's username", 'aria-describedby': "basic-addon2" })) -
Authenticate function not working in Django
I am trying to authenticate in Django using authenticate but my code is not running and showing errors. My code: def post(self, request): data = request.data username = data.get('name', '') password = data.get('password', '') if not username or not password: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(request, username=username, password=password) if not user: return Response({'Error': 'Invalid name/Password'}) login(request,user) What's wrong in my code? I am getting both username and password from json but it's failing to validate. -
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.