Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Algolia ranking edge cases
I am new to Algolia and Django so any help with the following task would be much appreciated. I am trying to re-rank the search results on the UI such that certain edge cases don't cause issues anymore. The problem was that initially there was only one searchable attribute that was used but we actually want that one to be split into 2. I did that so I split the initial attribute into 2 attributes, call them attribute_1 and attribute_2 and also passed them in the settings of the index.py file as follows: "searchableAttributes": [ "attribute_1", "attribute_2" ] From the documentation I understand that the order in which the attributes are added in the above lists prioritizes the search so the search engine will first look for matches in attribute_1 and then in attribute_2. This solved the issue for one of the edge cases but there is still one edge case that is not solved. I will explain the issue with this edge case below in more detail. Call the 2 examples that I want to be ranked for the remaining edge case E1 and E2. The search keyword, call it some_text, matches perfectly attribute_1 of E1 but it is … -
Perform action on saving inline django model
I have two models, one CommentModel displayed as an inline to the MainModel in the admin. models.py: class MainModel(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) class CommentModel(models.Model): main = models.ForeignKey(MainModel, on_delete=models.CASCADE, default=None) comment_german = CharField(blank=True, default='', null=True) comment_english = CharField(blank=True, default='', null=True) admin.py: class MainModelAdmin(SimpleHistoryAdmin): model = MainModel inlines = [CommentModelInline] class CommentModelInline(admin.StackedInline): model = CommentModel fields = ['comment_german', 'comment_english'] Suppose I want to automatically translate what the user writes in the comment_german field and save it to the comment_english field when the MainModel is saved. I tried overriding the save method. I successfully did it for another model which is not an inline. But this does not work for inlines. I need something like this: def save(self, *args, **kwargs): super().save(*args, **kwargs) for comment in CommentModel.objects.filter(main=self): if comment.comment_german != '' and comment.comment_english == '': comment.comment_english = comment.comment_german.translate_to_english() There must be a way to do this, maybe with a formset, but I can't wrap my head around it. -
Django Clear Sessions and Flags every 20 mins
I am working on a Django Website in which whenever a user logs in it creates a session and in Models active is set to true (is_active=true) when users logout the sessions clear and is_active=false for the user But the problem is when a User closes the tab/ browser instead of logging out user is still said to be active . How to make a function which will logout all active users after 15 mins of their login? Models.py class Employee(models.Model): emp_id = models.CharField(primary_key=True,max_length=50) name = models.CharField(max_length=50) gender = models.CharField(max_length=50,default="None") email = models.EmailField(max_length=50) password = models.CharField(max_length=50,help_text="Minimum of 8 Characters") dept = models.CharField(max_length=50) phone = models.CharField(max_length=20) last_login=models.DateTimeField(auto_now_add=True, blank=True) is_active=models.BooleanField(default=False) authcode=models.CharField(max_length=25) Views.py def home(request): loginUser= request.session['username'] if loginUser == '': return redirect('log') name= request.session['name'] return render(request,'home.html') def logot(request): loginUser=request.session['username'] Employee.objects.filter(emp_id=loginUser).update(is_active=False) request.session['name']=''; request.session['username']=''; return redirect('welcome') # def scheduled_logout # Logout all user's after 15 mins of last_login Thanks in advance -
Django migration : deleted column, now django says it doesn't exist
I want to get rid of a field of one of my models which has quite a few objects. This field was barely used so I removed every call to it from my code and did the migration. This migration couldn't be simpler, and it didn't cause any issue on my dev server. So I did the same on my running server. # Generated by Django 2.2.19 on 2021-06-22 12:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('my_app', '0010_auto_20210611_0751'), ] operations = [ migrations.RemoveField( model_name='permission', name='type', ), ] But when I try to access objects that relate to this model in my admin view, it throws psycopg2.errors.UndefinedColumn: column my_app_permission.type does not exist LINE 1: SELECT "my_app_permission"."id", "my_app_permission"... I don't understand why it looks for type when there is no reference to it in my code. I ran Django's manage.py shell and requested my Permission objects. I got them without any issue. I tried to access their type field, but it didn't exist as expected since the migration. Which means in the database the column "type" has been deleted as I asked. The error message doesn't give any insight as to what causes my error, it says the error … -
I cannot view my sqlite images in Django(uploaded to server-Plesk)
I made a site in Django and when i try to view the pages from the database i get the alt and not the image. File Structure Project -.venv -main -static (again here, only then does it seem to show static files) *settings.py *urls.py *wsgi.py ... -app ... *views.py *models.py *admin.py *apps.py ... -templates ... *offers.html ... -static -static stuff are in here, not important -staticfiles -static stuff are in here, not important -media -offers *VSy6kJDNq2pSXsCzb6cvYF.jpg *db.sqlite3 *passenger_wsgi.py *passenger_wsgi.pyc Settings.py MEDIA_URL= '/media/' MEDIA_ROOT= os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] urls.py urlpatterns = [ path('', homepage), path('servises', servisespage), path('offers', offerpage), path('products', productspage), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # Adding MEDIA_URL and root does not work either views.py def offerpage(request): ids = Offer.objects.values_list('id', flat=True) obj_list = [] for id in ids: obj = Offer.objects.get(id=id) obj_list.append(obj) context = { "objects": obj_list } return render(request, "offers.html", context) offers.html <main> {% for obj in objects %} <div class="offer"> <h1 id="name">{{obj.name|title}} </h1> <img id="photo" src= '{{ obj.photo.url }}' alt="this is the image" width="500"> <h3 id="price">Τιμη: <span id="price-color">{{obj.price}} €</span></h3> <h3 id="summary"> {{obj.description}} </h3> </div> {% endfor %} </main> When i try to inspect the site on firefox, in the … -
JavaFX Websocket with python server(Django)
So I have a project already running on a Django server In the server I have used channel implement the socket server and I was creating a desktop application(in JavaFX) and I'm kinda stuck on how to implement WebSocket in JavaFX which will later establish a full-duplex with the Django server. Is there a way to accomplish this, some tutorial I can go through? Thanks in advance -
Ionic& Angular: Ran into status 0 Unknown Error, what can I do when I cannot reproduce the same error?
I have helped to develop a hybrid check-in mobile app using Angular & Ionic. One of the clients informed that the following error occurs. Http failure response for https://url.com/api/: 0 Unknown Error. But it seems I cannot reproduce the same error, as it happens randomly after some days. I have gone and added a retry feature to my subscription, as well as being able to send me an email if the error happens again; since I have to know what is causing the issue. The snippet code is below, but the same issue is happening on different endpoints: this.sharedService.uploadImageToVisionAPI(image.dataUrl) .pipe(retryWhen(error => { return error.pipe( // we use mergeMap instead of switchMap to have all request finished before they are cancelled mergeMap((error, i) => { const retryAttempt = i + 1; // if maximum number of retries have been met // or response is a status code we don't wish to retry, throw error const scalingDuration = 500; if (retryAttempt > 9) { return throwError(error); } console.log( `Attempt ${retryAttempt}: retrying in ${retryAttempt * scalingDuration}ms` ); return timer(retryAttempt * scalingDuration); }), finalize(() => console.log('We are done!')) )})) .subscribe(confidence_percentage => { let confidence = confidence_percentage['percentage'] }) Have you ran into a similar error, … -
How to use django-select2 widgets in django admin site?
In my django app I have modified the User entity to include a worker field (OneToOneField). But from the django admin site that field yiels so many result , so it is difficult for the logged user to select a worker. Is there any way to use the select2 (ModelSelect2Widget) widgets from the django admin site? For any regular form I have define the widgets in the following way: from django_select2.forms import ModelSelect2Widget class ProcessForm(forms.ModelForm): class Meta: model = ProcessModel exclude = ('id',) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'code':forms.TextInput(attrs={'class': 'form-control'}), 'description':forms.Textarea(attrs={'class': 'form-control'}), 'geom': LeafletWidget(), 'product': ModelSelect2Widget(model=ProductModel, queryset=ProductModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), } Is there any way to use the ModelSelect2Widget for the worker field in the admin site form? Here is my code: class User(AbstractUser): worker = models.OneToOneField(WorkerModel, on_delete=models.CASCADE, related_name="user", verbose_name=_("Trabajador"), null=True, blank=True) class Meta: default_permissions = () verbose_name="Usuario" verbose_name_plural="Usuarios" permissions = ( ("secretario", "Secretario(a)"), ("director", "Director"), ) from django.contrib.auth.admin import UserAdmin class UserAdminInherited(UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Worker info'), {'fields': ('worker',)}), (_('Permissions'), { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'), }), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) admin.site.register(User, UserAdminInherited) -
not found(deploying via digitaloccean, nginx, ubuntu, Gunicorn )
I tried to deploy Django via digitaloccean, nginx, ubuntu, and Gunicorn. I followed the tutorial that digitaloccean provided. Everything was fine before the step of binding it with Gunicorn. I was able to use the run "manage.py runserver 0.0.0.0:8000"and was able to see the website on port 8000 of the IP address; however when I tried to run gunicorn --bind 0.0.0.0:8000 myproject.wsgioutput,and tried to connect to the IP address again, the 404 not found error occurred.output I also tried every port of the IP address but none of them worked. This is the output of systemctl status gunicorn.service output. And this is the output of sudo journalctl -u gunicornoutput. I have the following questions: What might possibly cause this error? Does being able to run it on local server means that the error is not caused by the source code? What can I try to fix this issue? Thank you !!! -
How to use a drop-down per column search form for django-tables 2?
Imagine you have the following table: views.py: class ActionView(SingleTableView, FormView, SingleTableMixin, FilterView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = SnippetFilter(self.request.GET, queryset = self.get_queryset()) queryset = kwargs.pop('object_list', None) if queryset is None: self.object_list = self.model.objects.all() context['actions'] = Action.objects.all() return context filters.py: class SnippetFilter(django_filters.FilterSet): class Meta: model = Action fields = ('name', 'description', 'control' ) action.html: <div class="row row-card-no-pd"> {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} <button type = "submit" class ="btn btn-primary">Search</button> </form> {% endif %} <div class="col-md-12"> <div class="card"> <div class="card-header"> <div class="card-head-row card-tools-still-right"> <h4 class="card-title">Overview of all actions</h4> <div class="card-tools"> <button aria-pressed="true" class="btn btn-primary btn-lg active" data-target="#addRowModal" data-toggle="modal"> <i class="fa fa-plus"></i> Add Action </button> </div> </div> <p class="card-category">Please find below an overview of all the current actions</p> </div> <div class="card-body"> {% for action in filter.qs %} {% load django_tables2 %} {% render_table table %} {% endfor %} </div> </div> </div> </div> Which renders the following: How can you get drop down filter option inside the table per column? For example, when clicking on a column you can type the inside the form to filter I'm running into some trouble there because there is no documentation at hand for django-tables-2.. Please help! -
Twitter-Bootstrap 5 carousel indicators and controls not working. Why?
I am making a ecommerce website with Django framework. I cannot make my bootstrap carousel work. Clicking on indicators and controls has no effect. I have pulled in Bootstrap source files with NPM. main.html <!DOCTYPE html> {% load static %} <html lang="fr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/main.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <title> {% block title %} {% endblock title %} </title> </head> <body class="mt-sm-5 mt-md-5 mt-lg-5 mt-xl-5"> <header> <div class="container border-bottom border-primary border-1"> </div> </header> <section class="page-content" id="page-content"> {% block content %} {% endblock content %} </section> <script src="{% static 'js/bootstrap.js' %}"></script> </body> </html> product_details.html {% extends 'main.html' %} {% load static %} {% block title %} Boutique - {{ product.title }} {% endblock title %} {% block content %} <div class="container"> <div class="row" > <div id="product-carousel" class="col-sm-12 col-md-6 border border-danger carousel slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> {% if product.image2 %} <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="1" aria-label="Slide 2"></button> {% endif %} {% if product.image3 %} <button type="button" data-bs-target="#product-carousel" data-bs-slide-to="2" aria-label="Slide 3"></button> {% endif %} </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ product.image.url }}" class="img-fluid" alt="..."> </div> {% if product.image2 %} <div … -
How to create related objects from JSON in DRF?
I have JSON like: [ { "groupId": 123, "groupName": "Group 1", "monthName": "May", "monthNumber": 5, "year": 2021, "usersDutyList": [ { "userName": "Test1", "userFullname": "Test1 User", "userId": 553, "userEmail": "asd@asd.com", "isOnDutyThisMonth": true, "userPhone": "+1 234 5678", "userExt": "123", "isOwner": "false" }, ... ] } ] And I wrote the models: class Group(Model): groupId = SmallIntegerField(primary_key=True) groupName = CharField(max_length=100) monthName = CharField(max_length=8, choices=MONTH_NAME_CHOICES) monthNumber = SmallIntegerField(choices=MONTH_NUMBER_CHOICES) year = SmallIntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) class User(Model): userName = CharField(max_length=20, unique=True) userFullname = CharField(max_length=40) userId = SmallIntegerField(primary_key=True) userEmail = EmailField(unique=True, verbose_name='Email') userPhone = CharField(max_length=15) userExt = CharField(max_length=10) isOwner = BooleanField() group = ForeignKey(Group, on_delete=CASCADE, related_name='usersDutyList') I need to create a Group object and its associated User objects from the "usersDutyList" key. Now I have this serializers: class UserSerializer(HyperlinkedModelSerializer): class Meta: model = User fields = '__all__' class GroupSerializer(HyperlinkedModelSerializer): usersDutyList = UserSerializer(many=True, required=False) def create(self, validated_data): users = validated_data.pop('usersDutyList') group = Group.objects.create(**validated_data) for user in users: user_dict = dict(user) User.objects.create(group=group.groupId, **user_dict) return group But since no Group object is passed to UserSerializer I receive [ { "usersDutyList": [ { "group": [ "Required field." ] } ] }, ... ] Can't find any information about related objects creation in DRF. Can you help implement this functionality? -
open source project with graphql django
I am learning graphql django and to learn better I have to see the real source of the real project with Django and graphql on github, but I can not find any. Can anyone help me find an open source project with graphql django -
ProgrammingError after reverting migration after AttributeError
I did the migration after adding SourceBook and SourceBooksOrderable and that worked. Then I managed to add two snippets in wagtail admin. But when I tried to add them into the BlogPage in admin, I got an AttributeError. Thinking that it was somehow a problem with the migration, I reverted migrations using python manage.py migrate blog 0001. Now I get a ProgrammingError under the snippet in admin. Tracebacks, models.py and migration files are below. How can I fix this? blog/models.py from django.db import models from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.core.models import Page, Orderable from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel from wagtail.images.blocks import ImageChooserBlock from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.models import register_snippet from wagtail.snippets.edit_handlers import SnippetChooserPanel richtext_features = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', "ol", "ul", "hr", "link", "document-link", "image", "embed", "code", "blockquote", "superscript", "subscript", "strikethrough", ] class BlogListingPage(Page): """Listing page lists all the Blog pages.""" template = "blog/blog_listing_page.html" subpage_types = ['blog.BlogPage'] custom_title = models.CharField( max_length=255, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context.""" context = … -
Django HttpOnly cookie doesn't protect but user can stop it if a malicious code didn't take an action yet. Am i right?
So in my understanding there are two ways of an XSS attack. Attacker user sends malicious Javascript code to backend and when another user opens it will have access to that users data. It is generally prevented with framework itself but you can also encode the data before sending to the backend and filter them before storing them into database in the backend side. When you open want to access it in the client side you decode it again. Browser extensions. Browser extensions have a all the access of client side. They cannot access HttpOnly cookies. But they can still send requests to backend, post something etc. If you use HttpOnly cookie once a user disables extension it will not have the control anymore. Am i right or is there another way of making an XSS attack? -
How to check the fields that are being update in a partial update DRF
I am developing a expense tracker, what I wanna do is to prevent users from updating the type of transaction what I have done so far is to check it with an if statement, but as it isn't pass into the request it generates an 500 error. My question id how can I preform a validation to check if the field is being pass into the request with out it giving an error when the filed isn't include into the request? -
How to make one column fixed and other is scrollable
Here I have tried to make one column is fixed and other is scrollable. In template "Os name" and "{{ i.os_name }}" I want to make it fixed and all the other should be scrollable I have tried but facing issues I have pasted the css which I have tried please tell me where I am going wrong so i can make it corret. <div> <table class="table accountTable" id="book-table" cellpadding="0" cellspacing="0" style="width: 91%;"> <thead> <tr class="accountBorder"> <th class="osfix">Os Name</th> <th class="">Browser</th> <th>IP Address</th> <th>Location</th> <th>Session Time</th> <th>Activity</th> </tr> </thead> <tbody> {% for i in account %} <tr> <td><div class="osfixName">{{ i.os_name }}</div></td> <td> <div class = "title_elipses accordion">{{ i.browser }}</div> <div class="panel" style="display: none;"><p>{{i.browser}}</p></div> </td> <td> <div>{{ i.ip_address }}</div> </td> <td> <div>{{ i.city }}, {{ i.country }}</div> </td> <td> {% for key,value in some_date.items %} {% if i.id == key %} <!-- here we are displaying the age of the ad --> <span class="dealpagetext">{{ value }}</span><br> {% endif %} {% endfor %} <!-- <div>{{ i.last_loggedin }}</div>--> </td> <td> {% if i.activity == 1 %} <div><a href="/Logoff_p/{{i.id}}">Signout</a></div> {% else %} <div></div> {% endif %} </td> </tr> {% empty %} <tr> <td colspan="7" class="text-center">No History</td> </tr> {% endfor %} </tbody> </table> </div> css … -
Securing Nginx autoindex within the scope of Django project
New to both Django and Nginx. I have a project with most of my views secured by the @login_requred() coroutine. How could I do the same with https://example.com/file-index which returns an Nginx autoindex? -
MariaDB: ALTER TABLE command works on one table, but not the other
I have two tables (Django Models) in a MariaDB database: coredb_vsatservicerate and coredb_simservicerate. MariaDB [servicedbtest]> desc `coredb_simservicerate`; +-----------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(80) | NO | | NULL | | | service_type | int(11) | YES | | NULL | | | category | int(11) | NO | | NULL | | | old | tinyint(1) | NO | | NULL | | | year | smallint(5) unsigned | YES | | NULL | | | reseller | tinyint(1) | YES | | NULL | | | description | longtext | NO | | NULL | | | description_update_ts | datetime(6) | YES | | NULL | | | currency | int(11) | YES | | NULL | | | price | decimal(7,2) | YES | | NULL | | +-----------------------+----------------------+------+-----+---------+----------------+ 11 rows in set (0.001 sec) And MariaDB [servicedbtest]> desc `coredb_vsatservicerate`; +-----------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(80) … -
The boolean field in form is not working in django
I'm using boolean in the form to filter the product. forms.py class BrandForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) brands = Product.objects.filter(category=1).values_list('brand', flat=True) for brand in brands: self.fields[f'{brand}'] = forms.BooleanField(label=f'{brand}', required=False) views.py product = Product.objects.all().order_by("-id") formBrand = BrandForm() return render( request, 'list/processor.html', {'formBrand': formBrand, 'product': product} ) index.html <form id="formBrand" action="{% url 'main:productdata' %}" method="get"> {{ formBrand.as_p }} <input type="submit" value="OK"> </form> What is wrong with the code. When I check the LG brand and hit the OK button. The product is not filtering. -
Django formsets in formsets
I am creating a quiz app. A quiz has one or more questions, each question has one or more images. I've already used django-dynamic-formsets to allow the user to create/delete multiple questions. However, I am struggling to find a method that allows the user to upload images for specific questions, and then for Django to recognise which images 'belong' to each question. Because a question could have multiple images (up to some unknown amount) I cannot just hard code multiple fields in my question model. My current code has a model for questions, and models for 'choices' which has a foreign key to a question model. -
How to Write a blog post with slug & image (django)
** when I clicked the publish button .get this error (image field = This field is required.). not submit the post in my database [1]: https://i.stack.imgur.com/Km5TH.png ** Models: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=300, verbose_name='Put a Title') slug = models.SlugField(max_length=264, unique=True, null=True) blog_content = models.TextField(verbose_name='What is on your mind') blog_image = models.ImageField(upload_to='blog_images', verbose_name='Image', null=True) publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title views: @login_required def createblog(request): form = CreateBlogPost() if request.method == 'POST': form = CreateBlogPost(request.POST, request.FILES) if form.is_valid(): blog_obj = form.save(commit=False) blog_obj.author = request.user title = blog_obj.blog_title print(title) blog_obj.slug = title.replace(" ", "-")+"-"+str(uuid.uuid4()) print(blog_obj.slug) blog_obj.save() return HttpResponseRedirect(reverse('index')) return render(request, 'App_Blog/create_blog.html', {'form': form}) -
How can I get distinct values for the area.names using graphene?
my resolver in schema.py looks like this def resolve_areas(self, info, **kwargs): result = [] dupfree = [] user = info.context.user areas = BoxModel.objects.filter(client=user, active=True).values_list('area_string', flat=True) In GraphiQL I am using this query: { areas { edges { node { id name } } } } And get Output that starts like this: { "data": { "areas": { "edges": [ { "node": { "id": "QXJlYTpkZWZ", "name": "default" } }, { "node": { "id": "QXJlYTptZXN", "name": "messe" } }, { "node": { "id": "QXJlYTptZXN", "name": "messe" } }, But i want distinct values on the name variable (Using a MySQL Database so distinct does not work) -
maximum recursion depth is exceeded error while calling a Python object in django while making a post request in Django?
I am trying to list all the doubtclasses model using doubtclass view but there is some recursion error in the post request, which i am not able to understand , i search across for same error and i have tried if i made a similar mistake to the other developers that have asked the same question but as far as i searched mine one is different My doubtclass view class DoubtClass(LoginRequiredMixin, mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = serializers.DoubtClass_serializer queryset = models.DoubtClasses.objects.filter(is_draft=False) def get(self, request): print("error in doubtclass get") return self.list(request) def post(self, request): if request.user.is_superuser: return self.post(request) else: return Response(status=status.HTTP_403_FORBIDDEN) my doubtclass model class DoubtClasses(models.Model): doubtClass_details = models.TextField() class_time = models.DateTimeField() end_time = models.DateTimeField() doubtsAddressed = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) mentor_id = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True) is_draft = models.BooleanField(default=True) class Meta: verbose_name_plural = 'DoubtClasses' def __str__(self): return self.doubtClass_details I am new to stackoverflow and django, so please forgive me if there is poor formatting of question or anything, always open for suggestions. Thanks in advance -
nginx + django + haystack = Server Error (500)
I've cobbled together a small blog application in Django using Haystack with Whoosh backend for search. It runs nicely in development server (on the laptop) but search fails when site runs in nginx on a server (rpi). I can access search page but any search results in Server Error (500), no additional info available from either nginx or django logs. I had RealtimeSignalProcessor on but turned it off - no change. Any pointer on how to attempt to debug this would be great.