Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handle select multiple on django
I have this on template <select name="document" id="document" multiple=""> <option value="2">test 1</option> <option value="3">test 2</option> </select> When I select two options when I accept the request in views.py I got correctly 2 options selected self.request.POST // It prints 'document': ['2', '3'] But when I try to select the field like this self.request.POST['document'] // It prints only '3' How can I select 2 options? Thanks -
How to restrict a Django model to a single one-to-one relation?
I am currently building a Django app that requires two different user types and I know that storing authentication information across multiple models/tables is a bad idea. As such, I have created a User model to handle the authentication information (username, password, etc.). I have then created two different models, one for the buyers and one for the sellers, each with their own unique fields and one-to-one relationship to the User model. Now, I thought this would work, but the problem is that it is still possible for a different buyer and seller to have the same User relation. How can I prevent this and restrict the User model to only a single one-to-one relation? -
Django Pass more complex python types into template
I'm creating a Car Shop web application using Django. Here is my index view: def index(request): cars = Car.objects.filter(brand=request.user.preferred_brand) return TemplateResponse(request, "main/home.html", {"cars": cars}) This shows the list of all cars which currently authenticated user has set a preferrence for. In my database, I also have the following model: class Interest(models.Model): repair_company_name = models.CharField(max_length=200) car_id = models.IntegerField() Each car has a set of companies that are willing to provide repair support for specific car. I would like to show this information on user's home page as well - so that he will not only see the list of his preferred cars, but each car will have information about repair companies next to it too. Here comes my problem - how to pass such a complex type into django template, as I'm not able to do there complex operations like indexing or so. I could imagine creating something like dictionaries containing these information groupped (so that each dictionary would contain everything about car and also the list of strings of names of all repair companies that belong to it). But how to access such a dictionary and its values from template? Is there any better way to do this? -
In django How do I insert ckeditor value inside CKEditorUploadingWidget and display it in templates?
What should I do in order to insert html content inside ckeditor uploading widget? I already have html content in my database field, and I am trying to create UpdateView page and inside ckeditor I want to insert html content. I am using CKEditorUploadingWidget in forms but I don't know how to insert html content django-ckeditor==6.1.0 Django==3.2.6 python 3.9 my code (forms) my html template my template code my UpdateView -
How to optimize Default Django oscars App Views Especially the catalogue App Views?
I am using Django oscar(2.1.1), and I want do to query optimization on Django Oscars default Apps Views specially the catalogue view for class ProductDetailView(DetailView). and class ProductCategoryView(TemplateView). and in App 'Offer' class RangeDetailView(CoreRangeDetailView):. I know that using select_related() and prefetch_related() I can optimize the views but what I am not understanding is which specific function I will have to override in order to optimize these views Especially for the Product Table. I dug into Django Oscars catalog App and found major roles and queries are being done by managers.py so I tried to override it like this but which method do I need to overwrite here any examples? what I tried is overriding this method: def base_queryset(self): """ Applies select_related and prefetch_related for commonly related models to save on queries """ Option = get_model('catalogue', 'Option') product_class_options = Option.objects.filter(productclass=OuterRef('product_class')) product_options = Option.objects.filter(product=OuterRef('pk')) return self.select_related('product_class', 'mtg_card')\ .prefetch_related('attributes','categories','children', 'product_options', 'stockrecords', 'images') \ .annotate(has_product_class_options=Exists(product_class_options), has_product_options=Exists(product_options)) def public(self): """ Excludes non-public products """ return self.filter(is_public=True).select_related('product_class', 'mtg_card')\ .prefetch_related('attributes','categories','children', 'product_options', 'stockrecords', 'images') is that the right way of doing it in a generic manner? and in catalogue/views.py found this class ProductDetailView(CoreProductDetailView): def get(self, request, **kwargs): product = self.get_object() . . def get_object(self, queryset=None): return get_object_or_404(Product.objects.prefetch_related('attributes' , … -
Manipulate strings in Django template
I have following string in my template documents/maca.pdf How can I output only 'maca.pdf' Thanks a lot -
TypeError at /login/user login() takes 1 positional argument but 2 were given
im trying to login using django.contrib.auth it giving me error whenever im trying to login it gives me error below TypeError at /login/user login() takes 1 positional argument but 2 were given this is my login template and url work perfectly from login/user <div class="container border border-2 border-info rounded-2 p-3" style="width: 400px;margin-top: 100px; margin-bottom: 200px;"> <form action="user" method="post"> {% csrf_token %} <h3 class="p-3"> <small class="text-muted">Login To Your Account</small> </h3> <div class="mb-3 form-floating"> <input type="text" class="form-control" id="InputUsername" aria-describedby="emailHelp" name="username" placeholder="Enter Username"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> <label for="InputUsername" >Username</label> </div> <div class="mb-3 form-floating"> <input type="password" class="form-control" id="InputPassword" name="password" placeholder="Enter Password"> <label for="InputPassword" class="form-label">Password</label> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Remember me</label> </div> <button type="submit" class="btn btn-primary">Login</button><a href="/register" class="streched-link p-3">Create Account</a> </form> </div> urls.py look like this from store.settings import MEDIA_ROOT, MEDIA_URL from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name="home"), path('login/',views.login,name="login"), path('register/',views.register,name="register"), path('register/user',views.registeruser,name="registeruser"), path('login/user',views.handlelogin,name="loginuser"), path('/user/logout',views.handlelogout,name="logout") ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py my handle login function def handlelogin(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. return redirect('') else: # Return an 'invalid … -
Django input field
I am making a project in Django which takes an equation having some variables and then perform mathematical function on it using python. Right now, I have CharField as an input field for entering equation but the problem is that it returns string which I can't use for calculation purpose. For eg. The user inputs an equation $x^2 + $y^2. Now I want to substitute value of x and y but the equation is in the form of string and I cannot calculate the value. So, is there any input field in Django which can take equation in a particular form so that I can input value in those variables? -
Iterating over the data received from ajax / json
Below is the type of data I am getting via ajax. [{"model": "blogapp.articles", "pk": 1, "fields": {"title": "Rainbow Buildings in Tokyo", "slug": "Rainbow-Buildings-in-Tokyo"}}, {"model": "blogapp.articles", "pk": 2, "fields": {"title": "4 Cool Cube Facades", "slug": "4-Cool-Cube-Facades"}}] How can I iterate over this data using .each to get the title and the slug for each entry? The below code gives me a syntax error on the data. app.js $(document).ready(function () { $(".tag-nav-links").on("click", function (e) { e.stopPropagation(); return $.ajax({ type: "POST", url: "", dataType: "json", data: { filter: `${e.target.textContent}` }, success: function (data) { var html = ""; $(data).each(function (index, value) { html += "<h4>{{" + value.title + "}}</h4>"; }); $("trial").append(html); }, }); }); }); -
Anti spam in django
Do you have a solution to deal with spam in Python? Should i use a library? I want to use it in "Django". I studied different sources, but I did not reach the desired result. Thanks for help!! -
How to set up optional demo data for a django project
I'm building a django app for making a family tree website, either from scratch or from importing a Gedcom file. In addition to the people/family records that make up the tree, you can add custom html files for stories and family history. First I've been building it out for my own family tree, and next I'm working on improving the setup process, with the goal of making this useful for others. Currently it's public on GitHub: the source code but also the custom files I'm using on my tree. Then my understanding is the 'official' way to make it available when it's ready is to make a package on pypi. I'd like to provide some optional demo files: demo gedcom import for families and people, and demo stories and family history html files. This will give people samples and help them see how it can look once set up. What's the right way to have these demo files available in the code, but optional to include? I've read about github's experimental sparse checkout and setup tools' data files support, but I'm not clear: what's the typical way that people approach this? Is there a standard way to let someone choose … -
Setting dynamic urls for django filter
I have little experience with Django and it's dynamic urls. I used django-filter package to filter items in the database. I'm using Django restframework. In the models.py I have some charfields (owners, item, category...). Using filterset, I want to set a dynamic url. Using the URL path('item**/categories=categoryname**', items-view.as_view(), name='category') I need to specify the category name in the browser search box before I get the items in a named category. That's the way I'm testing it on the browser and by using the category name, I get all the items in that category being returned. I want to use the url in a react application. Will it be a good practice to fetch that API as it is since I'm equating the category to the name of the category to obtain the list of items in that particular category? Or is there a way to set the url dynamically? For instance, when using lookup_field for the product id I can set the url dynamically using path('item/**<int:id>**', items-view.as_view(), name='category') without hard coding the id in the URL. -
Requested setting TEMPLATES, but settings are not configured
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I try to run migrations I got this error. Can someone help me please? -
inpage.js:1 MetaMask no longer injects web3
I am implementing the web3.py with Django and python. But I fail to link with web3.py Here is the error; inpage.js:1 MetaMask no longer injects web3. For details, see: https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3 Uncaught TypeError: Cannot read properties of undefined (reading 'contract') at login.js:192 ncaught ReferenceError: Web3 is not defined at login.js:176 Here is the code:: window.addEventListener('load', () => { if (window.ethereum) { web3 = new Web3(window.ethereum) return true } else if (window.web3) { web3 = window.web3 return true } return false }); -
How to optimize Django oscars Search View?
I am using Django oscar(2.1.1), and I want to optimize Django Oscars default search view i.e class ESProductSearchHandler(CoreESProductSearchHandler). I know that using select_related() and prefetch_related() I can optimize the views but what I am not understanding is which specific function I will have to override in order to optimize the default Django-Oscars search view for Product Table only. I dug into Django Oscars search App and found FacetedSearchView() but which method do I need to overwrite here? I am unable to see any get_queryset() function here then I looked into search_handlers.py in catalog model there i guess I need to override this function def get_search_queryset(self): sqs = super().get_search_queryset() if self.categories: for category in self.categories: sqs = sqs.filter_or(category=category.full_name) return sqs and in facets.py found this def base_sqs(): """ Return the base SearchQuerySet for Haystack searches. """ sqs = SearchQuerySet() for facet in settings.OSCAR_SEARCH_FACETS['fields'].values(): options = facet.get('options', {}) sqs = sqs.facet(facet['field'], **options) for facet in settings.OSCAR_SEARCH_FACETS['queries'].values(): for query in facet['queries']: sqs = sqs.query_facet(facet['field'], query[1]) return sqs what are facets here and how can I make use of it to optimize the search view? Let me know if I am right or not? and if yes how can I optimize it? As you … -
Async functions in Django
I'm trying to use django admin for administrate my Telegram bot. I have an async function called mailing, how can i start this function in django admin actions? I can make it sync but i don't know how make a pause to my bot will be no banned when it send many massages, and continue to answer users. This is my first question on Stackowerflow. Sorry for my english. admins.py @admin.action(description='mailing') def mailing(modeladmin, request, queryset): pass @admin.register(Publish) class PublishAdmin(admin.ModelAdmin): list_display = ('name', 'created_at') actions = [mailing] async def mailing_start(text, url, user_id=None): users = db.select_user_list() count = 0 receivers_count = 0 markup = '' if url: pass #markup = await create_link_button(url) for user in users: try: if user_id != user[0]: if url: await bot.send_message(user[0], text, reply_markup=markup) else: await bot.send_message(user[0], text) count += 1 if count == 18: await asyncio.sleep(3) count = 0 receivers_count += 1 except Exception as err: print(f'id - {user[0]}, bot is stopped \n{err}') receivers_count -= 1 return f'{emoji.emojize(":white_check_mark:", use_aliases=True)}, ' \ f'message recieved {receivers_count}' -
How to restrict an user from saving an instance of a model if he/she has not created an instance of a previous model?
I have five key models: class Patient(models.Model): title=models.ForeignKey(Title, on_delete=CASCADE) name=models.CharField(max_length=100) gender=models.ForeignKey(Gender, on_delete=CASCADE) center=models.ForeignKey(Center, on_delete=CASCADE) mr_uid=models.CharField(max_length=9) class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) class Discharge(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) date_of_discharge=models.DateField(default=None) mould_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) ct_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) discharge_updated=models.BooleanField(default=False) class Realization(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) cash=models.BooleanField(default=False) amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0) billing_month=models.DateField(default=None) deficit_or_surplus_amount=models.DecimalField(max_digits=8, decimal_places=2, blank=True) deficit_percentage=models.FloatField(blank=True, default=0) surplus_percentage=models.FloatField(blank=True, default=0) remarks=models.TextField(max_length=500, default="N/A") A basic summary: A patient consults a doctor. Immediately his treatment package is decided. If the patient has any Government scheme's support, the package goes for approval to the Government agency. Upon the arrival of the approval, the receivables are calculated. The patient then takes the treatment and gets discharged. We then receive the amount. The problem: At the beginning, the patient's profile is created. The rest of the tables will be created as and when the events occur. What I want is, for example, when the data-entry operator fills up the Receivables form and saves it, the Package instance must already be there for the same patient, likewise, when he/she … -
Twitter API "Token request failed with code 401, response was '{\"errors\":[{\"code\":89,\"message\":\"Invalid or expired token.\"}]}'."
Iam working with twitter API and stuck with an error can some one help me with that. I have to pass temporary URL to frontend which help the user to authenticate with our Application. I know its a one time URL. If we hit that temporary URL endpoint for the 1st time, user can authenticate(works fine). But for the next time, its showing error as "Token request failed with code 401". Is there any way to continuously regenerate..enter image description here enter image description here -
Django REST Framework: How to pass a prefetched queryset to the serializer when the View must use a library-provided queryset
I would like to use drf-haystack to use a queryset prefetched by serializer as shown below. I need to use a haystack-specific queryset (annotate and prefetch_related are not available) for this view, and I can't pass the prefetched queryset to the SerializerMethodField. I've spent quite a bit of time on this issue. Is there a better way to do this? # views.py class PostSearchView(ListModelMixin, HaystackGenericAPIView): index_models = [Post] serializer_class = PostSearchSerializer def filter_queryset(self, *args, **kwargs): #This queryset is haystack's own queryset, so it cannot be annotate or prefetch_related. queryset = super(PostSearchView, self).filter_queryset(self.get_queryset()) return queryset.filter(published_at__lte=timezone.now()) def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # serializers.py class PostSearchSerializer(BaseHaystackSerializer): is_views = serializers.SerializerMethodField() class Meta: index_classes = [PostIndex] search_fields = ("text",) fields = ("is_views",) def get_is_views(self, obj): try: History.objects.get(post_id=obj.pk) return True except History.DoesNotExist: return False return obj.is_views # I wanted to do it this way. -
How to get all files from a specific folder and store them in DB, django
class Documents(models.Model): file = models.FileField() I have got a folder called media in the root. It contains multiple files (pdf's). Can I automatically store them in the table called Documents. Thank you so much! -
Why Django copies all images, which I use for creating of the model instances
I have a model 'Book'. It has a field 'image'. Whenever I add a new instance on the admin panel, Django copies this image in a 'media' folder. Why does it do it? Can I turn off this function? -
OperationalError at / no such table: fruits_fruits
OperationalError at / no such table: fruits_fruits Request Method: GET Request URL: http://104.198.201.84/ Django Version: 3.2.8 Exception Type: OperationalError Exception Value: no such table: fruits_fruits Exception Location: /usr/local/lib/python3.7/dist-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /usr/bin/python3 Python Version: 3.7.3 Python Path: ['/var/www/projects/fruitstore', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 30 Oct 2021 08:49:33 +0000 Error during template rendering In template /var/www/projects/fruitstore/fruits/templates/fruits.html, error at line 47 no such table: fruits_fruits -
how do i upload video in django to heroku
please can someone tell me how to implement video upload in django for production? I actually i am working on a project to upload videos . In my model i used: (1). video = models.FileField() (2). video = CloudinaryField(resource_type = "video/%y") but of them didnt work as the project crashed. However, models.FileField() works for development on my local machine but doesnt work when i try to upload on heroku. I will deeply appreciate if anyone can help me solve this problem as i have searched youtube ,internet but still have not found solution to it. -
Render HTML from ajax/json in Django
I am trying to filter blog articles by certain tags via ajax. After days learning ajax and working on this I have come up with below code. I have successfully got the data filtered by tag and now want to display it as html. Ive used .each loop to iterate through the values in app.js, and trying to insert the html into the header id trial in all-articles.html. I am getting a syntax error in the console. The syntax error is on the json? data. Here is the screenshot of the error. Any help is appreciated! Thank you all-articles.html {% for article in page_obj %} <article> <header id="trial> <h4>{{ article.title }}</h4> </header> </article> {% endfor %} app.js $(document).ready(function () { $(".tag-nav-links").on("click", function (e) { e.stopPropagation(); return $.ajax({ type: "POST", url: "", data: { filter: `${e.target.textContent}` }, success: function (json) { var html = ""; $(json).each(function (index, value) { html += "<h4>{{" + value.title + "}}</h4>"; }); $("#trial").append(html); }, }); }); }); views.py @csrf_exempt def allarticles(request): articles_list = Articles.objects.all() paginator = Paginator(articles_list, 12) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) all_tags = Tags.objects.all() if request.is_ajax(): tag_assign = request.POST['filter'] tag = Tags.objects.get(tag=tag_assign) data = serializers.serialize('json', Articles.objects.filter(articletags__tag=tag)) return JsonResponse(data, safe=False) context = {'page_obj': page_obj, … -
What are the differences among django_redis, channels_redis, asgi_redis and redis server?
I am new to Django and right now i'm learning Django async with Channels. I have noticed some programmers use channels_redis for their projects, some use django_redis, some use asgi_redis and i found redis server in google. Is there any difference among those libraries?