Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
View that calls endpoint?
I am using the REST framework package for Django. I am trying to create a way to handle a POST request when a follow button is pressed. So far on the API View side I have this: class FollowToggle(APIView): def post(self, id=None): target = get_object_or_404(User, id=id) follower = self.request.user if follower.is_authenticated(): if follower in target.followers.all(): target.followers.delete(follower) else: target.followers.create(follower) data = { "success": 1 } return Response(data) Now what I'd like to do is using my ProfileView, I'd like to handle POST requests by executing the APIView I created with the specific parameters. How do I do this? class ProfileView(DetailView): model = User slug_field = 'username' template_name = 'accounts/profile.html' if request.method == 'POST': //Call the API with the parameters -
django sendgrid send uniqu arguments
Sendgrid allows to specify unique arguments when sending emails. These can be used for the event webhook integration to identify emails doc. I have an existing code piece in django that uses django.core.mail.EmailMultiAlternatives to send emails via SendGrid. I'd like to specify the above mentioned unique arguments if possible. So far I was trying to use the custom_args field email.custom_args = {'test_arg': 'value'} but that didn't seem to work. I saw that there's a django-sendgrid module, but if possible I'd prefer not having to re-write the existing code base. -
Django- Make python object persist during a session
I have a class which has an FSM. I want store variables and transition through the FSM states based on repeated interaction with the user. So, as per my requirements, I have a object that is not part of the database (not included in models but defined in a custom python file). I want to create an class instance per-user-per-session and have it persist through the session. I thought this could be done via session variables in Django but I read that you can't keep class instances as session variables (may be possible by pickling, but I read in multiple places that its discouraged). It maybe possible using cache system, but I do not know how to go about it. Can someone give me some solid directions on what the best method would be and how to implement it? I have not included any code, because I think the question is more in terms of knowledge than just implementation, but I can provide some example code if required. -
How do I create a user authentication n Django without using path? Specifically Using Cloud9
I'm a beginner to Django and trying to make a website where users can store their contacts in a list. So far I have been successful in adding list items via a form. However, I'm using cloud9 and path can't be imported and I'm trying to find a way around it but I can't. I've seen the documentation and this tutorial and they both use path. -
`TemplateDoesNotExist` error though it does exit
I wrote password reset and change templates structured as In [10]: !tree /Users/me/desktop/Django/forum/user/templates/user /Users/me/desktop/Django/forum/user/templates/user βββ activate.html βββ failure.html βββ logged_out.html βββ login.html βββ password_change_done.html βββ password_change_form.html βββ password_reset_complete.html βββ password_reset_confirm.html βββ password_reset_done.html βββ password_reset_email.html βββ password_reset_form.html βββ password_reset_subject.txt βββ register.html βββ success.html βββ validate.html I throw TemplateDoesNotExist error when I test it in browser http://127.0.0.1:8001/user/password_reset/ TemplateDoesNotExist at /user/password_reset/ /user/password_reset_form.html Request Method: GET Request URL: http://127.0.0.1:8001/user/password_reset/ Django Version: 1.11.13 Exception Type: TemplateDoesNotExist Exception Value: /user/password_reset_form.html all the passwords__ did not perform as intended but others function finely. The urls.py #Costomize the authentication system urlpatterns = [ # show the register page url(r"^register/$", views.register, name="register"), ... url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name="/user/password_reset_form.html"), name='password_reset'), ] What's the problem with my multiple password templates? -
django return .zip file type application/x-zip-compressed
django 2.0.2 python3.4 url.py urlpatterns = [ url(r'^', include(router.urls)), url(r'^do/gz/(?P<id>.*)$', Do.Gz.as_view({"get": 'list'}), name="GroupZip"), url(r'^UploadFiles/Thumb/(?P<id>.*)$', Do.GetImage.as_view({"get": "list"}), name="getimage") ] do.py class Gz(viewsets.ModelViewSet): queryset = "" serializer_class = BaseSerializer def list(self, request, *args, **kwargs): path = os.path.join( settings.MEDIA_ROOT, "Emo", "EmoFiles", "z") zipfiles = zipfile.ZipFile(os.path.join( path, kwargs.get("id") + ".zip") return HttpResponse(zipfiles, content_type='application/x-zip-compressed') class GetImage(viewsets.ModelViewSet): queryset = "" serializer_class = BaseSerializer def list(self, request, *args, **kwargs): path = os.path.join( settings.MEDIA_ROOT, "UploadFiles", "Thumb") try: imgfile = open(os.path.join( path, kwargs.get("id")), "rb").read() except: return HttpResponse(0) images = [] images.append(imgfile) return HttpResponse(images, content_type="image/png") GetImage is work but Gz is not work how to returned zip file zipfile is already to this directory i request GET localhost:11000/do/gz/test -
How enter a correct path?
In the linked picture you can see the path to the css folder ,i tried to open the server . The html code works . But the css doesn't work . I think the problem is in the path . If yes , how to correct it ? I have no idea [<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="description" content="Crypto currency news"> <meta name="keywords" content="bitcoin altcoin> <meta name="unknown" content="industry"> <title>Acme News | About</title> <link rel="stylesheet" href="./css/style.css"> </head> <body>][1] -
Annotate with count yields incorrect values with NullBooleanField
I am performing the following query with a few annotations: (AwardIssueProcess.objects.filter(grant__client=client, completed=completed_status) .annotate(total_awarded=Sum('award__awardissuedactivity__units_awarded'), num_accepted=Count(Case(When(award__accepted=True, then=1))), num_rejected=Count(Case(When(award__accepted=False, then=1))), num_unaccepted=Count(Case(When(award__accepted=None, then=1))))) However, the num_unaccepted yields incorrect values. Firstly, if I have awards the number is sometimes double what I expect. But if I remove total_awarded=Sum('award__awardissuedactivity__units_awarded') from the annotation, then the doubling problem goes away. Secondly, the num_unaccepted has a value of 1 if there are no awards. But when there are awards, the value is correct (but not is all cases due to the doubling problem I mentioned previously). In this second issue, I suspect that this may be because it is evaluating the award to be None, but what I really want is for it to check if the accepted field is None. And then if the award doesn't exists, just don't count it. The accepted field is a NullBooleanField. How should I be writing this differently to solve these two problems with num_unaccepted? -
Reference 'django.contrib.auth.urls' to custom specific templates
I wrote specific templates to deal with password reset and change, the file tree structures as: In [3]: !tree /Users/me/desktop/Django/forum/user/templates /Users/me/desktop/Django/forum/user/templates βββ registration β βββ logged_out.html β βββ login.html β βββ password_change_done.html β βββ password_reset_complete.html β βββ password_reset_confirm.html β βββ password_reset_done.html β βββ password_reset_form.html βββ user βββ activate.html βββ failure.html βββ register.html βββ success.html βββ validate.html The project urls is configured as: # Project url urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^$", views.index, name="index"), url(r'^article/', include('article.urls',namespace='article')), url(r'^user/', include('user.urls',namespace='user')), url(r'^user/', include('django.contrib.auth.urls')), ] Unfortunately, when I try to issue request as http://127.0.0.1:8001/user/password_reset/, the browser redirect to its default admin site I am working on Django 1.11 How reference 'django.contrib.auth.urls' to my own templates? -
Pythonanywhere mysql not working. Can't access my database
I created database in pythonanywhere in mysql. Username is other then root. I need to give permissions to this user. From where I can get root user data in pythonanywhere. My bash console shows error django.db.utils.OperationalError: (1044, "Access denied for user 'ishwarjangid116'@'%' to database 'math'") When I tried connect directly from bash it gives ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) -
Saving Django Form Data
I am learning Django forms and am trying to save form data. I have a working form, but I can't figure out to 'do' anything with the data entered on the form. Specifically, I am trying to do the following two things: First, once the user submits the form, load a new page that states: "You searched for 'X'". Second, have the form data interact with an existing database. Specifically, I have a model called 'Hashtag' that has two attributes: 'search_text' and 'locations'. I think the process would work as follows: Send X to the Model ('Hashtag'), If X is equal to an existing hashtag.search_text object in the database, then return a page with: "The following are the locations for 'X': 'Y' If X doesn't equal an existing hashtag.search_text object in the database, then return a page with: "The following are the locations for 'X': no locations found". Where, X = user-inputted form data Y = hashtag.locations.all() in a list Thus far, I have the below: models.py from django.db import models class Hashtag(models.Model): """ Model representing a specific hashtag search. The model contains two attributes: 1) a search_text (eg 'trump') for which there will be only one for database entry β¦ -
Local PostgreSQL databse in AWS Lambda
Can I connect my local database in AWS Lambda and fetch result from there. If so, What all changes I need to do? I am using PostgreSQL. -
I can't load polls/detail.html
hi guys I can't load polls/detail.html I am currently studying Django tutorials part3 If I enter http: // localhost: 8000 / polls / index.html in the browser address bar, I get a page not found response and The browser shows me the following text Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:question_id>/ [name='detail'] polls/ <int:question_id>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] admin/ The current path, polls/index.html, didn't match any of these I think there's a problem with the route this is my view.py code from django.shortcuts import get_object_or_404, render from .models import Question #... def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) polls/tamplates/polls/detail.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul> -
Django __str__ gives object has no attribute error
So, I'm not sure why this is failing. I have a model Card that has a billing profile. Then I have defined a str function on it. The field it refers to has a foreign key to another model's email field. class Card(models.Model): billing_profile = models.ForeignKey(BillingProfile) stripe_id = models.CharField(max_length=120) def __str__(self): return "{}".format(self.billing_profile__email) class BillingProfile(models.Model): user = models.OneToOneField(User, null=True, blank=True) email = models.EmailField() Whenever I don't comment out the str method, I get 'Card' object has no attribute 'billing_profile__email'. When I do comment it out and look at both of my Card objects, I see that the field for 'billing_profile' is populated. The BillingProfile has a entry for both of as listed int he card object and they each have a valid email. What could be throwing this off? -
No Part matches the given query
I'm begginer in django. I have a problem with error: No Part matches the given query. views.py: from description.models import Part from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render_to_response, get_object_or_404 def PartyNumView(request, pk=None, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 10) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) onePart = get_object_or_404(Part, pk = pk) return render_to_response('part_list.html', {'PartyNum': context, 'onePart': onePart}) urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P<pk>[\d]+)$', PartyNumView, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] And a little bit of part_list.html: {% for object in PartyNum %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'onePart' pk = object.pk %}"> {{ object.Party_number }}</a></td> <td>{{ object.Film }}</td> <td>{{ object.Thick }}</td> <td>{{ object.Critical_temperature }}</td> <td>{{ object.R_s }}</td> {% endfor %} In Models.py I have a class Part(models.Model) Help me please find a mistake. -
App error . Attribute error with first application
I have created this app in django but i cannot access the app . CMD says Attribute error : module 'hello.views' has no attribute 'index' VIEWS.PY from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello World !!!') URLS.PY/admin from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello.urls')) ] URLS.PY/Hello from django.urls import path from . import views urlpatterns = [ path('hello/', views.index, name='index') ] -
django-filter multiple filters in one view
I am successfully using django-filter to filter django-tables2 in Django 2.0.4, where I have a view with one instance of django-filter and one instance of django-tables2. So far so good... I would like to pass multiple (different) filters to a single view that has multiple tables on it. So far I have the tables successfully rendering by overriding get_context_data: class MyView(SingleTableMixin, TemplateView): template_name = 'my_template.html' def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['table1'] = Table1(MyModel1.objects.all(), prefix="1-") context['table2'] = Table2(MyModel2.objects.all(), prefix="2-") context['table3'] = Table3(MyModel3.objects.all(), prefix="3-") return context Is anyone able to point in the right direction as to how I can pass a different filter for each of these tables to my view? Any help is much appreciated! -
Is it okay that I use ManyToManyField for recent visit history in Django models?
I'm trying to implement a feature to track recent visit history in a user profile. There is a bunch of stores in my website. When a user enter a detailed page of a store, I wanna store each store in order a user enters. In order to do that, I'm currently confused about which way is better between using ManyToManyField in Django models and request.session. Can anyone suggest the most efficient way to do that? -
Split dict by value of one of the keys(To save it as a single data)
My data and issue are similar as this, but it's not the same How to split dict by value of one of the keys and save it as a single data in PostgreSQL? I have a dictionary as below: data = { "id": [1,1,2,2,1,2,1,2], "info": ["info1"],# one or more than one item, number >= 1 "number": [1],# one or more than one item, the numbers are the same as info's } I want to split it in one by id, keeping the respective info and number, and to save it as a single data in PostgreSQL. What is a Pythonic way of doing it? Django way is perfect! Thanks in advance. -
Django Queryset in ModelForm using a 'pk'
I'm trying to follow this SO Q&A which is exactly what I want to do but with a pk instead of a fixed key. My files... views.py class JuryCreate(CreateView): model = Jury form_class = JuryCreateForm def form_valid(self, form): form.instance.customer_id = self.kwargs['pk'] form.instance.court_year_id = self.kwargs['yr'] return super().form_valid(form) forms.py class JuryCreateForm(ModelForm): class Meta: model = Jury fields = [ 'parent_jury', #Other Fields ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent_jurisdiction'].queryset = Jury.objects.filter( customer_id = self.kwargs['pk']).filter( court_year_id = self.kwargs['yr']) If i go directly from the view to the template I'm able to access the queryset (it provides a queryset object). But if I go through the ModelForm it throws an AttributeError: 'JuryCreateForm' object has no attribute 'kwargs'. Basically, I bleive that the request isn't passed to the ModelForm so it can't access the kwargs. How do I get the primary keys into the ModelForm to populate the fields? I've also tried variations of get_form_kwargs method that I think is the appropriate mechanism to pass these to the ModelForm - I just can't get it to implement correctly (or get it in the right class object). -
How to generate web based report from my python charts
I wrote the following code to generate a couple of charts using the plotly library Read the excel file from local spreadsheet df = pd.read_excel(r'C:\Users\llopez\Documents\Temp\Python finished goods.xlsx', sheet_name='Sheet1') Create a dictionary of tuples by year dict_of_fgs = dict(tuple(df.groupby('Year'))) Loop through the elements of the dictionary of finished goods and plots them grouping FG, type and calculating the sum of quantities. Stacking by type for k in dict_of_fgs: df_grouped = dict_of_fgs[k].groupby(['Finished_Good','Type'],sort=False)['Qty'].sum().unstack('Type').iplot(kind='bar',barmode='stack', title='FG Chart') It yields the following charts: FG Chart 2017FG Chart 2018 The charts are exactly what I need, so now I'm looking for a way to generate a web based report and share it with users. I looked into the following tutorial but I can't seem to adapt my code to this since my code loops trough a dictionary and generates a plot for each key(Year). How can I generate a web based report given the charts I've created? Thanks in advance to all of you subject matter experts for all the great ideas on how to achieve this. I appreciate the help. -
Django app wont run after i have created my first app
This is the code for my first django app . I cant see the app after I run the server . Server cannot the find the app i have created . <URLS.PY/admin> from django.contrib import admin from django.urls import path , include urlpatterns = [ path('^admin/', admin.site.urls)``, path('^casio/', include('casio.urls')), ] <URLS.PY/app> from django.urls import path from . import views urlpatterns=[ path(r'^$' , views.index, name='index') ] <views.py/app> from django.shotcuts import render from django.hhtp import HttpResponse def index(request): return HttpResponse("<h2>HEY!</h2>") -
filter objects models depending on logged user
I have a form that contains a few fields, among these fields project that should be a select widget that contains projects that the logged user is member in. This is a portion of my code. class PublicationForm(forms.ModelForm): def __init__(self, *args, user=None, **kwargs): super(PublicationForm, self).__init__(*args, **kwargs) self.user = user project = forms.ModelChoiceField( queryset=ProjectMembers.objects.filter(user__username=user), widget=forms.Select, required=False ) class Meta: model = Publication fields = ['title', 'content', 'project', 'source'] I pass the logged user to the form in my view like this PublicationForm(request.POST, user=request.user) But I the form class I can't access the user variable, I tried ...queryset=ProjectMembers.objects.filter(user__username=self.user).. ...queryset=ProjectMembers.objects.filter(user__username=user).. but I got these errors NameError: name 'self' is not defined and NameError: name 'user' is not defined Is there a solution or other method to filter projects that the logged user is a member is. Thank you in advance. -
display images inside python django application
I am new to the python django application and I have a folder with nearly 5000 images which i want to display inside my venv django project. What is the most effective and dynamic way of displaying images using views.py and images.html which is pre-configured with basic boilerplate. later, those images will be fetched from a mongo database though. but looking for a temporary solution to work with. Thanks :D -
Django 2.1 urls returning error
please i need help, no matter how much i try, my site keep returning a 404 error due to fault in urls setup my views from django.shortcuts import get_object_or_404, render_to_response from catalog.models import Category, Product from django.template import RequestContext from untitled13.cart import cart from django.http import HttpResponseRedirect from untitled13.catalog.forms import ProductAddToCartForm def index(request, template_name='catalog/index.html'): page_title = 'online shop for all items' return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_category(request, category_slug, template_name='catalog/category.html'): c = get_object_or_404(Category, slug=category_slug) products = c.product_set.all() page_title = c.name meta_keywords = c.meta_keywords meta_description = c.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_product(request, product_slug, template_name='catalog/product.html'): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description if request.method == 'POST': postdata = request.POST.copy() form = ProductAddToCartForm(request, postdata) if form.is_valid(): cart.add_to_cart() if request.session.test_cookie_worked(): request.session.delete_test_cookie() url = 'show_cart' return HttpResponseRedirect(url) else: form = ProductAddToCartForm(request=request, label_suffix=':') form.fields['product_slug'].widget.attrs['value'] = product_slug request.session.set_test_cookie() return render_to_response(template_name, locals(), context_instance=RequestContext(request)) my urls """untitled13 URL Configuration from django.contrib import admin from django.urls import path, include from django.views import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('static/', static.serve), path('cart/', include('cart.urls')), ] my cart view from django.shortcuts import render_to_response from django.template import RequestContext from untitled13.cart import cart def show_cart(request, template_name="cart/cart.html"): cart_item_count = cart.get_cart_items(request) page_title = 'Shopping Cart' return β¦