Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO REST FRAMEWORK How to log in using username or email
I need to configure the settings.py so that it is possible to log in using username or email #Login con correo ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False #Following is added to enable registration with email instead of username -
Django Cycle Includes Template Tags
I want to cycle the include tags in a django template, but I am unable to nest cycle inside of includes. The cycle should be like I am trying to avoid creating a custom template just to keep it simple. I wanted to see if anyone had any suggestions of how to do this: {% for s in sections %} <section class="{% cycle 'lighter-section' 'cover cover-bg-section' %}"> {% if s.media.values %} {% include 'web_builder/apple-pie/sections/left_align.html' %} {% else %} {% include 'web_builder/apple-pie/sections/center_align.html' %} {% endif %} </section> {% endfor %} -
django redirect view with parameter
I was wondering if something like this is possible in Django. In my App i have the file urls.py that contains these rows: ... path('home/', views.home, name='home'), path('page/', views.page, name='page'), .... and in my view.py file i have two view like this: def home(request, value=0): print("value=", value) return render(request, 'template.html', context) def page(request): if bad: return redirect(reverse('home'), value=1) Is it possible to have the view function with a parameter (like value in this case) and then use redirection from the page view passing some value based on same condition like value=1 in this case using the format described in the urls.py? The code above always prints value=0 no matter what. The only way i can think to do this is to use global variables which i would really like to avoid.. Thank you -
How to render queryset according to radio buttons in Django
I need to render products list view according what user select in radio buttons in template if user select "men" only products with gender='men' appear and so for women products , so how to do that correctly? for that I coded some snippets but it didn't work ever I need help to do that correctly here is my code models.py GENDER_CHOISES=( ('men', "Men"), ('women', "Women"),) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to='products', null=True, blank=False) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) gender = models.CharField(max_length=120,default="" ,choices=GENDER_CHOISES) timestamp = models.DateTimeField(auto_now_add=True) views.py def ProductListView(request): if request.method=='post': queryset = Product.objects.filter(gender=request.POST.get(['gender'])) else: queryset = Product.objects.all() template_name = "products/list.html" return render(request,template_name,{'object_list':queryset}) list.html {% extends "base.html" %} {% block content %} <form method='post'> <div class="mx-auto mx-0"></div> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary"> <input type="radio" name="gender" autocomplete="off" value='men'> Men </label> <label class="btn btn-secondary"> <input type="radio" name="gender" autocomplete="off" value='women'> Women </label> </div></form> {{object_list.count}} <div class="row"> {% for product in object_list %} <div class="col"> <!-- {{ forloop.counter }} --> {% include 'products/snippets/card.html'%} {% if forloop.counter|divisibleby:3 %} </div></div> <div class="row"><div class="col-12"><hr></div> {% else %} </div> {% endif %} {% endfor %} </div> {% endblock %} Any help Appreciated … -
Can I name a model using a field from another model in django admin?
Such as... class firstModel(models.Model) name = models.CharField() def __str__(self): return self.name class secondModel(models.Model) paragraph = models.TextField() def __str__(firstModel): return firstModel.name Basically I have two model forms both of which the user fills in - user fills in firstModelForm on page 1, then page 2 is secondModelForm. In django admin I want secondModel to display the name that was inputted in firstModel, instead of secondModel object(1). I know the above code isn't how you achieve that, but I thought it illustrates what I'm trying to achieve. Thanks. -
Django - Update an html table every 1 minute
Is it possible to update an HTML table (client side) every minute without refreshing the page in a django project? If yes, please, just let me know what I should look for in order to achieve this result. Please, do not down vote my question due no code. I did not start the project yet. -
Content-length header lost during request (django)
Using clen = os.path.getsize(the_file) response['content-disposition'] = "attachment; filename=%s" % filename response['content-length'] = clen return response Results in a response header with only the content disposition, but not the content-length If I add a non-sense header like response['bla'] = 'some non-sense' it appears perfectly in the response. Is there somewhere else where headers are being overwritten or something. I'm using nginx with uwsgi. -
Django form is not showing
I want to create a simple html login form with django forms, but whenever I run the server the form does not show, only a button. This is what I have in my forms.py file from django import forms class LogForm(forms.Form): email = forms.CharField(label='email') psword = forms.CharField(label='pasword') Then in views.py from django.shortcuts import render from django.http import HttpResponse from blog.forms import LogForm def get_info(request): form = LogForm() return render(request, 'login.html', {'form': form}) And finally in login.html <h1>LOGIN PAGE!</h1> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> And the only thing that shows is this View of the webpage with only the sumbit button Thanks for the help -
How to link two variable DBs together
I am trying to think about the right way of implementing this schema. I have a piece of music with a pre-determined instrumentation. For example, Beethoven wrote a piano trio. The instrumentation is 3 instruments: 1 piano, 1 violin, and 1 cello. class Work_Music(MPTTModel, Work): composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), null=True, blank=True, on_delete=models.PROTECT) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) player_name = models.CharField(max_length=100, null=True, blank=True) Separately, I have have a performance model. On a high level, I think of Performance is an "instance" of a piece of music. One would expect there to be 1 pianist, 1 violist, and 1 cellist to perform. class Performance(Event): work = models.ManyToManyField(Work_Music, verbose_name=_('work'), blank=True) players = models.ManyToManyField(Ensemble, verbose_name=_('players'), blank=True) //Ensemble is just multiple players What is the best way to parallel link the two models? The issue here is instrumentation for each piece may be different. How do I create an admin.py that I can easily select a pianist to link to the piano role. … -
How do I translate Javascript standard error messages in Django?
I've a couple of Django projects using translations and everything works fine except Javascript error messages on forms are not translating. For example, on my Login form, if I simply press enter I will get the JS error message "Please fill in this field" in English, whether I've selected English, French, German or any other language. This is not my JS error message and if I run manage.py makemessages -d djangojs, then this message doesn't show up to translate so I don't think I need to correct through that process. Can anyone advise me how to ensure the user is getting JavaScript error messages in their language. Thanks -
Django Filtering Articles by Categories
I'm building a news web site as a part of a task I was given, homework. I have a "articles.html" template which renders all of my news articles by publish date. I added a for loop in the template to loop over the Category model and display Categories as a list. What I'm trying to do now is to filter my articles by category, so when I click "sports" on the list, my site now displays only sports related articles. I have read so much online, and I just got confused, I'm supposed to do this today but I'm having a rough day and would appreciate some guidance ! Here are my models.py : from django.db import models from datetime import datetime from autoslug import AutoSlugField class Category(models.Model): category_title = models.CharField(max_length=200, default="") def __str__(self): return self.category_title class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_image = models.ImageField('Article Image') article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") img2 = models.ImageField('Article Image 2', default="", blank=True) img3 = models.ImageField('Article Image 3', default="", blank=True) img4 = models.ImageField('Article Image 4', default="", blank=True) … -
How to send an image file on POST request on unit test Django
I have a few logo files that I'm trying to send via a POST request, which in turn then will be sent to an AWS S3 bucket by the view. I already have worked out how to do it on a standalone python script, but I'm trying to implement it with Django's MVC now. def test_post_photo(self): first_file_name = join(abspath(dirname(__file__)), 'logos/color_palette.png') url = reverse( "bige_transactions:merchant-logo-list", kwargs={"merchant_id": self.merchant_1.prefixed_id}, ) with open(first_file_name, 'rb') as data: resp_data = self.post(url, {"image": data}) views.py: class MerchantLogoViewSet(GetPrefixedIDMixin, FiltersMixin, viewsets.ModelViewSet): """GET and POST support for /metchants/<merchant_id>/logo/.""" merchant_lookup_field = "merchant_id" # used by `IsMerchantAdmin` permission permission_classes = permissions.IsPostRequest def post(self, request, *args, **kwargs): print(request.data) urls.py: merchants_router = routers.NestedSimpleRouter(router, r"merchants", lookup="merchant") merchants_router.register( r"members", views.MerchantMemberViewSet, base_name="merchant-members" ) merchants_router.register( r"transactions", views.MerchantTransactionsViewSet, base_name="merchant-transactions", ) merchants_router.register( r"logo", views.MerchantLogoViewSet, base_name="merchant-logo", ) models.py: class MerchantFile(BigeModel): """Store Merchant files.""" file = models.FileField() merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE) title = models.CharField(max_length=50) type = models.CharField(max_length=20) I am getting TypeError: Object of type 'BufferedReader' is not JSON serializable with the current test. I just need to able to send the image file in a POST request to the the view and be able to access the file from the view. -
Use instance in django form widget.[input field value]
forms.py class Update_Movies_form(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Avenger','maxlength':50,'value':this.name})) country = forms.ModelChoiceField(queryset=Country_list.objects.all()) story_line = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Description'})) cost = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': '$','maxlength':11})) release_date=forms.DateField(widget=forms.DateInput(attrs={'placeholder': 'Release date (yyyy-mm-dd)'})) imdb_rating = forms.FloatField(widget=forms.NumberInput(attrs={'placeholder': 'IMDB rating','maxlength':11})) imdb_link = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'IMDB link'})) trailer_link = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Trailer link'})) quality = forms.ModelChoiceField(queryset=Quality_list.objects.all()) movies_type = forms.ModelChoiceField(queryset=Movies_type_list.objects.all()) movies_thumbnail=forms.ImageField(widget=forms.ClearableFileInput(attrs={'placeholder': 'thumbnail'})) urls.py path('movies/<int:movies_id>/update',Movies_update,name='movies-update'), views.py @login_required def Movies_update(request,movies_id): obj=get_object_or_404(Movies_list,movies_id=movies_id) form=Update_Movies_form( data=(request.POST or None), files=(request.FILES or None), # instance=obj ) context={ "form":form, } return render(request,'movies_list/list_create.html',context) I want to create raw html for using django Form for updating movies list but i dont know how to initialize input text field with object details stored in database. -
How to Model Peer to Peer Transactions in Django?
I'm trying to figure out the correct way to model transactions between users in an ecommerce site I'm building. I want the transaction to be available to both users in a dashboard. It seems incorrect to have the transaction, and all its details, saved to both users objects. I think I need to create a separate model for transactions, with a unique id for each transaction. Then, in each user's object I could simply save that transaction id. Would I then simply give each transaction two primary keys, one for the purchaser's user.id and one for the purchasee's user.id? Is this "many to many"? Thanks for any guidance here. -
1 GB max download with uwsgi+nginx
I cannot use X-Accel-redirect because I am generating content on-the-fly, I tried: proxy_max_temp_file_size 1000000M; client_max_body_size 4G; proxy_request_buffering off; fastcgi_max_temp_file_size 1000000M; in nginx.conf but still my downloads served by a Django view are capped at exactly 1024 MB. Does anybody know how to disable this NGinx/uwsgi limit? Using the Django built-in webserver serves the large files (>1 GB) just fine so it is an Nginx/Uwsgi thing... -
How can i filter the relationship between parents and child?
Here is my code: \\models class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField("Middle Initial",max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(max_length=500,null=True,blank=True) class ChildProfile(models.Model): Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) Parent_Users = models.ForeignKey(ParentsProfile, related_name='+', on_delete=models.CASCADE,null=True,blank=True,) \\and this is my view def Parents_login_form(request): students = StudentProfile.objects.all() return render(request, 'Homepage/parentsprofile.html', {"students": students}) How do I filter the relationship between parents and their children? And how to display it in html? Please help me.... -
What are the potential side effects of overwriting __eq__ and __hash__ in the Django framework?
I am working with collections of instances of a model defined in my Django application and it would be advantageous if I could use the set class to process these collections. In order for set to compare these model instances correctly, I need to override the __eq__ and __hash__ methods in these models so they no longer use the built in model Ids. For example, if I had a "widget" model with "expiry" and "quantity" fields, I need model instances to be considered equal in sets when they have the same "expiry" and "quantity" even if they have different ids. I've overridden these methods to compare model instances based on a subset of their fields. I am no longer using the model pks/ids to check for equivalence: class Widget(model): expiry = models.DateField(null=True, blank=True) quantity = models.CharField(max_length=255, blank=True) ... def __eq__(self, other): if not isinstance(other, Widget): return False else: return ( self.expiry == other.expiry and self.quantity == other.quantity) def __hash__(self): widget_hash = hash( hash(self.expiry) ^ hash(self.quantity)) return widget_hash ... My code using the set class to process the collections is working as needed, however I am concerned as to what side effects these changes may have in the Django framework. Does … -
Django groupby itemgetter not grouping correctly
I am working on QuerySet which has user id's and some fields related to user. The queryset looks like: a_query = <QuerySet [{'id': 1, 'user_id': 10, 'name': 'xyz'}, {'id': 2, 'marketing_person_id': 10, 'name': 'abc'},{'id': 3, 'marketing_person_id': 12, 'name': 'pqr'}]> key = itemgetter('user_id') iter = groupby(a_query, key=key) But I am not getting the desired outputs after applying this loop data = [] for user_id, user_list in iter: ... user_data = [] for account in user_list: ... user_data.append(...) data.append(user_id, user_data) And the result I am getting is, [(10, ['xyz', 1]),(10, ['abc', 2]),(12, ['pqr', 1])] instead of, [(10, [['xyz', 1], ['abc', 2]), (12, ['pqr', 1])] -
Changing the queryKey argument in bootstrap autocomplete
I am using bootstrap autocomplete to fetch data from django-tastypie. The problem that I am facing is that bootstrap autocomplete uses a parameter q, while tastypie has all the regular django options. I could like to change q to name__contains so that the ajax query can work with the api exported with tastipie. How can I do it? I am not able to find a way to achieve this. -
How to convert below query to ORM equivalent
Below query How DO I convert into Django ORM equivalent. select channel, country, sum(impressions) as impressions, sum(clicks) as clicks from sampledataset where date <= '2017-06-01' group by channel, country order by clicks desc; -
Django Admin intercept onchange event of a field and make an action
In my django project i would clear a field value every time another select field have an onChange event. I have an add form like thisone: every time Template field change (onChange), Test Case field have to become blank. How can i do this in a django admin add or edit page? So many thanks in advance -
How to add the current user to a many-to-many field when creating via a viewset?
I have a Django project which has "workspaces", and users can belong to multiple workspaces, so there's a many-to-many relationship between the users and the workspaces. Now, everything else works fine so far, but I'm having trouble adding the current user to the workspace's list of users when the user creates that workspace. The model looks like this: class Workspace(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='workspaces') The serializer looks like this: class WorkspaceSerializer(serializers.ModelSerializer): class Meta: model = Workspace fields = ('name', 'users') And finally, the view: class WorkspaceViewSet(viewsets.ModelViewSet): queryset = Workspace.objects.all().order_by('name') serializer_class = WorkspaceSerializer permission_classes = [permissions.IsAuthenticated,] So, to elaborate, when a user creates a new workspace, I'd like the workspace's users field to refer to that user. Currently, that field remains empty. How would I populate the field so that the current user is added there right on creation? -
Modify <item><description> element from Feedparser
I'm using feedparser to handle an RSS fed from pubmed. The feed link is https://eutils.ncbi.nlm.nih.gov/entrez/eutils/erss.cgi?rss_guid=1RGmO3jHeXUu8o2CWPinET6JLLik93hwR2IAJ5mU-YzoPeX1-O The 'Abstract' for each article in the feed is buried within HTML in the <(description)> element, and it's the abstract that I want to display in a webpage (using Django). All of the other elements are easily accessible to me. I played around and wrote some code below to strip away anything that isn't in the abstract from and print it, but even using solutions found on Stackoverflow I can't substitute the 'abstract' variable back into the original feedparser dictionary. What exists: <(item)> <(description)> loads of HTML What I want: <(item)> <(description)> abstract or: <(item)> <(description)> <(abstract)> abstract Hope that makes sense. the code is: import feedparser rss = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/erss.cgi?rss_guid=1RGmO3jHeXUu8o2CWPinET6JLLik93hwR2IAJ5mU-YzoPeX1-O' feed = feedparser.parse(rss) for post in feed.entries: try: abstract = (post.description[post.description.index("<p>Abstract<br/>")+len("<p>Abstract<br/>"):post.description.index("</p><p>PMID:")])[:-14] print (abstract) except ValueError: break FWIW, here's the code for the front end: {% for post in feed.entries %} <div class="panel panel-default"> <div class="panel-heading"> <h4><a href="{{ post.link }}" target="_blank"> {{ post.title }} </a></h4> <h5> {{ post.description }} </h5> <h5> {{ post.author }}, {{ post.category }} </h5> </div> </div> {% endfor %} Thanks a million for any tips! -
Case insensitive URLS causes admin page error
In my Django site, I just made my urls case insensitive using re_path(r'^(?I)urlName', views.viewName) But this caused an error when attempting to access my admin page, ValueError at /admin/ Non-reversible reg-exp portion: '(?i' I have tried adding my admin page to my apps urls, my project urls, having admin not use re_patha and having an admin url in both the project and app urls.py in project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), path('', include('interface.urls')), ] in app urls.py: from django.urls import path, re_path from . import views urlpatterns = [ path('', views.indexView), re_path(r'^(?i)edit/', views.editView), re_path(r'^(?i)add/', views.addView), re_path(r'^(?i)delete/', views.deleteView), re_path(r'^(?i)postEditColumnData/', views.postEditTableData), re_path(r'^(?i)updateTableEdit/', views.postUpdateEdit), re_path(r'^(?i)postAdd/', views.postAdd), re_path(r'^(?i)postUploadFile/', views.postUploadFile), re_path(r'^(?i)postDelete/', views.postDelete), re_path(r'^(?i)postDelete/', views.postDelete), re_path(r'^(?i)postUploadDeleteFile/', views.postUploadDeleteFile), re_path(r'^(?i)uploadEditFile/', views.uploadEditFile), re_path(r'^(?i)denied/', views.authDenied), ] How would I make this error go away, and is there a way to make the admin url case insensitive along with the other urls? -
Django view dramatically slower when called via HTTP request than when called via Django shell
I have a view that retrieves a class instance and runs a method on it: def run_loader(request, loader_id): try: pl = Loader.objects.get(pk=loader_id) pl.run() return JsonResponse({ 'success': True}, safe=False) except Exception as e: print(e) return JsonResponse( 'error', safe=False ) When this view is run via an HTTP request to the associated path, processing is approximately 300 times slower than when run via the Django shell using RequestFactory. I have tried hitting the path using both Axios and Postman, with the same result. The method, run(), involves processing many rows of Pandas dataframes. When the view is run via the Django shell, it takes a few minutes to complete. Eventually I'll move this to an asynchronous task worker, but I'm baffled by the speed disparity. What could be the cause?