Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How make Like button in django using ajax
How I can connect like button in Django to ajax and when the button hit the number of likes +1 and if hit again the number of likes -1 my view class AddLike(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): video = Video.objects.get(pk=pk) is_dislike = False for dislike in video.dislikes.all(): if dislike == request.user: is_dislike = True break if is_dislike: video.dislikes.remove(request.user) is_like = False for like in video.likes.all(): if like == request.user: is_like = True break if not is_like: video.likes.add(request.user) if is_like: video.likes.remove(request.user) next = request.POST.get('next', '/') return HttpResponseRedirect(next) my template html <form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form"> {% csrf_token %} <input type="hidden" class="likin" name="next" value="{{ request.path }}"> <button class="remove-default-btn" type="submit" id="openPopup" class="remove-default-btn like-btn{{ request.path }}" style="border: none; "> <i class="fa fa-thumbs-up" aria-hidden="true"><span class="">{{ video.likes.all.count }}</span></i> </button> </form> -
Filtering Objects Based On Another Model
I have a website where service providers upload their services to the site and in addition to their services they can also upload the FAQ for each service they create. So I have two models for this each separate and linked with a Foreign Key. below is my model.py file with these two models class Services(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(editable=False, max_length=130) category = models.ForeignKey(Category, on_delete=models.CASCADE) intro = models.CharField(max_length=100, unique=True) pricing = models.IntegerField() detail = SummernoteTextField() image = models.ImageField(default='default.png', upload_to='services') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class FAQ(models.Model): question = models.CharField(max_length=150, help_text="The possible question that a client could ask you") answer = models.TextField(help_text="The response to the question above") service = models.ForeignKey(Services, on_delete=models.CASCADE, related_name='faq_service', help_text="Which service is this FAQ linked to?") author = models.ForeignKey(User, on_delete=models.CASCADE) Within my views.py I have added the capabilities that allow me to display a ListView to of the FAQ within the same DetailView which contains all details of the post. My views.py for that looks like this: class ServiceDetailView(DetailView): model = Services def get_context_data(self, *args, **kwargs): context = super(ServiceDetailView, self).get_context_data(*args, **kwargs) context['faq'] = FAQ.objects.all() # to fix-->Need to only show FAQ of that service return context Now, I need to be able to Filter the FAQ … -
How do i edit a record but show existing value selected of a drop-down box
models.py class Products(models.Model): Name = models.CharField(max_length=100, verbose_name='Name of Product') Category = models.CharField(max_length=100, verbose_name='Product Category') Description = models.CharField(max_length=220, verbose_name='Product Description') class Categories(models.Model): Title = models.CharField(max_length=100, verbose_name='Category Title') Description = models.CharField(max_length=100, verbose_name='Category Description') Picture = models.ImageField(default='/gifts.png', upload_to='ffff/') def __str__(self): return self.Title forms.py class EditProduct(forms.ModelForm): class Meta: model = Products fields = ['Name', 'Category', 'Description', 'Weight', 'Size', 'Cost', 'Personalised', 'Keywords', 'Picture1'] widgets = { 'Category': Select(), } def __init__(self, *args, **kwargs): super(EditProduct, self).__init__(*args, **kwargs) self.fields['Category'] = forms.ModelChoiceField(queryset=Categories.objects.all().order_by('Title')) I've created records in models.py Categories (eg Title = 1, Title, 2, Title =3) In models.py Products i have created some records (eg Name=Hat, Category=1; Name=Cap, Category=3) I can add Product records easily with crispy forms and my drop down list appears for Category, select the choice and form saves. All works great But when i try to EDIT the record, i use instance= and it brings the contents of the record back, but i also want a drop down list for category in the edit section, but if i put a drop-down list in, then it doesn't populate that field with existing value, i need to reselect it My views.py def products_edit(request, item_id): pp = Products.objects.get(id=item_id) my_form = EditProduct(instance=pp) if 'first' in request.POST: if request.method … -
Ticket Selling Problem in REST with django
I am doing a project where we run into a problem, where we have N number of tickets available at certain time. And we are serving it from the backend REST API and people are buying it in FIFO fashion. Its like a race between the buyers. Problem: Currently we are handling it like first we take the money from the user (we take money first because it is might possible that customer's bank transaction fails due to some reason so we make it confirm we do not lose anything) and the proceed for the conformation email but we faced the Overbooking issue. Because we already had taken the money but there was no tickets available because in the meanwhile someone else bought it. So we have to give that customer tickets, which lead us to over booking. I want to solve it. I have put some thoughts on it. First Solution: The first solution I come up with is that I have an API that will initially check whether enough tickets are available to sell, if it is, it subtract the number of tickets from the available tickets and ask the customer for payment. Once the payment get confirmed … -
What is the best way of creating a 'featured image' in Django?
I'm relatively new to Django and I'm looking for a way to create a featured image within an image category. At the moment I have a Show class and a Photo class: class Show(models.Model): title = models.CharField(max_length=100, unique=True, db_index=True) playwright = models.CharField(max_length=100) description = models.TextField() def __str__(self) -> str: return self.title class Photo(models.Model): show = models.ForeignKey(Show, on_delete=models.CASCADE) image = models.ImageField(upload_to='', default='images/default.png') def __str__(self) -> str: return self.image.name And I'd like to be able to set one photo for each show as the 'featured' image. Of course, I could put a Boolean field in for this, but that runs the risk of having multiple Featured images when there should be only one. What is the best structure for this? I've had a look around and can't find any tutorial or resource that shows this behavior. I should be able to set this 'featured' setting from the admin panel. (Also, I'm aware there are gallery apps out there for Django, but this is part of my learning Django, so I'm trying to build this myself.) Thanks! -
Angular + Django project
Bonsoir, je travaille sur un projet angular et l'API a été créé avec Django. Je souhaite récupérer les images depuis mon serveur et les afficher côté front-end dans mon application mais je ne sais pas comment m'y prendre, une aide précieuse de vous me serait utile. Merci d'avance. -
Command errored out with exit status 1:
I have problem when i try to push my app on heroku, so when i write git push heroku master this error is appear remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-48na90v5/importlib/setup.py'"'"'; __file__='"'"'/tmp/pip-install-48na90v5/importlib/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-dccx97n0 remote: cwd: /tmp/pip-install-48na90v5/importlib/ remote: Complete output (11 lines): remote: Traceback (most recent call last): remote: File "<string>", line 1, in <module> remote: File "/app/.heroku/python/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> remote: import distutils.core remote: File "/app/.heroku/python/lib/python3.6/distutils/core.py", line 16, in <module> remote: from distutils.dist import Distribution remote: File "/app/.heroku/python/lib/python3.6/distutils/dist.py", line 19, in <module> remote: from distutils.util import check_environ, strtobool, rfc822_escape remote: File "/app/.heroku/python/lib/python3.6/distutils/util.py", line 9, in <module> remote: import importlib.util remote: ModuleNotFoundError: No module named 'importlib.util' remote: ---------------------------------------- remote: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed -
Dokku Postgres: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
welpie/settings.py import dj_database_url DATABASES = {'default': dj_database_url.config()} I have also linked my app with postgresdb: -dokku postgres:link welpiedb welpie Also checked if it is running. welpiedb postgres service information Status: running Error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? why am i getting this error ? can anybody help? -
path/url not showing up
So I'm trying to make an API and I have followed the documentation but the products path is just not showing up, I have register product in admin and it says these are the paths available, also I did not define login or logout in this API yet, Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: admin/ api/ login/ [name='login'] api/ logout/ [name='logout'] The current path, api/products, didn't match any of these. urls.py backend from django.contrib import admin from django.urls import path, include from rest_framework import routers urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('API.urls')) ] urls.py API from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('products', views.ProductViewSet) urlpatterns = [ path('', include('rest_framework.urls', namespace='rest_framework')) ] views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product # Create your views here. class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer serializers.py from rest_framework import serializers from .models import Product class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name','price','description'] -
Django Querystring Extract Dictonary
I want to send a post request via ajax to my django server. Within this, there is the data dictonary "inputs": $.ajax({ type: 'POST', headers: { "X-CSRFToken": this.csrf }, data: { "Intent": intent, "Inputs": inputs}, ... The inputs-object is something like this: inputs = { "Var1": "Test1", "Var2": "Test2"} Django converts the request data to a Querydict: <QueryDict: {'Intent': ['18'], 'Inputs[Var1]': ['Test1'], 'Inputs[Var2]':['Test2']}> I want to extract the inputs-object so that I can work with it the same way like with a python dictonary. I've tried: request.POST request.POST.iterlist() request.POST.get('Inputs') dict(request.POST) dict(request.POST.iterlist()) dict(request.POST._iterlist()) request.POST.getlist() but I never got a python dict. How do I extract a object/dict of a Querydict? -
Python Twilio without using flask or django?
As far as I know, this question hasn't really been asked. I want to use twilio to send and receive messages from a python app. Sending isn't a problem, but I know receiving uses webhooks. Every tutorial and even the twilio documentation uses flask. Im wondering if I can create a program to receive information from twilio without using flask or is flask/django required. Thanks -
How to get rid of OrerderedDict in the default HTML form of django rest_framework?
I am working on an API and this is how it looks in the top section: Every field is working great but, I am not able to fix the context and config field in the HTML form whose output looks in this way: The Configuration section of it comes from a nested serializer. Relevant serilizers.py code:- class ConfigSerializer(ValidatedModelSerializer): context = serializers.JSONField() config = serializers.JSONField() class Meta(BaseMeta): model = Config fields = '__all__' class DeviceDetailSerializer(ValidatedModelSerializer): configuration = ConfigSerializer(read_only=False, source='config') class Meta(BaseMeta): model = Device fields = DeviceListSerializer.Meta.fields + [ 'created', 'modified', 'configuration', ] Can I have tried adding context = serializers.JSONField(binary=True) but with this my top content type of the endpoints gets rendered with trainling \n for the fields of config and context Is there anyway I can get rid of this. What I basically expect is to get the same output in the both HTML form and the ContentType as in JSON Format. -
How to specify a srid when creating a GeometryField model object?
I understand that generally, the srid is associated with the GeometryField model, not the instance itself. However, is it possible to specify the srid at the instance creation, which can be different for each feature? Here is my model class VectorEntity(models.Model): geomdata = gisModels.GeometryField(blank=True) layer = models.ForeignKey(VectorLayer, on_delete=models.CASCADE) and here is how I create the VectorEntity instances: for feature in layer: VectorEntity.objects.create(geomdata=feature.geom.geos, layer=vectorLayer) Where layer is a OGR DataSource object. feature.geom.geos looks like that: SRID=3826;POINT (226930.946787846 2563160.436286877) However, the features are always saved with the default srid=4326 and the coordinates adapted. Is that possible to have a per-feature srid? -
Building an Autocomplete Form Element with Atlas Search and Django
I want to build an autocomplete form in a Django webapp. I have already been able to do the search bar where I query my MongoDB database with: class SearchResultsView(ListView): model = Perfume template_name = 'todo/search_similar_results.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = list(collection.find({"q0.Results.0.Name": {"$regex": query, "$options": "i"}})) return object_list How can I do an autocomplete? I tried to adapt an official tutorial that does it with Javascript: search_similar.html: <div class="recommendations"> <!-- <div class="login-page"> --> <div class="form"> <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Perfume name..."> <input type ="submit" value="Find Similar Perfumes" /> </form> <form class="login-form" action = "/predict" method="POST"> <input type="text" placeholder="perfume name"/> <!-- https://www.youtube.com/watch?v=TRODv6UTXpM&ab_channel=ProgrammingKnowledge --> <input id="perfumename" type ="submit" value="Find Similar Perfumes" /> </form> </div> <script> $(document).ready(function() { $("#perfumename").autocomplete({ source: async function(request, response){ let data=await fetch(`http://localhost:3000/search_similar?q={request.term}`) .then(results => results.json()) .then(results => results.map(result => { return { label: result.name, value: result.name, id:result._id }; } response(data); }, minLength=2, select: function(event, ui){ console.log(ui.item); } }) }) </script> </div> But it seems that I have my own former autocomplete that shows up: I don't know if I would have been able to do it without Javascript... -
How Increase the number of likes when hit the button
I using Django and I find difficult in ajax I want when the user click the button the number of likes increase 1 and the button color change and if click again the number of likes decrement 1 my template <form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form"> {% csrf_token %} <input type="hidden" class="likin" name="next" value="{{ request.path }}"> <button class="remove-default-btn" type="submit" id="openPopup" class="remove-default-btn like-btn{{ request.path }}" style="border: none; "> <i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i> </button> </form> my ajax $("#my-like-form").submit(function(e){ e.preventDefault(); let form = $(this); let url = form.attr("action"); const likes = $(this).find("button[class*=like-btn] span").text(); const trimCount = parseInt(likes) console.log(trimCount) var selector = $(this).find("button[class*=like-btn]") let res console.log(trimCount) $.ajax({ type: "POST", url: url, data: form.serialize(), dataType: "json", success: function(response) { selector = document.getElementsByName(response.next); if (response.liked == true) { console.log('Hello'); $(selector).css("color", "blue"); res = trimCount + 1 } else if (response.liked == false) { $(selector).css("color", "black"); res = trimCount - 1 } $(selector).find("span").text(res) } }) }) -
Segfault while running django tests in parallel mode on macOS
When i running test in regular mode there is no problem. But if i trying to run test with --parallel flag i'm always getting segmentation fault in my system after processing half of my tests. I have ~7000 tests in my project and segmentation fault happened always when ~3500 test passed) I've tried to use OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES environment variable to solve this problem but it doesn't help me. Here is some system trace of my error: Process: Python [21265] Path: /Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.6.8 (3.6.8) Code Type: X86-64 (Native) Parent Process: Python [21222] Responsible: pycharm [342] User ID: 501 Date/Time: 2021-03-01 17:22:25.997 +0200 OS Version: macOS 11.2.1 (20D74) Report Version: 12 Bridge OS Version: 3.0 (14Y908) Anonymous UUID: 61E9A706-0C04-8107-68D7-088455564AD6 Time Awake Since Boot: 24000 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000008 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [21265] VM Regions Near 0x8: --> __TEXT 10d915000-10d916000 [ 4K] r-x/rwx SM=COW /Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python Application Specific Information: *** multi-threaded process forked *** crashed on child side of fork pre-exec Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 com.apple.CoreFoundation 0x00007fff205afaf6 _CFGetNonObjCTypeID … -
maximum recursion depth exceeded while calling a Python object with def __str__(self): when I delete the inline form object
I am encountering a maximum recursion depth exceeded...error when I try to delete one of the inline forms in Django admin. this is my model: class Correction_Factors (models.Model): Treatment_unit= models.ManyToManyField(Unit,blank=False) def __str__(self): # def __Unicode__(self): list_01 =self.Treatment_unit.all() print(list_01) return u", ".join([a.name for a in self.Treatment_unit.all()]) It seems to be the problem is in "self.Treatment_unit.all()". No errors occurred while the inline form is created. It has only come up as soon as I started to delete one of the inline forms. I tried to switch to "def Unicode(self):" but it did not return what I expect. The returned text appeared like "Correction_Factors object (23)" with no details. N.B. There is no delation issue with "def Unicode(self):". And I am on Djano 2.2.18 and python 3.9.2 Appreciate your help in advance. -
Use list_editable with get_list_editable in Django Admin
I am showing the fields of a model conditionally in the Admin page based on a filter. I would like to some of these fields that are common to the lists to be editable. I am using get_list_display to create the condition of which fields are to be displayed based on the argument of a filter. How can I use the list_editable in this case? This is what I did and it doesn't create the edit widgets for the fields. def get_list_display(self, request): # The columns in the list view param = request.GET.get('param__exact', False) if protocol and protocol == 'ethernet-ip': list_display = ('A', 'B', 'C', 'D',) else: list_display = ('B', 'C', 'F', 'G',) list_editable = ('B', 'C',) return list_display -
How to integrate Stripe payment without redirects - Django
I have my stripe payment up and working. However I am wanting the user to be able to make the payment without leaving the page they are on. Is it possible to submit a Stripe Payment using Django without redirecting? -
How to give different access to different roles?
How can I allow access only for admin,moderator(I have these roles in models) and author for patching or deleting the post, and access to get request for everybody Here is my code, permissions: class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user class MyPermissionClass(permissions.BasePermission): # def is_authenticated(self, request): # return request.user and request.user.is_authenticated def has_permission(self, request, view): if view.action == 'create' and request.user.is_authenticated: return True if (view.action == 'destroy' or view.action == 'update' or view.action == 'partial_update') and (request.user.is_admin or request.user.is_moderator): return True if view.action == 'list' or view.action == 'retrieve': return True return False views: class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [MyPermissionClass, IsAuthorOrReadOnly] Will it work? Or one permission will overwrite another one? -
Why do I get "attempt to write a readonly database" error in Django running on Nginx?
So I have deployed my Django project using EC2, running on uwsgi and nginx. I have successfully deployed, created RDS(engine is MySQL) as well, fully working. However when I try to login to my admin, I get the error saying "attempt to write a readonly database". I understand that it is permission issue, but not getting any sufficient solution. What should I do? Thanks in advance. :) -
QueryDict coming through in django instead of JSON when AJAXing
I have like 8 ajax calls on a javascript page. 7 are like so, and go to the same view in python in Django for parsing and stuff: $.ajax({ url: '/apiForStuff", type: 'POST', cache: false, data: JSON.stringify({'boxStuff': stuff}), contentType: "application/json", dataType: 'json', success: function(data) { table.reload() }, error: function(err) { console.log('err', err) } }); 1 is like this: $.ajax({ url: '/otherAPIStuff", data: formData, type: 'POST', cache: false, contentType: application/x-www-form-urlencoded; charset=UTF-8', processData: false, dataType: 'json', success: function(data) { table.reload() }, 'error': function(err) { console.log('err', err) } }); The view called by the first one (and seven like it): @method_decorator(login_required, name='dispatch') class StuffUpdater(LayerDetailMixin, ApplicationDomainMixin, generic.TemplateView): def post(self, request, *args, **kwargs): print(request.POST) post_request = json.loads(request.POST) The print statement prints a QueryDict, and json.loads proceeds to fail with: TypeError: the JSON object must be str, bytes or bytearray, not QueryDict -
Django how to access an abstract Base model local variables
I have defined this abstract base model as below: class ActivityAbstractBaseModel(models.Model): POOR = 'PR' FAIR = 'FA' MEDIOCRE = 'ME' GOOD_ENOUGH = 'GE' GOOD = 'GO' VERY_GOOD = 'VG' EXCELLENT = 'EX' STATE = [ (POOR, 'Poor'), (FAIR, 'Fair'), (MEDIOCRE,'Mediocre' ), (GOOD_ENOUGH, 'Good Enough' ), (GOOD, 'Good'), (VERY_GOOD, 'Very Good'), (EXCELLENT, 'Excellent'), ] speaking = models.CharField(max_length=50, choices=STATE, default=GOOD) I then inherit this abstract model as below and added the new field writing class Fluency(ActivityAbstractBaseModel): writing = models.CharField(max_length=50, choices=STATE, default=GOOD) Now, this new field writing is trying to access the variable GOOD and STATE that was created in the abstract class but I am having the NameError exception. Is there a way to get these variables? -
How to solve error ImproperlyConfigured: Requested setting REST_FRAMEWORK?
When testing a code with pytest I face the following error venv\lib\site-packages\rest_framework\settings.py:218: in __getattr__ val = self.user_settings[attr] venv\lib\site-packages\rest_framework\settings.py:209: in user_settings self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) venv\lib\site-packages\django\conf\__init__.py:82: in __getattr__ self._setup(name) venv\lib\site-packages\django\conf\__init__.py:67: in _setup % (desc, ENVIRONMENT_VARIABLE)) E django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried various solutions that I found in the internet, but nothing seems to work E.g. this solution import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') import django django.setup() does not work for me somehow when I'm running my code everything works just fine, the error occurs only on tests -
Django: How to filter and get results that include all the keywords searched
I have a list of posts that I filter with a simple search function that gets results based on a list of queries. It works fine when I use one keyword but when I search for multiple keywords the first one is considered and the others are ignored. So for example, if I search for 'wood' I'll get all the results that contain 'wood' (included in the content description or the name of the post) but if I search for 'wood panels' I still just get the results that include 'wood', Instead, I want to get ONLY the results that contain both keywords 'wood panels'. def searchimages(request): if request.method == 'GET': queryset= request.GET.get('q', '').split(" ") submitbutton= request.GET.get('submit') if queryset is not None: queryset_list1= Q() for query in queryset: queryset_list1 |= ( Q(name__icontains=query) | Q(content__icontains=query) | Q(format__icontains=query) | Q(contentdetail__icontains=query) ) results = Image.objects.filter(queryset_list1).distinct().order_by('-date_posted') context={'results': results, 'submitbutton': submitbutton} return render(request, 'search/search.html', context) else: return render(request, 'search/search.html') else: return render(request, 'search/search.html') Does anyone have a solution for this?