Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django(-CMS) Userwarning: No registered apphook
I have a django website with some selfbuild applications, three in count. Since I have updated to Django-CMS 3.4.3 and Django 1.9.11 (for aldryn newsblog) I get the following warning: venv/lib/python2.7/site-packages/cms/apphook_pool.py:97: UserWarning: Kein registrierter apphook "u'AssociationAppApp'" gefunden warnings.warn(_('No registered apphook "%r" found') % app_name) or in english (my own translation) venv/lib/python2.7/site-packages/cms/apphook_pool.py:97: UserWarning: No registered apphook "u'AssociationAppApp'" found warnings.warn(_('No registered apphook "%r" found') % app_name) I have a cms_app.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ from .menu import AssociationSubMenu class AssociationApp(CMSApp): name = _('Associations') app_name = 'associations' def get_urls(self, page=None, language=None, **kwargs): print("called") return ['bbd.apps.associations.urls'] apphook_pool.register(AssociationApp) my urls.py from django.conf.urls import url from .views import AssociationListView, AssociationDownloadListView, AssociationDetailContactView, AssociationEventListView urlpatterns= [ # List View url(r'^$', AssociationListView.as_view(), name="association_list"), # Contact View url(r'^(?P<slug>[^/]+)/kontakt$', AssociationDetailContactView.as_view(), name='association_contact'), # List association_events url(r'^(?P<slug>[^/]+)/veranstaltungen$', AssociationEventListView.as_view(), name='association_detail_events'), url(r'^(?P<slug>[^/]+)/downloads$', AssociationDownloadListView.as_view(), name='association_detail_downloads'), # Detail View url(r'^(?P<slug>[^/]+)', AssociationDetailContactView.as_view(), name='association_contact'),] my projects urls.py from django.contrib.sitemaps.views import sitemap admin.autodiscover() urlpatterns = staticfiles_urlpatterns() urlpatterns += i18n_patterns( url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), url(r'^filebrowser_filer/', include('ckeditor_filebrowser_filer.urls')), url(r'^associations/', include('bbd.apps.associations.urls', namespace="associations"), name='associations'), url(r'^google986acbe70fc0baef\.html$', lambda r: HttpResponse("google-site-verification: google986acbe70fc0baef.html", mimetype="text/plain")), url(r'^robots\.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: ", mimetype="text/plain")), url(r'^', include('cms.urls')) ) The App is in the INSTALL_APPS. My problem … -
Why won't my server start running?
Why am I getting an error when trying to run my server to access the database to see if my code works? While in my projects folder in Terminal, I ran sudo python manage.py runserver to try to run the server but it doesn't work because of the aforementioned error. I've looked around SO but can't find one directly related to my problem. I'm guessing my if() statement is the problem. The error I'm getting says: RuntimeError: maximum recursion depth exceeded while calling a Python object Here's my views.py file: from .models import Album from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.core.urlresolvers import reverse_lazy from django.views import generic from django.views.generic import View from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import UserForm class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DeleteView): model = Album template_name = 'music/detail.html' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def … -
Django error: bad interpreter: No such file or directory
I'm trying to install Django using a Python environment using terminal. I'm currently within the Python environment attempting to run: pip install django The error that I repeatedly receive is the following: bad interpreter: No such file or directory (New to using CLI btw) -
Implement a statistical measure
Just a light question. I'd like to implement a form of content rating into my website using a statistical measure such as the gitbub example below How do I go about that?. What is it called? And is there an app for it in the django framework? Thanks -
Issue with assertContain()
{% extends "loanwolf/base.html" %} {% load i18n crispy_forms_tags staticfiles %} {% block js %} {{ block.super }} <script src="{% static "loanwolf/js/loanwolf.customer.fields.js" %}"></script> <script src="{% static "loanwolf/js/loanwolf.module.application.js" %}"></script> {% endblock %} {% block page_title %}{% trans "New loan request application" %}{% endblock %} {% block breadcrumb_items %} <a href="{% url "requests:index" %}" data-turbolinks="false">{% trans "Requests" %}</a> <a href="{% url "requests:applications" %}" data-turbolinks="false">{% trans "Applications" %}</a> <a href="#!">{% trans "New" %}</a> {% endblock %} {% block content %} <div class="row change-form"> <div class="col s12 m12 l12"> {% include "loanwolf/form-errors.inc.html" with object=object %} {% crispy form form.helper %} </div> </div> <script> function testUser () { $('#id_first_name').val('Arold').next().addClass('active'); $('#id_last_name').val('Tremblay').next().addClass('active'); $('#id_email').val('testjohn@email.com').next().addClass('active'); $('#id_birth_date').val('1971-01-01').next().addClass('active'); $('#id_ssn').val('123 456 789').next().addClass('active'); $('#id_phone_1').val('450 123 1234').next().addClass('active'); $('#id_phone_2').val('450 514 1234').next().addClass('active'); $('#id_fax').val('450 816 1234').next().addClass('active'); $('#id_civic_number').val('123').next().addClass('active'); $('#id_street').val('test street').next().addClass('active'); $('#id_state').val('QC').next().addClass('active'); $('#id_address_line2').val('').next().addClass('active'); $('#id_city').val('Montreal').next().addClass('active'); $('#id_zip_code').val('A1A B2B').next().addClass('active'); $('#id_company_name').val('Test company').next().addClass('active'); $('#id_date_hired').val('2016-05-05').next().addClass('active'); $('#id_job_title').val('Test jobtitle').next().addClass('active'); $('#id_supervisor_name').val('Supervisor Name').next().addClass('active'); $('#id_phone').val('450 111 2222').next().addClass('active'); $('#id_phone_extension').val('333').next().addClass('active'); $('#id_emp_civic_number').val('888').next().addClass('active'); $('#id_emp_street').val('test emp street').next().addClass('active'); $('#id_emp_state').val('QC').next().addClass('active'); $('#id_emp_address_line2').val('line 2').next().addClass('active'); $('#id_emp_city').val('Quebec').next().addClass('active'); $('#id_emp_zip_code').val('B1B A2A').next().addClass('active'); $('#id_bank').val('815').next().addClass('active'); $('#id_first_pay_date').val('2017-03-09').next().addClass('active'); $('#id_ref1_fullname').val('Test full name 1').next().addClass('active'); $('#id_ref2_fullname').val('Test full name 2').next().addClass('active'); $('#id_ref1_phone').val('450 222 2222').next().addClass('active'); $('#id_ref2_phone').val('450 342 2342').next().addClass('active'); $('#id_ref1_link ').val('Test link 1').next().addClass('active'); $('#id_ref2_link ').val('Test link 2').next().addClass('active'); $('#id_agree_terms_and_cond').prop('checked', true) $('#id_mass_mailing_subscription').prop('checked', true) } </script> {% endblock %} From this html file, I tried to make a unittest with def test_create_valid(self): self.signin() rs = self.client.post(reverse('requests:applications-create'), EXTERNAL_REQUEST_DATA, follow=True) self.assertContains(rs, … -
How do I update the ManyToManyFields of my model using a ModelForm?
I have a Model Profile containing info about a User, including a number of tags. This Profile is created when the User is created. I also have a FormView that updates this profile by adding tags. What I am trying to do is add any new tags, keep any existing checked tags, and remove any existing tags which are unchecked, but when I do this, the unchecked tags are not removed from the CheckboxSelectMultiple field. They are however removed from the user.profile.tags as used in the profile.html template. What I would like to do is one of: 1) Have the "checked" attribute for each tag set depending on whether it is currently present in the user.profile.tags. 2) Only show a tag in the CheckboxSelectMultiple field if it is currently present in the user.profile.tags. How should I approach this? Or am I missing a better way of achieving this goal? # models.py ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, editable=False) tag = models.ManyToManyField(Tag, blank=True) def __unicode__(self): return self.user.username # forms.py ... class ProfileForm(forms.ModelForm): add_tags = forms.CharField(max_length=255, required=False) class Meta: model = Profile fields = ['tags'] widgets = { 'tags': CheckboxSelectMultiple(attrs={"checked":""}), 'add_tags': TextInput(), } def clean(self): cleaned_data = self.cleaned_data tags = self.cleaned_data.get('tags', … -
Django Rest Framework restrict user data view to admins & the very own user
I am using Django and DRF, and I would like to check if a user (regular one), after it has been authenticated, is allowed to view it's own profile and only that (no other user's). serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'url', 'username', 'password', 'email', 'groups', 'is_staff') def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user Views.py class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = (IsUser,) permissions.py class IsUser(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_permission(self, request, view, obj): # View or Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user This, obviously is not working, because is wrong. But I can not figure out how to allow a user to view: http://127.0.0.1:8000/api/users/7 ONLY if its an admin, or the very same user doing the request. And: http://127.0.0.1:8000/api/users/ Only if it's an admin. Thanks! -
Newbie - Python Django - NoReverseMatch Error
I have gone through lots of related questions but I am not able to solve this issue so I though I will finally post it, I have an app 'Customers' which will hold a list of customers, currently there are two user levels 1) Customer - If I login as a Customer I would ONLY see my details and I must be able to edit and make changes to my information 2) Advisor - If I login as an Advisor I would see a list of customers and I would be able to make changes to any customer. To achieve this I have an 'Edit' button when clicked redirects to a 'form' with the particular fields already populated, I can edit and save. Issue arises when I click on this 'Edit' I get this error "NoReverseMatch at /customer/". But when I directly navigate to the form by typing in, "localhost:8000/customer/1/edit" I could see the form. Here's my views.py @login_required def customer_edit(request, cust_number): # customer = get_object_or_404(Customer, pk=cust_number) if request.method == "POST": form = CustomerForm(request.POST) # form = CustomerForm(request.CUSTOMER, instance=customer) if form.is_valid(): customer = form.save(commit=False) customer.cust_number = request.user customer.updated_date = timezone.now() customer.save() return redirect('customer', pk=cust_number) else: form = CustomerForm() return render(request, … -
Require at least one MultiFieldPanel object [wagtail]
I have a content_panels definition that includes this: MultiFieldPanel( [ InlinePanel('related_resource_type', label="Resource Type",), ], heading="Resource Type", classname="collapsible" ), This references class RelatedResourceType(Orderable): page = ParentalKey('ShopPage', related_name='related_resource_type') resource_type = models.CharField( max_length=16, choices=shopchoices.RESOURCE_TYPE_CHOICES, default="shop" ) Is there a way in Wagtail to require at least one RelatedResourceType? Preferably I would also have the ability to specify a minimum number of RelatedResourceTypes. I cannot find in the documentation how to specify required panels. Thanks in advance. -
Ordering by a OneToOne self-referencing field in Django
I'm trying to order a query by a self-referencing OneToOne field. The model: class Foo(models.Model): prior_foo = models.OneToOneField('self', related_name='following_foo', null=True, blank=True) There is no guarantee that the pk for the linked item is higher or lower, (or any other field is useful besides the OneToOne reference) e.g.: Foo.pk | prior_foo.pk 3 | null 6 | 3 5 | 6 10 | 5 I'd love to have the query return: [foo_3, foo_6, foo_5, foo_10] -
Use Travis-CI to deploy my Django app to Azure
I want to use Travis-CI to deploy my Django app to Azure, if anyone has idea how to make it? thank you -
How do I refresh an access token from Azure AD using django-rest-framework-social-oauth2?
The documentation gives an example of how to convert an Azure access_token that the user already has from the login process, but I'm not seeing anything about how to refresh that token. I managed to roll my own using adal, the Azure AD library for python, but I'm wondering if there's a better way using the tools included in DRF social oauth 2 or other django oauth packages that I'm just not finding. Please advise. Below is the function that refreshes my Azure AD token. def refresh_social_access_token(self, request): """ This function leverages adal https://github.com/AzureAD/azure-activedirectory-library-for-python to refresh an expired access token. .acquire_token_with_refresh_token(self, refresh_token, azure_ad_app_key, resource, azure_ad_app_secret) """ user_social_auth = request.user.social_auth.filter(user=request.user) \ .values('provider', 'extra_data')[0] context = AuthenticationContext(f'https://login.microsoftonline.com/{self.TENANT_ID}') token = context.acquire_token_with_refresh_token( user_social_auth['extra_data']['refresh_token'], SOCIAL_AUTH_AZUREAD_OAUTH2_KEY, user_social_auth['extra_data']['resource'], client_secret=SOCIAL_AUTH_AZUREAD_OAUTH2_SECRET ) try: expiry = convert_iso_to_epoch(token["expiresOn"]) user_social_auth = request.user.social_auth.get(user=request.user) user_social_auth.extra_data['expires_on'] = expiry user_social_auth.save() except KeyError: HttpError('Oauth2 token could not be refreshed as configured.') -
Auto-fill Django Forms Before Using "clean(self)" to Raise ValidationError
I am hoping to have my users enter an integer value for quantity, then check to see if the entered number is greater than the total quantity available. If it is greater, then the user can't place the order so a validation error will be raised. However, I am having some trouble accomplishing this. As it stands my models.py looks like this: class DirectInvestment(models.Model): offering = models.ForeignKey('company.DirectOffering', blank=True) quantity = models.IntegerField() The total share count is derived from offering.current_shares_outstanding (since it is a foreign key). Furthermore my forms.py looks like this: class DirectInvestmentForm(forms.ModelForm): class Meta: model = DirectInvestment fields = ('offering', 'quantity') def clean(self): cleaned_data = super(DirectInvestmentForm, self).clean() print(cleaned_data) quantity = cleaned_data.get("quantity") total_available_shares = cleaned_data.get("offering.current_shares_outstanding") if quantity > total_available_shares: raise forms.ValidationError("Quantity exceeds total shares available") And finally, here is the relevant bits of my views.py: form = DirectInvestmentForm(request.POST or None) form.fields['offering'].widget = forms.HiddenInput() if form.is_valid(): investment = form.save(commit=False) offering = DirectOffering.objects.get(id=offering_id) # offering_id I get from the URL investment.offering = offering investment.save() return HttpResponseRedirect('/investments') context_dict['form'] = form When I rum my code and submit the form I get the error: unorderable types: int() > NoneType() and if I look at the Local vars I see that cleaned_data has the following: … -
Wagtail static files fail on apache
I managed to upload wagtail to the live server and configured it using the following instructions. Due to time sensitivity I started upload some content while running python manage.py runserver 0.0.0.0:1234 Now while running it on apache I can see most things just nothing that used the static tag. Based on some research it may have something to do with dev and production mode? So i tried changing my wsgi file to point to my production configs os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uraia.settings.production") Which has: DEBUG = False But to no avail. I then tried using the libraries WhiteNoise and dj-static in my wsgi.py Non worked. How do I get Wagatil to work on my apache2 as normal without losing any uploaded data i did via the admin page/data in the database? -
how to merge x views in one template
I'm trying to use two views list(post_list and classification_list) in a template called blogpage. here's what I've done to solve the problem, however it didn't work: class GenViewList(ListView): model = Posting,Classification template_name = 'Blog/blogpage.html' def get_context_data(self, **kwargs): context=super(BlogViewList,self).get_context_data(**kwargs) context['latest_post_list']=Posting.objects.filter().order_by('-id')[:30] context['classification_list']=Classification.objects.all().order_by('id') return context Any help will be appreciated! -
Can not upload image in django rest frame work
I am trying to upload image in Django. I am successful in saving data of other fields. But images are not uploading. My model: from django.db import models from account.models import Account # Create your models here. class Question(models.Model): question_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(Account,db_column='account_id',on_delete=models.CASCADE) type = models.CharField(max_length = 50 ,default= 'General') location = models.CharField(max_length =50,default='Dhaka') header = models.CharField(max_length =200) details = models.CharField(max_length=500) date_time = models.DateTimeField(auto_now_add=True) vote = models.IntegerField(default=0) hidden_flag = models.BooleanField(default=False) anonymous = models.IntegerField(default=1) image_1 = models.ImageField(blank=True,default='',upload_to='questions/') image_2 = models.ImageField(blank=True,default='',upload_to='questions/') My Serializer: from rest_framework import serializers from .models import Question class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('question_id', 'user_id', 'type', 'location', 'header', 'details', 'date_time','vote','hidden_flag','anonymous','image_1','image_2') read_only_fields = ('question_id',) My views.py: from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response # Create your views here. from .serializer import QuestionSerializer class QuestionView(APIView): def post(self,request): serealizer = QuestionSerializer(data=request.data) if serealizer.is_valid(): serealizer.save() return Response("Created") else: return Response(serealizer.errors) At the end of my settings.py file i have included the following code: MEDIA_ROOT = os.path.join(BASE_DIR,'..','uploaded_media') MEDIA_URL = '/media/' I think I have made some mistakes in my views because when i am trying to upload image with django admin panel. The image upload is successfull. But if i try to upload … -
Django set form field after POST request
I'm using class-based views (FormView) and I would like to keep a search keyword after form is submitted (POST request). I tried this in form_valid method: def form_valid(self, form): self.initial['search'] = form.data['search'] ... but this will show it for all users. This is quite common solution on many web search forms (not to mention Google search) so I wonder how this can be done in Django. -
Code architecture for a Pinterest-like website? Complex to manage?
[DISCLAIMER] I'm an uber-n00b about most things dev/programming/coding & well-aware of that. I know how dumb my questions might be. The questions I'm asking could be completely redundant or totally moot or not even applicable or relevant.. I'm just trying to learn. [END DISCLAIMER] I've been reading that Django works really well for websites similar to Pinterest? If you were going to create a website similar to Fancy.com Pinterest.com Thisiswhyimbroke.com What code would you use? So basically here are the questions I'm seeking answers for: To build a Pinterest-like website, what would be good? I know basic HTML & CSS and have done Wordpress websites is managing a Django or other type of website (after having a developer help me build it) going to be way too complicated for me? -
Error in running command manage.py migrate
I change my models.py and after that i cant do python manage.py migrate, i have an error when i run this command. I dont understand what is this string value Incorrect string value: '\\xD0\\x90\\xD0\\xB4\\xD0\\xB4...' In Traceback wrote that this string in column name, but i have not column name in my database! This is my models.py: from django.db import models from datetime import datetime, timedelta, date from django.utils import timezone from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from .sitemap import add_url # Create your models here. class Server(models.Model): title = models.CharField(verbose_name='Название', max_length=255, unique=True) client = models.CharField(verbose_name='Клиент',max_length=255) rate = models.CharField(verbose_name='Рейт',max_length=255) online = models.IntegerField(verbose_name='Количество онлайн',blank=True, null=True, default=0) description = models.TextField(verbose_name='Описание',blank=True, null=True) price_for_gold = models.IntegerField(verbose_name='Цена за золото',) lvl_up_1_10 = models.IntegerField(verbose_name='Прокачка 1-10',default=0) lvl_up_10_20 = models.IntegerField(verbose_name='Прокачка 10-20',default=0) lvl_up_20_30 = models.IntegerField(verbose_name='Прокачка 20-30',default=0) lvl_up_30_40 = models.IntegerField(verbose_name='Пркоачка 30-40',default=0) lvl_up_40_50 = models.IntegerField(verbose_name='Прокачка 40-50',default=0) lvl_up_50_60 = models.IntegerField(verbose_name='Прокачка 50-60',default=0) lvl_up_60_70 = models.IntegerField(verbose_name='Прокачка 60-70',blank=True, null=True) link = models.CharField(max_length=255, verbose_name='Ссылка', default='', unique=True) def __str__(self): return self.title def get_image_url(self): image = Image_for_server.objects.get(server=self) return image.image.url class Meta: verbose_name = 'Сервер' verbose_name_plural = 'Сервера' class Discount(models.Model): TYPE_CHOICES = ( ('Золото', 'Золото boost'), ('Прокачка уровня', 'Прокачка уровня %') ) start = models.IntegerField(verbose_name='Со скольки') count = models.IntegerField(verbose_name='Какая скидка') type = models.CharField(verbose_name='Тип скидки', max_length=255, choices=TYPE_CHOICES) server = … -
Django Login form not authenticating
Trying to create a login view using class based views (first time), and everything populates, but it keeps saying that my username is invalid. Please help me figure out whats wrong. login.html (Just the opening tag username id is username password id is password): <form class="form-horizontal" method="post" action="{% url 'dispatch:login' %}" role="form"> {% csrf_token %} views.py: (Pulled from a tutorial) class LoginView(FormView): """ Provides the ability to login as a user with a username and password """ success_url = '/' form_class = LoginForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'pages/login.html' @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # Sets a test cookie to make sure the user has cookies enabled request.session.set_test_cookie() return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): auth_login(self.request, form.get_user()) # If the test cookie worked, go ahead and # delete it since its no longer needed if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() return super(LoginView, self).form_valid(form) def get_success_url(self): redirect_to = self.request.REQUEST.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to class LogoutView(RedirectView): """ Provides users the ability to logout """ url = '/accounts/login/' def get(self, request, *args, **kwargs): auth_logout(request) return super(LogoutView, self).get(request, *args, **kwargs) forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=255, required=True) password = forms.CharField(widget=forms.PasswordInput, required=True) def clean(self): username = self.cleaned_data.get('username') password = … -
Cannot send Django email
I am trying to send email notification when user will receive a message in my application from another user. But for some reason emails are not sending. Email accounts are configured properly on a server. I do not have any errors. Django version 1.10.6. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'my.smtp.host' EMAIL_PORT = 25 EMAIL_HOST_USER = 'myemailaccount@mydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER views.py: from django.core.mail import EmailMessage class View(TemplateView): def post(self, request, pk): form = MessagesForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.sender = request.user message.reciever = User.objects.get(pk=pk) reciever_id = User.objects.get(pk=pk).pk message.save() email = EmailMessage('Hello', 'World', to=[message.reciever.email]) if message.reciever.userprofile.email_notifications: email.send() form = MessagesForm() return redirect(reverse('user_messages:user_messages', args=[reciever_id],)) args = {'form': form} return render(request, self.template_name, args) -
join queryset of dictionary in python by value?
I have this queryset [{'estacion__nombre': u'Agencia 5ta y 42', 'cantidad': 1,, 'fk_codigosm__fk_categoria__identificador': u'b'}, {'estacion__nombre': u'Agencia 5ta y 42', 'cantidad': 2, 'fk_codigosm__fk_categoria__identificador': u'D'}, {'estacion__nombre': u'Agencia Habana', 'cantidad': 2, 'fk_codigosm__fk_categoria__identificador': u'D'}, {'estacion__nombre': u'Agencia Pinar del Rio', 'cantidad': 1, 'fk_codigosm__fk_categoria__identificador': u'b'} I want this Agencia 5ta y 42 (1,b) (2,d) Agencia Habana (2,d) Agencia Pinar del Rio (1,b) -
django storages uploades to amazon s3 but displays error when accessed from the website
I have a single page application which use Vuejs and django as its backend. I am using django-storages and boto3 to store files. I have install aws cli and has set up credentials. Also in my project settings these are added: AWS_STORAGE_BUCKET_NAME = 'mybucket-name-static' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can run collectstatic and it does upload to my bucket. However, no static files are downloaded into the browser. If I inspect the url of the static files in the website, extra strings are attached to the urls, and opening those urls displays an error msg: <Error> <script id="tinyhippos-injected"/> <Code>PermanentRedirect</Code> <Message> The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. </Message> <Bucket>mybucket-name-static</Bucket> <Endpoint>mybucket-name-static.s3.amazonaws.com</Endpoint> <RequestId>xdxdxxdxd</RequestId> <HostId> YmH2sBIsddvdrdSxrp8viWZBIoZFlfqUpp6YGJHgVkMH2Vh4AOZP9xeUoezJI0Y= </HostId> </Error> index.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static "favicons/favicon.ico" %}" type="image/x-icon"> <link rel="icon" href="{% static "favicons/favicon.ico" %}" type="image/x-icon"> <title>app</title> <link href="{% static "css/app.7759951d6d7e8ca6b5f586cdd9b55f3b.css" %}" rel=stylesheet> </head> <body> <div id="app"></div> <script type="application/javascript" src="{% static "js/manifest.862a9db37e07dc2a85b7.js" %}"></script> <script type="application/javascript" src="{% static "js/vendor.09e075a2fb63be36f883.js" %}"></script> <script type="application/javascript" src="{% static "js/app.f6fac1f9f25fe4014887.js" %}"></script> </body> </html> Could you please help me out. What … -
import DjangoREST+Geojango
my name is Gabriel Sansigolo. Last week I came across a little problem during the development of a project. The problem appeared when I needed to import a function from a class, which was in another folder. Capture_1: File Organization At first I thought it was wrong in the way I wrote import. Capture_2: The Error The source pointed to by the error was the urls.py file, as the image shows: Captura_3: urls.py It should be noted that PyCharm did not identify it as an error. After researching on the subject I noticed that many said that probably the problem was in the "INSTALLED_APPS" inside the settings.py file, thinking about it follow image of my installed apps Capture_4: Installed Apps This may be a trivial mistake in Django, but as I do not know much, I'm a beginner, I can not see the solution. Links of the prints: Capture_1: Capture_2: Capture_3: Capture_4: Thank for the space. regards, Gabriel -
Django REST Framework Foreign Key - cannot create object from JSON
I have following setup Models class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() paymentMethod = models.CharField(max_length = 200) class Reservation(models.Model): start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False) end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False) hasRefund = models.BooleanField(verbose_name='Возвратная бронь', default=True) room = models.ForeignKey('Room', verbose_name='Номер', on_delete=models.CASCADE) day = models.ManyToManyField(Day, blank=True) check_in_time = models.CharField(verbose_name='Время заезда', max_length=200) check_out_time = models.CharField(verbose_name='Время выезда', max_length=200) guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True) payed = models.BooleanField(verbose_name='Оплачено', default=False) class Room(models.Model): name = models.CharField(max_length = 200, null=True) Views class ReservationCreateAPIView(CreateAPIView): queryset = Reservation.objects.all() serializer_class = ReservationSerializer Serializers class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = [ 'date', 'price', 'paymentMethod', ] class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = [ 'pk', 'name', ] class ReservationSerializer(serializers.ModelSerializer): room = RoomSerializer day = DaySerializer(many=True) class Meta: model = Reservation fields = [ 'start', 'end', 'hasRefund', 'room', 'day', 'check_in_time', 'check_out_time', 'guest_name', 'payed', ] def create(self, validated_data): day_data = validated_data.pop('day') room_data = validated_data.pop('room') reservation = Reservation.objects.create(**validated_data) room = Room.objects.get_or_create(name=room_data['name']) reservation.room.add(room) for day in day_data: day, created = Day.objects.get_or_create(date=day['date'], price=day['price'], paymentMethod=day['paymentMethod']) reservation.day.add(day) return reservatrion Data, that I try to save { "start": "2017-12-12", "end": "2017-12-12", "hasRefund": false, "room": 2, "day": [ { "date": "2017-12-12", "price": "2", "paymentMethod": "3" }, { "date": "2017-12-12", "price": "2", "paymentMethod": "3" } ], "check_in_time": …