Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
DjangoLoop through an app urls in template
I'm django beginner working on my third project, but running into small issue. Basically, i have an app called 'projects' which contains html templates that the CBV needs for CreaeView, UpdateView, DeleteView and ListView. My base templates inherits from a menus file which contains all the navigation menus needed for the website. Now my issue is i wanted to make projects menu active (css) for all the crud operations of project app. i did this and it's working as intended: {% url 'projects-list' as url %} {% url 'project-detail' project.pk as url1 %} {% url 'project-create' as url2 %} {% url 'project-update' project.pk as url2 %} <a href="{{ url }}" {% if request.path == url or request.path == url1 or request.path == url2 or request.path == url3 %} class="item active" {% endif %}><span class="icon"><i class="fa fa-folder-o"></i></span><span class="name">Projects</span></a> But i don't like it this way as it's too repetitive and i want to add a lot of menus like this in future. What is the easiest way to loop through all links of app? Thanks in advance. Best regards. -
sql query to python django query
I'm new to Django and SQL. I have this following SQL query. How to implement the same in the Django query? "SELECT DISTINCT C1.CLASSDESC AS CLASS,C2.CLASSCODE AS CODE, C1.CARDCATEGORY AS CATEGORY, C2.CLASSBENEFITS BENEFITS FROM CARDCLASSMAPPING C1,CARDCLASSMASTER C2 WHERE C1.ISACTIVE = 1 AND C2.ISACTIVE = 1 AND C1.CLASSDESC = C2.CLASSDESC AND C1.SCHEMETYPE = ? AND C1.SCHEMECODE = ? AND C1.GLCODE = ? AND C1.ACCOUNTCATEGORY = ? ORDER BY CLASS"; -
Developing filtering api for the fields of two models which has many to one relationship (ie one model has a foriegn key field) using djangofilterset
Its not a problem for making a filterset for a single model. But I have two models and I have to make an endpoint http://127.0.0.1:8000/api/activities/?destination=Dubai&title=Surfing like this. Here destination is the foreign key field. I can only filter by using primary key, but I want to put the actual name of destination. What should I do? class Destination(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) discount = models.CharField(max_length=255, default="5% OFF") image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) def __str__(self): return self.name class TopActivities(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) title = models.CharField(max_length=64) description = models.TextField(blank=True) def __str__(self): return self.title class TopActivitiesSerializer(serializers.ModelSerializer): destination= serializers.StringRelatedField() class Meta: model = TopActivities fields = '__all__' class TopActivitiesListAPIView(ListAPIView): queryset = TopActivities.objects.all() serializer_class = TopActivitiesSerializer filter_backends = [DjangoFilterBackend] filterset_fields = [ 'destination', 'title', ] Here, If I put pk or id of the destination field in the query parameter, then I can see the result, but I need to be able to search by using destination name itself. -
Reverse for 'edit' with arguments '(12,)' not found. 1 pattern(s) tried: ['edit$']
In views.py def index(request): if request.method == "GET": posts = Post.objects.all().order_by('-id') allpost = True paginator = Paginator(posts, 5) # Show 5 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html",{ "AllPost" : allpost, "page_obj" : page_obj, }) def edit(request,post_id): if request.method == "POST": post = Post.objects.get(id=post_id) content = request.POST["textarea"] post.content = content post.save() return redirect("index") In urls.py path("", views.index, name="index"), path("edit",views.edit,name="edit"), Index.html <form method="POST" action="{% url 'edit' post.id %}" id="edit-form{{post.id}}" style="display:none;"> {% csrf_token %} {{post.date}} <textarea rows="5" class="form-control" name="textarea">{{post.content}}</textarea> <button type="submit" class="btn btn-outline-primary" style="float: right;">Save</button> </form> Trying to edit some post but getting an error of Reverse for 'edit' with arguments '(12,)' not found. 1 pattern(s) tried: ['edit$'] -
How to set virtualenv to stay active on a host server
I created a website that uses vuejs as the frontend and django as the backend with another service running behind everything that im making api calls to. So django is setup in a way to look at the dist folder of Vuejs and serve it if you run manage.py runserver. but the problem is that my service that I created is in python and it needs to run in a virtualenv in order to work (It uses tensorflow 1.15.2 and this can only run in a contained environment) I'm sitting here and wondering how I can deploy the django application and keep the virtualenv active and Im coming up with nothing, I've tried doing some research on this but everything I found was not relevant to my problem. I've deployed it and when I close the ssh connection the virtualenv stops. If there is anyone that can enlighten my ways I would appreciate it.