Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework: AttributeError: 'PhotoView' object has no attribute 'encoding'
I have this code class UploadedPhotoView(GenericViewSet, ListModelMixin): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (IsAuthenticated, ) def get_queryset(self): return self.queryset.filter(owner=self.request.user) class PhotoView(GenericViewSet, CreateModelMixin, ListModelMixin): queryset = Photo.objects.all() serializer_class = PhotoSerializer permission_classes = (IsAuthenticated, ) uploaded_view = UploadedPhotoView.as_view({'get': 'list'}) def perform_create(self, serializer): try: serializer.save(owner=self.request.user) except IntegrityError: raise SuspiciousOperation @list_route(methods=('GET', )) def uploaded(self, request, *args, **kwargs): return self.uploaded_view( request, *args, **kwargs ) After run tests I got next File "/Users/denny/project/picme/api2/venv/lib/python3.6/site-packages/rest_framework/views.py", line 376, in initialize_request parser_context=parser_context File "/Users/denny/project/picme/api2/venv/lib/python3.6/site-packages/rest_framework/request.py", line 151, in __init__ self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET AttributeError: 'PhotoView' object has no attribute 'encoding' So I find it like bug, but I'm thinking problem in magic of rest framework. If I rewrite function uploaded like below then It will works. @list_route(methods=('GET', )) def uploaded(self, request, *args, **kwargs): return UploadedPhotoView.as_view({'get': 'list'})( request, *args, **kwargs ) -
Detailview Object Relations
I'm trying to use a generic detailview to return an object and it's related object. In this example, a company like mcdonalds would have any sites (or locations). What I want the detailview to be able to show is the company detail, and the site detail related to the company. I'm stuck though. Dispite my efforts in not asking for help, I have not been able to pull the data from the model referencing the company sites. Where am I going wrong? I have sort of proven this to work in the django shell with SiteModel.objects.filter(company=5) showing all of the company with an ID of 5's site names. models.py ''' The company model consists of the base company information ''' class CompanyModel(models.Model): name = models.CharField(_('Company Name'), max_length=255, blank=False) website = models.URLField(_('Company Website'), blank=True) since = models.DateField(auto_now_add=True) rate = models.DecimalField(max_digits=5, decimal_places=2, blank=False) def __str__(self): return '%s' % (self.name) class Meta: ordering = ['name'] verbose_name = 'Company' verbose_name_plural = 'Companies' ''' The site model consists of sites of a company as some companies have several sites that we will work from. ''' class SiteModel(models.Model): company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT) address = models.ForeignKey(AddressModel, on_delete=models.PROTECT) phone = models.ForeignKey(PhoneModel, blank=True, null=True, on_delete=models.PROTECT) distance = models.SmallIntegerField(blank=True) def … -
Wagtail "Pages awaiting moderation" not showing in dashboard despite having all permissions
I feel like I'm missing something painfully obvious, but if I'm in the default editors / moderator group + the user is a superuser.... Should not pages that were submitted for moderation be showing under the wagtail dashboard? I thought I might have missed a permissions so then I went to admin and added every single option there and still no dice..... What is required to be able to moderate the pages submitted for mod approval? Example: I submit a page programatically from a create view for moderation by doing the following: my_page = self.index.add_child(instance=my_page_instance) my_page.unpublish() my_page.save_revision(submitted_for_moderation=True) if not send_notification(my_page.get_latest_revision().id, 'submitted', None): print("Failed to send notification + email for mod approval") -
Prevent Suspicios actions in django
I have following suspicious logs in my django output logs. Somebody is doing vulnerability check or what? Invalid HTTP_HOST header: '47.95.231.250:58204'. You may need to add '47.95.231.250' to ALLOWED_HOSTS. [03/Dec/2017 20:09:28] "GET http://47.95.231.250:58204/ip_js.php?IP=my_ip&DK=my_port&DD=FOQGCINPZHEHIIFR HTTP/1.0" 400 62446 How can I prevent it? Tried to block 47.95.231.250 IP, but didn't help. Request is coming from different IP address probably -
how to make simple request to Google to get token to YouTube Api
Is there any simple way to just make simple request to get token? I can't find anything simple. The process of authorization need to be done by server in the background so the solution provided by Google is not good for me(login web page). I just want to make something simple like post request with all data and get token as the response. There will be google account created for django app, and using this app user will be able to create/update playlist on youtube. One account, many playlists and users. Br Tomo -
Django - trying to call manytomany field with though in both view and template
Im trying to get data from the user's model from another model, that is between the both to models. My main model is Team from there there's a members field that is a manytomany field where it's going through its own model called team memberships that has 3 fields where one is a relation to a user. Short saying: Calling model.Teams -> field.membersmanytomany -> model.TeamMembership -> field.userforeignkey -> model.users -> getting info But every time im trying it I don't get any info, why? My Models: Users model is standard from Django. class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() @property def teamleaders_listable(self): leaders = self.members.filter(teammembership__leader=True) return ", ".join(l.extendeduser.nickname for l in leaders) @property def multiple_teamleaders(self): if len(self.members.filter(teammembership__leader=True)) > 1: return True else: return False def __str__(self): return self.name class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField() My View: def team(request, team_pk): requested_team = get_object_or_404(Team, pk=team_pk) feedback = FeedbackSupportForm() context = { 'requested_team': requested_team, 'feedback': feedback, } if requested_team.multiple_teamleaders: context["multiple_teamleaders"] = True if request.user.is_authenticated(): if requested_team.members.all().count() > 0: context['teamhasmembers'] = True logged_in_user = get_object_or_404(User, pk=request.user.pk) context['logged_in_user'] = logged_in_user return … -
from tagging/models.py: ImportError: cannot import name 'generic'
While running server import error is generated. Here I even don't use this generic types anywhere in my file. Then how can this error is generated??? C:\Python34\python.exe manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000004BC8B70> Traceback (most recent call last): File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Python34\lib\site-packages\django-2.0-py3.4.egg\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "C:\Python34\lib\site-packages\tagging\models.py", line 5, in <module> from django.contrib.contenttypes import generic ImportError: cannot import name 'generic' -
Can't connect to Dockerized Django application
My full source code for my project can be found here: https://bitbucket.org/cxbenchmark/cx-benchmark/src I am trying to run the production stack (using docker-compose) of my application locally. First, I build the images: docker-compose -f production.yml build Then I run everything with: docker-compose -f production.yml up The output of this command can be found here: https://bitbucket.org/!api/2.0/snippets/cxbenchmark/ReeAnx/087c8a63c196522d17791dd2d9f729ce4662dd16/files/snippet.txt At this point, I'm not exactly sure where to go to try to view the application. I've tried localhost, localhost:443, localhost:8000, and localhost:80. I've also tried all those ports with 127.0.0.1 instead of localhost. In all cases, the browser tells me the site can't be reached. Can anyone help me understand what I'm doing wrong here? Thank you! -
Ajax request for file to be processed in JS on client-side
This is a very general question: I would like to download a file from the server that is only available after some input-dependent processing was done on the server via an AJAX request (e.g. using jQuery). However, I don't want to pass that file explicitly to the user as a download in the browser. Instead, I would like to use the file for displaying some figures, which I want to create on the client-side in JavaScript because they are dynamic (specifically, can be modified by the user with sliders). As a backend, I am using Django. Any thoughts/code on how to do this exactly, or alternatively reasons why the pipeline I imagine is not a good idea? -
html forms download file django
I am stuck with this issue in Django: I want to download a file already existing on my server through a html form. The file to be downloaded is served through a function in views. My problem is with html form and passing the file name to view. How can I pass the name of the file from form toward view without having to select the file? In html I have: # 'content' keeps the name of the file to be downloaded {% block content %} {{content}} <table> <tr> <td> <form action="" method="POST" enctype="multipart/form-data"> <input type="file" name="file"/> <br /> <input type="submit" value="Download File" /> </form> </td> </tr> </table> {% endblock %} When I select the file and press submit button, it works but I need a different behavior: the name of the file containing results (downloadable file) to be passed to views into a variable. The views will then serve it. The view which handled the downloadable file: def forecast(request): if request.method == 'POST': #handle_download_file(request.FILES['file'], str(request.FILES['file'])) print('request.method este: ',request.method) RESULTS_filename = 'frcst_'+ str(request.FILES['file']) #download('GET', RESULTS_filename) file_path = os.path.join(os.path.relpath('forecast/'), RESULTS_filename) print (file_path) print(settings.MEDIA_ROOT) with open(file_path,'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['content-disposition'] = 'attachment; filename='+RESULTS_filename print(response) return response HttpResponseRedirect('/forecast/') return render(request,'result_links.html',{'content':'frcst_history.csv'}) -
MultiFieldPanel width in Wagtail and displayed name
I have the following MultiFieldPanel. class TeamRooster(Page): staff = StreamField([ ('staff', CardsBlock(Staff(), icon="plus")), ], blank=True) content_panels = [ MultiFieldPanel( [ StreamFieldPanel('staff') ], heading="Staff", classname="col12" ), three times "Staff" is too much. I looked in the documentation and tried to delete the names but I have a bug. And how to change the width of MultiFieldPanel? I tried to add classname="full" but it doesn't help me. -
Can I use the Node.js packages along with Django?
I think I haven't understood this concept right . If I am using Django as a backend to run server side code , is there a way to include the packages of Node.js also . Isn't Node.js kind of another environment or language for server side code ? If I can use Node packages with Django , how to go about it. What does it mean when people say "Node js is a platform and Django is a framework" ? I would be very greatful if you include some indepth details about these two environments ( new to web development here:)) -
Django template counting days from now to specific date
I have a model with DateField: end_date = models.DateField(default=datetime.date.today) In the template I need to calculate how many days there is to the end_date from now. I tried: {% now "d m Y"|timeuntil:placement.end_date|date:"d m Y" %} but it doesn't work. How can I get number of days until that date? -
Why a form don't need 'action'? UserCreationForm
I create a form using django auth forms UserCreationForm and it works without 'action' inside . Why it works? views.py def sign_up(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('contacts:index') else: form = UserCreationForm() return render(request, 'account/signup.html', {'form': form}) sgnup.html <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up!</button> </form> -
Django json.loads(request.body) gives error Expecting value: line 1 column 1
I'm trying to push JSON data to my Django View, GET is working fine but every time I try to process the push data with json.loads(request.body) I get raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) My JavaScript <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(document).ready(function () { var post = function () { $.ajax({ type: "POST", contentType: "application/json", url: "http://127.0.0.1:8000/app/input", data: {first_name: "Test", status: "testing"}, dataType: "json" }); }; post(); }) </script> The console.log for the browser is {"baz": "goo", "foo": "bar"} jquery-3.2.1.min.js:4 POST http://127.0.0.1:8000/app/input 500 (Internal Server Error) Django View from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import json # Create your views here. @csrf_exempt def input(request): if request.method == 'GET': data = {'baz': 'goo', 'foo': 'bar'} data = json.dumps(data) return HttpResponse(json.dumps(data), content_type='application/json') else: data = request.body print(request.body) #b'first_name=Test&status=testing' print(type(request.body)) #<class 'bytes'> decodebody = request.body.decode('utf-8') print(decodebody) #first_name=Test&status=testing print(type(decodebody)) #<class 'str'> jsondata = json.loads(data) print(jsondata) print(type(jsondata)) return HttpResponse(data, content_type='application/json') Django Log b'first_name=Test&status=testing' <class 'bytes'> first_name=Test&status=testing <class 'str'> [03/Dec/2017 13:00:49] "GET /app/input HTTP/1.1" 200 38 Internal Server Error: /app/input Traceback (most recent call last): File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) … -
How to generate a histogram in Django view (from pandas df) and pass to template
I have a script that gets executed when the following view function is called in Django: def CalScriptResultsView(request): all_activities = models.CalEvents.objects.filter(user=request.user) activities = ['Undefined',] for activity in all_activities: activities.append(activity.activity_code) script_result = gCalScriptMain.main(activities) return render(request, 'gCalData/gCalData_result.html', {'script_result': script_result}) The script gCalScriptMain.main() reads events in a google calendar and builds a pandas data frame. The headers (columns) of the df are the activities defined by the user and the index (rows) is made of date type dates (e.g. 2017-10-02). The actual data consists in number of hours spent on each activity for each day (in a three month period). I want to be able to plot a histogram that looks something like this: Desired histogram type And I have to somehow return the histogram to the view so that then it gets passed to the corresponding template and can be displayed on the webpage. What I have tried is the following: import matplotlib.pyplot as plt df.hist() plt.savefig('path/to/hist.png') But it just generates a blank file. However, I'm also doubting if this is a good approach or if there is something better. Any ideas? -
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N
I am learning django from a book. According to instruction I created a forms.py file inside the same directory that views.py exists. Inside the file I wrote the following codes: from django import forms class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required = False) message = forms.CharField() Then after entering virtual environment through env_mysite\scripts\activate I started python. After than I typed: from mysite.forms import ContactForm f = ContactForm() But I receive the following message after a lot of file paths django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I opened setting.py file and USE_I18N was True I have just followed the instruction from tutorial book I but don't understand what is wrong here. Could you please help -
Django ModelForm - Displaying ManyToMany relationship to model which has a recursive relationship
I have two models Product and Category. Category has a recursive relationship to store subcategories Class Product(models.Model): name = models.CharField(max_length=50) categories = models.ManyToManyField(Category) Class Category(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', related_name='parent_category') I want to use a ModelForm for adding products along with categories class ProductForm(ModelForm): def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['categories'].widget = forms.widgets.CheckboxSelectMultiple() self.fields['categories'].queryset = Category.objects.all() class Meta: model: Product fields: ('name', 'categories') The above modelform displays all categories on a single level. category1 category2 subcategory11 subcategory12 subcategory21 subcategory22 Is there a way to display categories and sub categories under the parent category as below? category1 subcategory11 subcategory12 category2 subcategory21 subcategory22 -
when should I write custom methods in model vs model manager/ queryset
when should I write methods in the model itself and when in the model manager? is it like all methods to get something should be written in manager and others in model -
AttributeError: 'TaggableManager' object has no attribute 'rel' error
I am new to django and i can't locate this error: File "E:\charmi\mysite\personal\models.py", line 113, in <module> class Disease(models.Model): File "E:\charmi\mysite\personal\models.py", line 118, in Disease symptoms.rel.related_name = "+" AttributeError: 'TaggableManager' object has no attribute 'rel' This my model file: class TaggedSymptoms(TaggedItemBase): content_object = models.ForeignKey("Disease",on_delete=models.CASCADE) class Disease(models.Model): did = models.AutoField(verbose_name='Disease id',primary_key=True,auto_created=True) dName = models.CharField(max_length=100,unique=True) symptoms = TaggableManager(verbose_name='symptoms list',through=TaggedSymptoms) symptoms.rel.related_name = "+" -
Django rest serializer nested objects serialized as OrderedDict instead of pure JSON
How to make Django serializer to serialize nested objects as json instead of ordereddict? class SummaryGroupContract: class Serializer(serializers.Serializer): total = serializers.DecimalField(max_digits = 10, decimal_places = 2) def __init__(self, total: Decimal): self.total = total class SummaryResponse: class Serializer(serializers.Serializer): income = SummaryGroupContract.Serializer(required=False) expenses = SummaryGroupContract.Serializer(required=False) def __init__(self, income: SummaryGroupContract, expenses: SummaryGroupContract): self.income = income; self.expenses = expenses; class SummaryViewSet(viewsets.ViewSet): def list(self, request): income = SummaryGroupContract(10.0) expenses = SummaryGroupContract(-90.0) return Response(SummaryResponse.Serializer(SummaryResponse(income, expenses)).data) returns {'income': OrderedDict([('total', '10.00')]), 'expenses': OrderedDict([('total', '-90.00')])} expected {'income': {'total': '10.00'}, 'expenses': {'total': '-90.00'}} -
Django url variable not passing
I'm trying to get a variable from url and display it in template using django. Here's the page with the link to the bucket's page: <div id="left"> <a href="{% url 'project:bucket' bucket=bucket.bucketName %}"><h4 id='s3ItemName'>{{ bucket.bucketName }}</h4></a> </div> This displays the bucket name properly and contains a link to abucket detail page. My urls.py look like this: url(r'bienbox/bucket/(?P<bucket>\w+)$',views.bucketPage.as_view(),name='bucket') Now, here's views.py class bucketPage(TemplateView): template_name = "project/bucket.html" def get(self, request, bucket): bucketName = request.GET.get('bucket') return render(request,self.template_name,{'bucketName': bucketName}) So I'm passing the bucketName variable here, however when the page opens I get "None" instead of the variable name. Here's the bucket.html: <div class="mainPage"> <div class="s3Wrapper"> <h2>{{ bucketName }}</h2> </div> </div> What am I doing wrong? Why is the variable not passed? Thanks. -
Can I use a hosted PayPal button with the Django PayPal package?
I'm new to PayPal but I created a hosted button using the form on the PayPal developer website: <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="XXXXXXXXXXXXX"> <table> <tr> <td> <input type="hidden" name="on0" value=""> </td> </tr> <tr> <td> <select name="os0"> <option value="Foo">Foo : £10.00 GBP - monthly</option> <option value="Bar">Bar : £15.00 GBP - monthly</option> </select> </td> </tr> </table> <input type="hidden" name="currency_code" value="GBP"> <input type="image" src="https://www.sandbox.paypal.com/en_US/GB/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.sandbox.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1"> </form> I searched the documentation for the Django PayPal package (https://django-paypal.readthedocs.io/en/stable/) but I didn't see any mention of hosted buttons. Can I use this HTML code as is with Django PayPal, do I have to generate a new button through Django PayPal, or can I somehow point Django PayPal to this hosted button? -
Django intermediate M2M a[href] not saving data to database
Working on a project with Django (social platform) where user can create group for other users to join or leave. This is my first Django project, i'm not sure if my implementation of the join and leave group logic is right. i have a join button which is an a[href] tag: <a href="{% url 'join' group.id %}" class="btn btn-primary">Join Group</a> Clicking it supposed to add the user to the group. Below are the models and views: models.py: @python_2_unicode_compatible class Group(models.Model): title = models.CharField(max_length=255, null=False, unique=True) description = models.TextField(max_length=2000, null=False) location = models.CharField(max_length=255, null=False) date = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, related_name="creator") members = models.ManyToManyField(User, through='Membership') counter = models.IntegerField(blank=False, null=True) @python_2_unicode_compatible class Membership(models.Model): person = models.ForeignKey(User) group = models.ForeignKey(Group) date_joined = models.DateField(auto_now_add=True) views.py: @login_required def group(request, pk): group = get_object_or_404(Group, pk=pk) return render(request, 'group/group.html', {'group': group}) @login_required def join(request, pk): _group = get_object_or_404(Group, pk=pk) membership = Membership() membership.group = _group membership.person = request.user membership.save() return group(request, pk) The user doesn't get saved to the membership table. What is the best way to approach this? Any help will be very much appreciated. Also tried this view function for the join button: @login_required def join(request, pk): _group = get_object_or_404(Group, pk=pk) membership = Membership.objects.create(user=request.user, group=_group) … -
How to make a layout like Youtube? Is there a template in HTML5/CSS3 that I can follow?
How to make an layout like current Youtube's homepage in HTML5/CSS3? I've learned the basics of HTML5/CSS3, Javascript, and Python Django. However, I have no idea about how to find a template to make websites like Youtube or where to find the template. If anyone knows the answers, please let me know. Appreciated!!