Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MySQL | Django | subclasses of BaseDatabaseOperations may require a datetime_cast_date_sql() method
I am using MySQL as database in Django Application. I am filtering date from datetime filed in Django ORM using datetime_field__date But I'm getting Error subclasses of BaseDatabaseOperations may require a datetime_cast_date_sql() method. I searched online but coudn't get any help. Basically I want to filter data on basis of date from datetime field. My code is below. I'm using mysql-connector-python==8.0.18 all_payment_requests = Payment.objects.select_related('payment_method').filter(request_date__date__lte=todays_date).filter(request_date__date__gte=last_month_day) Is there any alternative method for this? or solution to this error. -
How can I nest Django template language?
I'm trying to use a static image with a file name decided by forloop in Django template. {% for items in dictionary %} <tr> {% for records in items %} {% if forloop.counter == 2 %} <td><img src="{% static '{{ records }}.png' %}"></td> {% else %} <td>{{ records }}</td> {% endif %} {% endfor %} </tr> {% endfor %} It turned out '{{ records }}.png' part didn't work as I intended. How do I do this? -
Concurrency Payment System
When I click on 'Place Order' I have begun the transaction and set the column is_payment_processing to True before taking the user to the merchant website and then there could be three possibilities: User landed on success callback page User landed on failure callback page User landed neither on success nor on failure callback coz he closed the window. The product will remain in the state where is_payment_processing is True. And, other users who attempt to check out the same product will not be able to do so. Thinking to have a cron job to run every minute which will track the last modification time of that column and if it is not been altered for more than 3 minutes then set that flag to False. What should be the best approach here? How in general scenario this is implemented? (Concurrency Control) -
Django/plotly.js: Pass Pandas Dataframe columns to template chart
I have a pandas dataframe (not user input) stored in my database as a csv. I extract this csv in my view, and then want to pass two columns to my template and into a plotly.js chart: a date column and a value column. How should I correctly pass these as template variables in order for plotly javascript to interpret them correctly? attempted solution: views.py def chart_function(request): df = #dataframe is extracted from DB using some code dates = df['dates'] values = df['values'] return render(request, template.html, {'values': values, 'dates': dates}) template.html: <div id="myDiv"></div> <input type = "hidden" id = "dates" name = "variable" value = "{{dates|safe}}"> <input type = "hidden" id = "values" name = "variable" value = "{{values|safe}}"> <script type = "text/javascript"> var dates = document.getElementById("dates").value.split(','); var values = document.getElementById("values").value.split(','); var trace1 = { x: dates, y: values, type: 'scatter', }; var data = [trace1]; Plotly.newPlot('myDiv', data, {}, {showSendToCloud: true}); </script> The plot actually plots somewhat correctly, but it's clear that the dates are not being passed as date objects because the x axis has dates within strings and brackets. I need the df columns to be recognized as dates/values by plotly javascript. I think my halfway solution is … -
I want create a app for my business to maintain branches from the head office
I'm about to create an app for my business and looking for tutorials and all are making tutorials on website making and I want to create a desktop app which can be remotely accessed i.e i need manage my branch offices by sitting in the head office. suggest me some guideline -
Django AttributeError: type object 'Book' has no attribute '_default_manager'
I created a simple Django Webapp using django-neomodel integration. When trying to create a new book, at "http://localhost:8000/book/new" and after submitting it, I see the error as shown in the traceback. I have searched online, and in most of the cases, the errors seem to be because of some typos in specifying the model name, or inadvertently usage of strings. I have double-checked for such reasons, but couldn't see any such issues in my code. Also, I tried using Forms, by creating a form and giving a specifying form in the views, rather than model itself. But I see the same error in that case too. models.py: TITLE_MAX_LEN = 100 USERNAME_MAX_LEN = 25 NAME_MAX_LEN = 25 class Book(DjangoNode): custom_pk = UniqueIdProperty() title = StringProperty(max_length=TITLE_MAX_LEN, unique_index=True, required=True) description = StringProperty() difficulty = IntegerProperty() importance = FloatProperty() class Meta: app_label = 'knowledge' def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'pk': self.custom_pk}) views.py class BookCreateView(CreateView): model = Book fields = ['title', 'description'] template_name = "knowledge/book_form.html" class BookDetailView(DetailView): model = Book template_name = "knowledge/book_detail.html" urls.py urlpatterns = [ path('book/new/', BookCreateView.as_view(), name='book-create'), path('book/<str:pk>/', BookDetailView.as_view(), name='book-detail'), ] Traceback: Traceback: File "/Users/sam/code/website/django_env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/sam/code/website/django_env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, … -
Django Secret Key Compromised
I am wondering what are the steps one would need to take should the production secret key become compromised. Luckily, that is not the case, but it would be good to know, nonetheless. In particular, what happens if one simply swaps the old key to a newly generated one? Since it is used in making hashes, does it break the entire system or make it unstable? In the case of a compromise, would the response be as simple as generating a new key and inserting it into the production settings? -
table main_about has no column named featured_image
I am getting an error saying table main_about has no column named featured_image. I've tried running python manage.py makemigrations and python manage.py migrate however it is not working. The only thing I can think to do is delete the database but I'm hoping to avoid doing that. I read you can manually add columns through the shell? views.py def about_view(request): context = { "about": About.objects.first(), } return render(request, "main/about.html", context) models.py class About(models.Model): featured_image = models.ImageField(upload_to="about") about_text = models.TextField() def image_tag(self): return mark_safe('<img src="%s" style="height: 150; width: auto;"/>' % (self.featured_image.url)) image_tag.short_description = 'Image' class Meta: verbose_name_plural = "About Page" def __str__(self): return "About Page" -
django-allauth email confirm won't log out a user with an existing logged in session
scenario settings.py ... ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ... You are logged in as UserA on Computer 1 On another machine, Computer 2, you signup for UserB, and email is sent for confirmation On Computer 1 (with UserA still logged in) if you click on the confirm link, it will redirect you to LOGIN_REDIRECT_URL, but as UserA what I expect to happen is that it will log you out as UserA and redirect to the login page... Am I mistaken in having this expectation? -
Python/Django How do I make it so that only the creator of an object/post can see a delete/edit function button for their post?
I am currently new to python developing and am currently in school to learn multiple stacks. My code is in the most basic form. I haven't gotten to authenticated yet nor have i ever been introduced to KWARGS or pk. I also don't even know what those are at this moment. How would I make it so that the delete button only shows up to the side of the "Thought" post of the User who created the object so that they can delete it themselves but the button wouldn't be available for other User's posts? Also, how would I implement a single Like/Dislike button that transitions back and forth for every Object post in the most simple form of what I have learned thus far? this is my current code. models.py from __future__ import unicode_literals from django.db import models import re import bcrypt class UserManager(models.Manager): def registration_validator(self, postData): errors = {} EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if not EMAIL_REGEX.match(postData['email']): # test whether a field matches the pattern errors['email'] = ("Invalid email address!") if len(self.filter(email = postData['email'])) > 0: errors['email'] = "Email address has already been taken!" if len(postData['first_name']) < 2: errors["first_name"] = "Insufficient amount of character letters, you must type over 2 … -
Appending own Django DB data to data from an REST API in Graphene
I'm currently trying to figure out how to work with GraphQL with Python (graphene-django). There's one thing which is not clear to me yet which is how to append own data to REST API data (or vice-versa). The REST API I'm using is made in NodeJS/Express and should not be meddled with to maintain compatibility with other software/clients. The GraphQL node will be used as an end-point to access that REST API, but also to persist own data to an own DB and later on to connect to other REST APIs. Anyhow, so I've found this article about how to build a GraphQL wrapper, but the code examples only show how to fetch complete objects and convey it to the client. Thus no appending. Sidenote: I'm just exploring options, choosing between Apollo Server(JavaScript) and Graphene+Django. The syntax of the code below could be incorrect. I'm just trying to get a grasp on the concept. An example of how the Model class would look like: # models.py from django.db import models class User(models.Model): # REST API data - fetched from a different server. id = models.IntegerField() name = models.CharField(max_length=100) email = models.CharField(max_length=320) avatar = models.CharField(max_length=64) # etc # Own DB data … -
Not able to see the filter option with Django class based views
I have the below two views : class BookApiView(APIView): filter_backends = (filters.SearchFilter,) search_fields = ('title',) authentication_classes = (JSONWebTokenAuthentication, ) permission_classes = (IsAuthenticated, IsNotBlacklistedUser) def get(self, request): books = Book.objects.filter( user=request.user.id, is_published=True).order_by('-title') serializer = BookSerializer(books, many=True) return Response(serializer.data) def post(get, request): data = request.data serializer = BookSerializer(data=data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) class AllBookViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = AllBookSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title',) def get_queryset(self): queryset = Book.objects.all() title = self.request.query_params.get('title', None) if title is not None: queryset = queryset.filter( title__contains=title, is_published=True) queryset = queryset.filter(is_published=True) return queryset They both work on the same model. However with one(AllBookViewSet) i can see the filter option on the django rest framework UI and with the other one i cannot. Is django filter no applicable for class based views . I am assuming that should not be the case but then where am i going wrong here. Please help -
Managing cart for non registered users with sessions on Django
I want to let me users be able to add products to cart and check out without registering. I am trying to associate a session_key with each cart to organize things. However I am not sure about the some things: How to add my session_key as a field to my model How to recognize when to create a new session Here is my code for my cart/models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from django.contrib.sessions.models import Session from paintings.models import Painting # https://stackoverflow.com/questions/29113548/django-anonymous-session-temporary-one-to-one-related-model class CartManager(models.Manager): def new_or_get(self, request): #getting existing object if it exists, create new object if none exists cart_id = request.session.get("cart_id", None) #get the current id or None qs = self.get_queryset().filter(id=cart_id) #querying the id to make sure that it actually exist if qs.count() == 1: new_obj = False cart_obj = qs.first() #if the id doesn't exist then we'll create a brand new one and start that new session else: cart_obj = Cart.objects.new_cart(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id #this is the setter return cart_obj, new_obj def new_cart(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated: user_obj = user defaults = {'session_key': request.session.session_key} else: session_key = request.session.session_key, … -
Django Admin View, Narrow querset of Foriegn and Many to many field (30k related objects in queryset)
I have a University Model which currently has 31k objects in the database. University Club or Domain Name object has university as a foreign key and many to many object so it looks all of the objects in the dom which breaks the page. I added a class to optimize the list being return but that didn't really provide the results I wanted. Is there a way to better filter the query maybe add some kind of search instead of dropdown? models: class UniversityClub(models.Model): university = models.ManyToManyField(University) name = models.CharField(max_length=250) address = models.CharField(max_length=250) privacy = models.IntegerField( choices=PRIVACY, default=INVITE) def __str__(self): return self.university.name + ' - ' + self.name class UniversityEmailDomain(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class University(models.Model): name = models.CharField(max_length=250) address = models.CharField(max_length=250) location = models.PointField(srid=4326) views: class MappingDomainNameForm(forms.ModelForm): email_domains = forms.MultipleChoiceField(required=False, choices=UniversityEmailDomain.objects.values_list('id', 'name')) main_campus = forms.ChoiceField(required=False, choices=University.objects.values_list('id', 'name')) class Meta: model = University fields = '__all__' admin.site.register(UniversityEmailDomain) @admin.register(University) class UniversityAdmin(OSMGeoAdmin): list_display = ('name', 'address', 'location') search_fields = ('name',) form = MappingDomainNameForm -
Obj.objects.filter() hangs
on my system for one table Obj.Objects.filter() hangs. Hang means python eats 100% of CPU. virtualenv Python 3.5.2 Django 2.0.9 Ubuntu (probably 16.04, lsb_release does not work for some reason) Mysql: mysql-server-5.7 (5.7.27-0ubuntu0.16.04.1) mysql-connector-python 8.0.13 country-list 0.1.3 . I had a small management command to fill the table initially: def handle(self, *args, **options): if not Country.objects.filter(): for code, name in countries_for_language('en'): Country.objects.create(code=code, name=name) print('%s ' % code, end='', flush=True) which run perfectly for the first time, but not for the second. Trying to eliminate the strange problem with pdb.set_trace() i found that it hangs here: -> if not Country.objects.filter(): (Pdb) s --Call-- > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(176)__get__() -> def __get__(self, instance, cls=None): (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(177)__get__() -> if instance is not None: (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(180)__get__() -> if cls._meta.abstract: (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(185)__get__() -> if cls._meta.swapped: (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(194)__get__() -> return cls._meta.managers_map[self.manager.name] (Pdb) n --Return-- > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(194)__get__() -> -> return cls._meta.managers_map[self.manager.name] (Pdb) n --Call-- > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(81)manager_method() -> def manager_method(self, *args, * *kwargs): (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(82)manager_method() -> return getattr(self.get_queryset(), name)(*args, * *kwargs) (Pdb) n --Return-- > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/manager.py(82)manager_method()-><QuerySet [<C...uncated)...']> -> return getattr(self.get_queryset(), name)(*args, * *kwargs) (Pdb) n --Call-- > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site-packages/django/db/models/query.py(275)__bool__() -> def __bool__(self): (Pdb) n > /home/lenovo/.virtualenvs/cotw/lib/python3.5/site- packages/django/db/models/query.py(276)__bool__() -> self._fetch_all() (Pdb) s --Call-- … -
Trying to set up Django, but receiving error in cmd
I'm in the process of learning about django and the different possibilities that it brings, however I am unable to go through the first few steps that I found in pretty much every tutorial. I successfully installed django-2.2.6, pytz-2019.3 and sqlparse-0.3.0. I then set up the correct directory to my working folder, I used django-admin startproject mysite and finally python manage.py runserver. System check identified no issues (0 silenced). When I try to connect to the local machine on http://127.0.0.1:8000/ it loads up just fine, but then I get this output in cmd and it will not let me do anything else: [26/Oct/2019 23:29:47] "GET / HTTP/1.1" 200 16348 [26/Oct/2019 23:29:47] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [26/Oct/2019 23:29:47] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 Not Found: /favicon.ico ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 50150) Traceback (most recent call last): File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Arivald\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in … -
update throwing TypeError: serializer.update() got an unexpected keyword argument 'data'
I'm trying to update an already db-saved object once it has successfully sent a message. it calls the update() method of the serializer class in order to achieve this. This is the model that will have it's instance updated: class SMSMessages(models.Model): sms_number_to = models.CharField(max_length=14) sms_content = models.CharField(max_length=160) sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent") sent_date = models.DateTimeField(auto_now=True) delivery_status = models.BooleanField(default=False) class Meta: verbose_name_plural = "SMSMessages" def __str__(self): return str(self.sending_user) This is the serializer class I'm using: class SMSMessagesSerializer(serializers.ModelSerializer): """ A class for serializing the SMSMessages model's data. It sub-classes the ModelSerializer class from serializer's module. """ class Meta: model = SMSMessages fields = '__all__' def update(self, instance, validated_data): """ This method is used to update an instance of the SMSMessages's delivery_status attribute. It get's the value for delivery_status from the input parameter, updates the specific instance of the SMSMessagesSerializer, saves that instance and returns it. """ instance = self.get_object() instance.delivery_status = validated_data.get('delivery_status', instance.delivery_status) instance.save() return instance and this is the APIView class that has the POST method that will update the if the message is successfully sent: class SMSView(APIView): """ This class is responsible for all the method operations of an sms. It provides implementations for the GET, POST, and OPTIONS methods. … -
Django template: change id for form in the for loop
I have a Model and a Form as below class Comment(models.Model): post = models.ForeignKey('Post', related_name='comments',on_delete=models.CASCADE,) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, default=uuid.uuid4) class CommentForm(forms.ModelForm): class Meta: model = models.Comment fields = ('text',) widgets = { 'text': forms.TextInput(attrs={ 'id': 'comment-text', 'required': True, 'placeholder': 'Say something...'}), } And in the Django template, I want to use this form several times in a for loop but each iteration I want to change the id of the text in the loop. Currently I am using like below code {% for post in post_queryset %} {% csrf_token %} {% bootstrap_form formComment %} {% endfor %} can someone help me to change the code so that id will change each time in the loop. -
Pagination where search and results are on the same page
I have a template where the users pass a query and select a couple of checkboxes (these can range from 1-100). Then, my view does the following: def search(request): results_list = search(request.GET.get("q", ""), request.GET.getlist("c")) # Pagination paginator = Paginator(results_list, 10) page = request.GET.get("page") results = paginator.get_page(page) return render( request, "web/search/show.html", { "query": query, "results": results, }, ) The issue arrises because both the search and the presentation of the results happen on the same page. Therefore, when I want to include pagination, in my template, I have to do the following: <div class="pagination"> <div class="step-links"> {% if results.has_previous %} <a href="?page={{ results.previous_page_number }}&{{request.GET.urlencode}}" class="prev-page-link">Previous</a> {% endif %} {% if results %} <span class="current"> Page {{ results.number }} of {{ results.paginator.num_pages }} </span> {% endif %} {% if results.has_next %} <a href="?page={{ results.next_page_number }}&{{request.GET.urlencode}}" class="next-page-link">Next</a> {% endif %} </div> </div> Please consider the usage of request.GET.urlencode because when I go to either the previous or next page I have to pass the same query and checkboxes. However, this creates a bug when the user goes past the second page, because the ?page=3&page=2 keep on piling up. Can someone point me in the right direction for solving this issue? -
Loading url content (Django template) into a <div> with jQuery not working
<body> <script>function lol () { $("#content").load("banned_profiles") } </script> <div class="side_bar_links"> <div id="side_bar_links"> <ul> <li><a href="javascript:lol();" id="banned_profiles">Banned Profiles</a></li> </ul> </div> </div> <div id="content" class="content"> </div></body> The above snippet is self-explanatory. I am trying to load content - basically another Django template inside a , using the load() function . It doesn't work . I assume load("banned_profiles") makes a call to the URL as if it would be written on href="banned_profiles" value. (Which works but redirects and refreshes the whole page). banned_profiles view is constructed in the Django backend and can be normally called . I have also tried load('http://localhost:8000/admin/banned_profiles') - doesn't work. I have tried many other options, like to extend the template, which then works, however, it doesn't load only when the link is pressed, but loads concurrently with the entire page and doesn't display within the given . I know this has been asked a thousand times, but I have search pretty much everything on google and still no success. Any ideas? Many Thanks. -
Next request does not contain COOKIE with sessionid value with Django Session middleware
I am not sure why I dont see the cookie value of sessionid in my next request after creating a new session. This is the SECOND call from my frontend: fetch('http://127.0.0.1:8000/game', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({'name': player.name, 'email': player.email}) }) In my first call to my view I created a session and responded with some data and a 200. I can see the session be created in my Session table in my DB. @csrf_exempt @api_view(['GET']) def shuffle(request): if request.method == 'GET': request.session['selected'] = [] request.session['words'] = [] if not request.session.session_key: request.session.create() print(request.session.session_key) response = Response(data={'dice': 1}, status=status.HTTP_200_OK) else: response = Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) return response I can see this session_key in my console and I see it in my developer tools cookie as well. However, on my next request to another view, I do not see anything in my request.COOKIE as well as nothing in my request.session.session_key @csrf_exempt @api_view(['POST']) def game(request): if request.method == 'POST': print(request.session.session_key) # None <--- print(request.COOKIE) # None <--- response = Response(status=status.HTTP_201_CREATED) return response -
Setting Redis password breaks Django Channels Despite providing channels the password
I want to start of by saying I was following this digital ocean guide to setup and secure Redis. After setting the Redis password, it breaks the notification system I had implemented. So I tried using the options setting to provide the password as such: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'OPTIONS': { "PASSWORD": 'pass', }, 'CONFIG': { 'hosts': [('localhost', 6379)], } } } Despite this, it is erroring: Exception Value: NOAUTH Authentication required. Traceback: Environment: Request Method: POST Django Version: 2.1.7 Python Version: 3.6.8 File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/user/project/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/project/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/user/project/project-name/textcorrect/decorators.py" in wrapper 38. return func(self, *args, **kwargs) File "/home/user/project/project-name/journal/views.py" in correction 196. return catch_correction(request, pk) File "/home/user/project/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/user/project/project-name/textcorrect/decorators.py" in wrapper 38. return func(self, *args, **kwargs) File "/home/user/project/project-name/journal/views.py" in catch_correction 229. create_notification({'creator': request.user, 'receiver': Post.objects.get(id=pk).user_id, 'type_id': 1, 'post_id': pk}) File "/home/user/project/project-name/notifications/views.py" in create_notification 21. send_count(data.get('receiver')) File "/home/user/project/project-name/notifications/views.py" in send_count 31. {"type": "receive", "text": n_count, "notification": notification.first().notification_text}, File "/home/user/project/env/lib/python3.6/site-packages/asgiref/sync.py" in __call__ 79. return call_result.result() File "/usr/lib/python3.6/concurrent/futures/_base.py" in result 425. return … -
Understanding inheritance in Django
I am trying to understand some basics in django inheritance - I'm sure it is something trivial, buy I just can't get it. I've got my CartItemForm(forms.ModelForm) and I override init method to get user from post.request, like that: def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) And it works, but I don't really get why it doesn't work when I inherit init method first: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.request = kwargs.pop('request', None) init() got an unexpected keyword argument 'request' What am I missing here? -
Trouble Serializing a many-to-many field
Before this gets marked as a duplicate, I've looked at the following questions: Django Rest framework Serialize many to many field Django rest framework serializing many to many field No results are being shown for payins when I test. serializers.py class PayinsSerializer(serializers.ModelSerializer): class Meta: model = Payins fields = '__all__' class UserStokvelSerializer(serializers.ModelSerializer): payins = PayinsSerializer(many=True) class Meta: model = Stokvel fields = '__all__' models.py class Payins(models.Model): payin_date = models.DateField(default=timezone.now) payin_by = models.ForeignKey(User, on_delete=models.CASCADE) stokvel_payin = models.ForeignKey('Stokvel', on_delete=models.CASCADE, related_name="payin_user") payin_amount = models.IntegerField() def save(self, *args, **kwargs): stokvel = Stokvel.objects.get(id = self.stokvel_payin.id) stokvel.balance += self.payin_amount stokvel.save() super(Payins, self).save(*args, **kwargs) class Stokvel(models.Model): stokvel_name = models.CharField(max_length=55) balance = models.IntegerField(default = 0) payouts = models.ManyToManyField(Payouts, related_name="stokvel_payouts") payins = models.ManyToManyField(Payins, related_name="stokvel_payins") group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stokvel_group_admin") users = models.ManyToManyField(User, related_name="stokvel_users") invite_key = models.CharField(default = secrets.token_hex(15), max_length=55) -
Searching in django, query
Hei, I want to create an app where an user can search ingredients by their names, but when i search for ingredient and put enter then I get blank side without any information what is wrong. My models: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name my views: from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q |= (Q(ingredient_name=queries)) results = Ingredient.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context)