Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why CreateView with ModelForm showing model fields twice
I have a question here I was looking to use django-summernote without forms but it seems Impossible, so I decided to use forms and when I read the Doc about "Form handling with class-based views" here it says : These generic views will automatically create a ModelForm I think because of this my fields are showing twice on my template (in admin it works greats) that because i made a ModelForm and generic view (CreateView) make another one! I want to know how to solve this my Models.py : from django.db import models from django.urls import reverse # Create your models here. class Game(models.Model): name = models.CharField(max_length=140) developer = models.CharField(max_length=140) game_trailer = models.CharField(max_length=300, default="No Trailer") game_story = models.TextField(default='No Story') my main urls.py : urlpatterns = [ path('games/', include('core.urls', namespace='core')), path('summernote/', include('django_summernote.urls')), ] my app(name=core) urls.py : from django.urls import path from . import views app_name = 'core' urlpatterns = [ path('new/', views.GameCreate.as_view(), name='game_new'), path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'), ] my views.py : class GameCreate(LoginRequiredMixin, CreateView): model = Game template_name = 'core/game_new.html' form_class = GameForm redirect_field_name = 'home' class GameUpdate(LoginRequiredMixin, UpdateView): model = Game template_name = 'core/game_edit.html' fields = '__all__' my forms.py : from django import forms from django_summernote.widgets import SummernoteWidget from core.models … -
Django rest framework writeable nested serializer data missing from validated_data
I'm trying to create a writeable nested serialiser for my API endpoint, however upon entering my parent serialiser's create method the nested data doesn't appear in my validated_data dictionary like it is supposed to in the example here. Instead, the nested key is not even present in the dictionary. Instead, it looks like: {'foo': 'bar'}. So, the nested keys appear to be flattened, and any other nested object with the same keys are overwritten. Any clues as to what the problem might be? I have some fairly complicated validation logic, however after trimming all of this out the problem wasn't recitified, so it appears to be irrelevant. My models are defined thus: class Payment(models.Model): id = models.AutoField(primary_key=True) foo = models.CharField(max_length=15, blank=True, null=True) class Booking(models.Model): id = models.AutoField(primary_key=True) payment = models.ForeignKey(Payment, blank=True, null=True) My serializers: class PaymentSerializer(serializers.ModelSerializer): class Meta: model = Payment fields = '__all__' class BookingSerializer(serializers.ModelSerializer): payment = PaymentSerializer(source='*', write_only=True) def create(self, validated_data): print("Creating booking", validated_data) # Outputs "Creating booking {'foo': 'bar'}" payment_data = validated_data.pop('payment') # Obviously errors at this point primary_guest = Payment.objects.create(**validated_data) booking = Booking.objects.create(**validated_data) # other creation related code return booking class Meta: fields = '__all__' My ViewSet: class PrebookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all().order_by('id') serializer_class = BookingSerializer My … -
Handle a request header in Django rest framework to get the secret key passed in the header and save it with User table?
I have a django backend for a mobile app. I'm using django rest framework (django-rest-auth), but I'm still writing my own views and logic because the API endpoints are not model based. The request sent to me has a secret key in the headers which is associated to individual devices registered. Along with it it has post data consisting of device id and other details. Once I get that header using request.META how can Save it in User model(It'll update everytime user login), so later it can be used as a foreign key to getting all the details like user and associated device. class CustomLoginView(LoginView): def get_response_serializer(self): if getattr(settings, 'REST_USE_JWT', False): response_serializer = JWTSerializer else: # print(self.request.data) response_serializer = serializers.TokenSerializer # response_serializer = {'data':response_serializer} return response_serializer def get_response(self): # raise APIException("There was a problem!") serializer_class = self.get_response_serializer() # print(serializer_class.data) try: if getattr(settings, 'REST_USE_JWT', False): data = { 'user': self.user, 'token': self.token } serializer = serializer_class(instance=data, context={'request': self.request}) else: print("hello") serializer = serializer_class(instance=self.token, context={'request': self.request}) print("BYE") print(serializer.data) # print(self.request.data) try: # print(serializer.data) if 'email' not in self.request.POST: return Response({'data':'message'}) return Response({'data':serializer.data,'status':1,'message':'Success'}, status=status.HTTP_200_OK) except ValidationError as exc: raise ValidationError({ 'field_val1': exc.detail, }) except: print("in except") raise APIException("There was a problem!") def post(self, … -
Modelar view para renderizar questões específicas de um quiz, de acordo com uma pk
Estou com algumas dúvidas na forma mais adequada de renderizar questões apenas de uma categoria especifica de um quiz. Tenho a seguinte modelagem: models: class Category(models.Model): title = models.CharField('título', max_length=50, unique=True) slug = models.SlugField() class Quiz(models.Model): STATUS_CHOICES = ( ('draft', 'Rascunho'), ('published', 'Publicado'), ('closed', 'Encerrado'), ) title = models.CharField('título', max_length=50) category = models.OneToOneField('Category', verbose_name='categoria', primary_key=True) questions = models.ManyToManyField('Question', verbose_name='questões', related_name='question_quiz') def get_questions(self): return "; ".join([a.title for a in self.questions.all()]) get_questions.short_description = 'Questões' def questions_count(self): return self.questions.count() class Question(models.Model): title = models.TextField('título', max_length=200) class Answer(models.Model): title = models.TextField('título', max_length=150) question = models.ForeignKey('Question', verbose_name='questão') correct = models.BooleanField('correta', default=False) incorrect = models.BooleanField('incorreta', default=True) views básicas: def quiz(request): global count count = 0 global progress progress = 1 global number_page number_page = 1 categories = Category.objects.order_by('title') return render(request, 'quiz/quiz.html', {'categories': categories}) def quiz_categories(request, slug_category): category = get_object_or_404(Category, slug=slug_category) quiz_list = Quiz.objects.all() questions_list = Question.objects.all() answers = Answer.objects.all() page = request.GET.get('page', 1) paginator = Paginator(questions_list, 1) try: questions = paginator.page(page) except PageNotAnInteger: questions = paginator.page(1) except EmptyPage: questions = paginator.page(paginator.num_pages) global count global progress parameter = request.GET.copy() if 'page' in parameter: del parameter['page'] context = { 'category': category, 'quiz_list': quiz_list, 'questions': questions, 'answers': answers, } return render(request, 'quiz/quiz_categories.html', context) def votes(request, slug_category, pk_question): question = … -
DRF: HTTP 401 logged at ERROR level. How to lower logging level?
I am trying to enable email alerts when HTTP 500 errors happens. Everything works fine, except that a Authentication credentials were not provided (HTTP 401) error is logged at ERROR level, which is way too verbose for email alerts. Also, I am using the django-request-logging module to print requests' content. Here is my logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'email_backend': 'django.core.mail.backends.smtp.EmailBackend', 'include_html': True, 'filters': [], 'formatter': 'simple' }, }, 'loggers': { 'django.request': { 'handlers': ['console', 'mail_admins'], 'level': 'DEBUG', 'propagate': False, }, }, } Any idea how I could filter out HTTP 401 from the mail_admins handler? -
Django Streaming HTTP Response from RESTful API
I have a Django app that needs to interact with a database of medical images. They have a RESTful API that returns a stream of bytes, which I am writing to a HttpStreamingResponse. This is working, but the issue is that it is very slow. Most files I am downloading are around 100mb, and it usually takes around 15-20 seconds before the download even begins. Does anyone have insight into how to speed up this process and start the download faster? Here is my code: # Make api call response = requests.get(url, cookies=dict(JSESSIONID=self.session_id)) # write bytes to Http Response http = StreamingHttpResponse(io.BytesIO(response.content), content_type='application/zip') http['Content-Disposition'] = 'attachment; filename="%s.zip"' % patient_id return http -
Can we authenticate user by username as well as email from username field in django?
I am using Django built-in authentication. A user can be login by username and password from django login form. But I want the user to be able to login with email id and password too. The login form has only username field. Can we use this login field to enter an email id or username and authenticate the user. This is my django login views class LoginForm(generic.CreateView): print("login") form_class = LoginForm template_name = "feed/SignUp.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): UserModel = get_user_model() username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('') else: print(form.errors) My idea is same as like we can log in to GitHub account either by username or by email. What should I do to achieve this? -
django 2 re_path expression passing email verification token
I'm quite stuck with using regular expression in django 2 url. All seems to be correct, however i'm getting 404 error. Actual path: http://localhost:8000/user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/ error: Using the URLconf defined in ec2django.urls, Django tried these URL patterns, in this order: user/ ^user/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='activate'] health/ ^static\/(?P<path>.*)$ The current path, user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/, didn't match any of these. urls.py urlpatterns = [ ..... re_path(r'^user/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', user_activate, name='activate') ] Generating the tokens: from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from django.contrib.auth.tokens import default_token_generator message = render_to_string('email_account_activate.html', { 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) Verification: try: uid = force_text(urlsafe_base64_decode(uidb64)) user = MyUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, MyUser.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): user.is_active = True user.save() Is the problem with the url or token format? Appreciate any help. -
Python: Where to put external packages?
I have a Django project that uses an external package that I haven't installed via pip in my virtualenv, rather I got it via git clone, and now I am wondering where to put it, and how the name of the folder should be. It's the Evernote Python3 SDK This is my current Django project structure: ➜ (venv:evernote) evernote_bear_project git:(master) tree . ├── README.md ├── bear2evernote │ ├── static │ └── templates ├── config │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── libs │ ├── evernote-sdk-python3 │ (omitted) │ └── utils │ ├── __init__.py │ └── file_utils.py └── manage.py I have put this package evernote-sdk-python3 in a folder called libs in my Django project folder. I also put utility functions in a package called utils beneath libs Now I know that there are many suggestions out there on how to structure your projects like these two: [1] Structuring Your Project — The Hitchhiker's Guide to Python [2] Python Application Layouts: A Reference – Real Python And I also know that Python does not force you to use a dogmatic folder structure. But nontheless: I don't have a solid understanding of packaging, package naming and package … -
Replacement for django `render_options`
So I am implementing this answer: Country/State/City dropdown menus inside the Django admin inline, but the def render piece of code needs to be redone.... I have managed to redo it, but I am struggling to find a replacement (or the correct code) for the self.render_options method (which was deprecated on 1.11) of the Widget class. I am on Django 2.1. What should I change? Here is my code: class StateChoiceWidget(widgets.Select): def render(self, name, value, attrs=None, renderer=None): self.choices = [(u"", u"---------")] if value is None: value = '' model_obj = self.form_instance.instance if model_obj and model_obj.country: for m in model_obj.country.state_set.all(): self.choices.append((m.id, smart_text(m))) else: obj = State.objects.get(id=value) for m in State.objects.filter(country=obj.country): self.choices.append((m.id, smart_text(m))) final_attrs = self.build_attrs(attrs) output = [u'<select%s>' % flatatt(final_attrs)] options = self.render_options(self.choices, [value]) if options: output.append(options) output.append('</select>') return mark_safe(u'\n'.join(output)) -
django rest framework 3.8.2 - getting data from request.data (POST)
I'm having troubles on retrieving data on posting a request: curl 'http://127.0.0.1:8005/api/curricula_report/v1/report-data/?format=json' -H 'Origin: https://ux.tribridge-amplifyhr.com' --data-binary '{"storesIds":[80403,66729,66996,67355,67393,67405,67406,67417,67439,67690,67713,67780,67851,68060,68082,68224,68305,68338,68414,68422,68437,68508,68513,68542,69004,69131,69516,69693,69845,69886,69887,69890,69954,69960,69976,70025,70102,70151,70166,70273,70334,70493,70512,70632,70696,70864,70991,71099,71415,71551,71572,71693,71926,71979,72478,72830,72846,72848,72872,72881,73202,73253,73326,73337,73363,73364,73382,73452,73463,73674,73683,73776,78997,73909,74666,73921,73989,77485,77538,77843,78135,77902,77833,78961,79238,80106,79239,79785,80914,81129,80800,81115,80520,80521,80801,81825,81659,82441,83128,74489],"courseIds":["3f8c8bd7-5aae-4184-a824-68edf528a011"],"audienceId":2,"hiredId":1,"user":"TW9oYW1tYWQ7UmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkQGRla2tncm91cC5jb207ZHVua2luYnJhbmRzOzIwMTgtMDctMDNUMTE6MjE6MzhaO0M3RDVCMUZEOUExN0RFNDEyNUVDODJBRTEzOTFEQ0E5N0M4Q0VFNUM"}' --compressed on inspecting the request through ipdb: def post(self, request, *args, **kwargs): post_data_dict = request.data user_token = post_data_dict.get('user', None) user is always None. ipdb> post_data_dict <QueryDict: {u'{"storesIds":[80403,66729,66996,67355,67393,67405,67406,67417,67439,67690,67713,67780,67851,68060,68082,68224,68305,68338,68414,68422,68437,68508,68513,68542,69004,69131,69516,69693,69845,69886,69887,69890,69954,69960,69976,70025,70102,70151,70166,70273,70334,70493,70512,70632,70696,70864,70991,71099,71415,71551,71572,71693,71926,71979,72478,72830,72846,72848,72872,72881,73202,73253,73326,73337,73363,73364,73382,73452,73463,73674,73683,73776,78997,73909,74666,73921,73989,77485,77538,77843,78135,77902,77833,78961,79238,80106,79239,79785,80914,81129,80800,81115,80520,80521,80801,81825,81659,82441,83128,74489],"courseIds":["3f8c8bd7-5aae-4184-a824-68edf528a011"],"audienceId":2,"hiredId":1,"user":"TW9oYW1tYWQ7UmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkQGRla2tncm91cC5jb207ZHVua2luYnJhbmRzOzIwMTgtMDctMDNUMTE6MjE6MzhaO0M3RDVCMUZEOUExN0RFNDEyNUVDODJBRTEzOTFEQ0E5N0M4Q0VFNUM"}': [u'']}> not sure what I'm doing wrong, all the keys seems to be omitted, and the values too: ipdb> post_data_dict.keys() [u'{"storesIds":[80403,66729,66996,67355,67393,67405,67406,67417,67439,67690,67713,67780,67851,68060,68082,68224,68305,68338,68414,68422,68437,68508,68513,68542,69004,69131,69516,69693,69845,69886,69887,69890,69954,69960,69976,70025,70102,70151,70166,70273,70334,70493,70512,70632,70696,70864,70991,71099,71415,71551,71572,71693,71926,71979,72478,72830,72846,72848,72872,72881,73202,73253,73326,73337,73363,73364,73382,73452,73463,73674,73683,73776,78997,73909,74666,73921,73989,77485,77538,77843,78135,77902,77833,78961,79238,80106,79239,79785,80914,81129,80800,81115,80520,80521,80801,81825,81659,82441,83128,74489],"courseIds":["3f8c8bd7-5aae-4184-a824-68edf528a011"],"audienceId":2,"hiredId":1,"user":"TW9oYW1tYWQ7UmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkcmhhbWFuO21vaGFtbWFkQGRla2tncm91cC5jb207ZHVua2luYnJhbmRzOzIwMTgtMDctMDNUMTE6MjE6MzhaO0M3RDVCMUZEOUExN0RFNDEyNUVDODJBRTEzOTFEQ0E5N0M4Q0VFNUM"}'] ipdb> post_data_dict.values() [u''] with rest_framework v 3.1.3 it was working. any help on this? -
Django: How to obtain current user in CreateView and filter a ForeignKey select field based on this
I am creating an expense submission system, which will be multi-user. For the purpose of this question, there are two models: Claim and Journey. A user creates a claim and each claim can have multiple journeys. I have made a gist of the code snippet as it's quite long. In this snippet, I have sucessfully: Made ClaimListView.get_queryset filter by current user, so whoever's logged in can only see a list of their own claims. Made ClaimCreateView.form_valid set the correct user when the form is submitted. Made ClaimDetailView.get_queryset filter by current user. If someone tries the url for another user's claim detail, they get a 404 (perfect!) Done the same as above for JourneyListView Done the same as above for JourneyDetailView - again 404 if not authroised :D However, when I access JourneyCreateView via the URL, the dropdown box for claim still shows claims for the other users. How should I filter the user within the JourneyCreateView class, so that the claim field only shows claims assigned to said user? The closest to a solution I've got is this answer which suggests overriding the __init__ function in the JourneyForm which would leave me with this: class JourneyForm(forms.ModelForm): class Meta: model = … -
How can I develop dynamic form field(image upload or text entry) in django admin panel?
I am developing an online quiz application. Some of question has image chocies(options), some of them are text. Moreover, In some questions, an explanatory image can be found before the question title. Therefore, While adding questions in the admin panel, If the user chooses the visual question type, the image loading areas will be shown(as A-B-C-D choices separately) next to the option textbox, in the other case users will write choices in textboxs. How can I make and implement this model? My current Question model; TYPE_CHOICES = ( ('WRITTEN', 'Yazılı'), ('VISUAL', 'Görsel'),) class Question(models.Model): OPTION_CHOICES = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D') ) DIFFICULTY_CHOICES = ( ('Zor', 'Zor'), ('Orta', 'Orta'), ('Kolay', 'Kolay') ) title = models.CharField(max_length=500, help_text='Soru başlığı giriniz') type = models.CharField( max_length=10, choices=TYPE_CHOICES, default='WRITTEN', help_text='Soru tipini seçiniz' ) correct_answer = models.CharField( max_length=10, choices=OPTION_CHOICES, default='A', help_text='Doğru cevabı seçiniz' ) section = models.ForeignKey(Section, on_delete=models.CASCADE,default=None) difficulty_level = models.CharField( max_length=10, choices=DIFFICULTY_CHOICES, default='Zor', help_text='Zorluk derecesini seçiniz' ) datetime = models.DateTimeField( default=timezone.now) admin model visual description is here Thanks. -
scrollNice plugin isnt working with django webpages
I am using niceScroll plugin to have a nice scroll on my website. I am using Django in the backend and I am encountering a problem with the scrollbar. it works on the home page only and not on the other pages. here is my base.html page <body> {% include "header.html" %} {% block content %} {% endblock content %} <script src="{% static 'js/jquery-3.1.1.min.js' %}"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="{% static 'js/code.js' %}"> </script> <script src="{% static 'js/jquery.nicescroll.min.js' %}"> </script> </body> code.js $(function() { $("html").niceScroll(); }); home.html // I am satisfied with the scrollbar {% extends "base.html" %} {% block content %} <div class="container "> <p>fdfdfdfdffdffffffffffffffffffffffffffffffffffffffffffff</p> <!--a lot of p tags for now -> </div> {% endblock content %} anyotherPage.html // i am getting the normal scrollbar {% extends "base.html" %} {% block content %} <div class="container "> <p>fdfdfdfdffdffffffffffffffffffffffffffffffffffffffffffff</p> <!--a lot of p tags for now -> </div> {% endblock content %} not sure if this will help but i will try to keep it short mywebsite urls.py path('' , TemplateView.as_view(template_name="home.html") , name="home"), path('files/', include((files_urls , "files") , namespace="files" )), files urls.py path('contact-us/' , contact , name="contact" ), -
Django Internationalization and localization instead of /en use a specific domain for each language
i have 3 domains, which will be one website, just that each one will serve a language ej: drenglish.com for 'en' drspanish.com for 'es_ES' drportugueses for 'pt_BR' automatically Internationalization and localization works with /lang added to the urls, but i dont want that i tried transurlvania but cant figure it out, is there an easy way to use my translated po file and tie it to a domain ? site framework seem to maybe be the answer, but i get lost when they tell to create different settings and urls files for each domain so you can add the right SITE_ID i am starting to use i18n for the internationalization and localization settings; middleware: 'django.contrib.sites.middleware.CurrentSiteMiddleware' USE_I18N = True #drspanish.com = ID 5 #drportugueses = ID 4 #drenglish.com = ID 1 SITE_ID = 1 from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('pt_BR', _('Portuguese')), ('es_ES', _('Spanish')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) urls(main); from django.conf.urls.i18n import i18n_patterns urlpatterns = [ #urls for english + global path('admin/', admin.site.urls), path('users/', include('users.urls')), #for allauth path('accounts/', include('allauth.urls')), #for allauth url(r'^ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # comment out this line from the +... if the website is live, its only to serve … -
Django ImageField not render at <img> tag HTML
# models.py from django.db import models from . import constants class Photos(models.Model): band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE) photo = models.ImageField(upload_to='media/') photo_description = models.TextField(max_length=400) class Photos(models.Model): band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE) photo = models.ImageField(upload_to='media/') photo_description = models.TextField(max_length=400) @property def photo_url(self): if self.photo and hasattr(self.photo, 'url'): return self.photo.url # views.py def member_photos(request,member_id): current_member = BandMember.objects.get(pk=member_id) photos = current_member.photos_set.all() context = { 'all_photos': photos, 'current_member': current_member, } return render(request,'band_members/member_photos.html', context) html file : {% if all_photos %} {% for foto in all_photos %} <img class"" src="{{ foto.photo_url }}" alt = {{foto.photo_url }}"> <h5>{{ foto.photo_description }}</h5> {% endfor %} Although , image is not displayed , alt displays the correct path of the file What am i doing wrong ? What i'm trying to achieve , is when user clicks on a 'SHOW PHOTOS' button at a page containing informations about a specific band member (site/band_member/member_id here ), another page loads (site/band_member/member_id/photos) , displaying all the photos of the current member. NEW TO DJANGO !!! Thank you ! sorry for my 'bad english' language :) -
Django annotate on property field
I'm using Django 2.0 and Django REST Framework I have a model like below. class Contact(models.Model): first_name = models.CharField(max_length=100) class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') @property def total_payable(self): return self.amount @property def amount_due(self): returned_amount = 0 for returned in self.amountreturned_set.all(): returned_amount += returned.amount return self.total_payable - returned_amount class AmountReturned(models.Model): amount_given = models.ForeignKey(AmountGiven, on_delete=models.CASCADE) amount = models.FloadField() I have to get the top 10 contacts of the amount given and due respectively. In my view, I'm filtering data like @api_view(http_method_names=['GET']) def top_ten(request): filter_type = request.query_params.get('type', None) if filter_type == 'due': # query for due type elif filter_type == 'given': qs = Contact.objects.filter( user=request.user ).values('id').annotate( amount_given=Sum('amountgiven__amount') ).order_by( '-amount_given' )[:10] graph_data = [] for q in qs: d = {} contact = Contact.objects.get(pk=q['id']) d['contact'] = contact.full_name if contact else 'Unknown' d['value'] = q['amount_given'] graph_data.append(d) return Response(graph_data) else: raise NotFound('No data found for given filter type') the type query can be due or given. The code for given type is working fine as all fields are in the database. But how can I filter based on the virtual field for due type? What I have to do is to annotate Sum of amount_due property group by contact. -
Python: Referenced before assignment
I receive the following error local variable 'ticket_reservation_expired' referenced before assignment. Anyone knows how to resolve this? I think a solution could be to assign ticket_reservation_expired = ""before calling the function, but I wonder if that is the best way to resolve this? helpers.py def ticket_reservation_expired(request, timestamp_of_reservation): """ * Calculate the latest possible time where tickets are still reserved. * Check that 'created' timestamp of reservation item is not expired. * If expired, error message is being generated and redirect occurs. """ latest_time_before_expired = timezone.now() - timedelta( minutes=settings.MINUTES_TICKET_RESERVATION ) if timestamp_of_reservation < latest_time_before_expired: messages.add_message( request, messages.ERROR, _("Ticket reservation is too far in the past.") ) return True views.py ticket_reservation_expired = ticket_reservation_expired( self.timestamp_of_reservation ) if ticket_reservation_expired: return redirect( 'events:detail', organizer=self.organizer, event=self.event, ) -
Django ModuleNotFoundError: No module named (from Python Crash Course Ch 18)
I am studying from Python Crash Course, and I'm on chapter 18 - Web Application. On terminal, I set the virtual environment using virtualenv ll_env --python=python3 so that it's python3 specific (as said in the book). Then I activated it using source ll_env/bin/activate, and installed Django 2.1.1, which goes well with python3 or so I read. So starting the project with django-admin.py startproject learning_log . works fine, and all the necessary files and folders are there. But when I do python manage.py migrate, I get an error: File "/Users/dk/Desktop/Web_Application/learning_log/ll_env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named'/Users/dk/Desktop/Web_Application/learning_log/settings' I've tried almost everything... Could anyone help me out on this? -
django models - instance method to check if a model with matching attributes already exists in database
I am using django 2.0.8 and Python 3.5 in a project. I want to write an instance method on class Foo that checks to ensure that a "similar record" (i.e. same attributes) does not exist in the database. I am aware that I could use R.I (referential integrity) rules in the DB, to enforce this, but I want to push this responsibility to the model, not the DB layer. Here is the relevant portion of my code: class Foo(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # Model specific fields user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, on_delete = models.CASCADE) def is_available(self): temp = models.Manager().get_queryset().filter(content_type=self.content_type, object_id=self.object_id, user=self.user) res = (temp is None) del(temp) return res My question is how to correctly implement the instance method is_available(). As it currently stands, when I invoke that method, I get the following error message: AttributeError: 'NoneType' object has no attribute '_meta' -
Django source language and default language code
I have a django app, where code and template strings initially were in polish. Now I want to add english language and set it as a default. I use localeMiddleware and i18n patterns. When in settings.py I have: LANGUAGE_CODE = 'pl' LANGUAGES = ( ('pl', _('Polski')), ('en', _('English')), ) If works fine - my urls are automatically prefixes with 'pl', when I change it to 'en' website is translated to english. But, because I want my default language to be english (so visitors from China/wherever can see website in english) I have to change LANGUAGE_CODE to 'en'. However, if I do so, website is in english, default url prefix is 'en' but even when I change it to 'pl' it is being ignored, and website is still in english. I know that default language should be the same as "source" language as in code and templates - but maybe there is another/better solution then replacing all strings in all my views and templates? My middleware: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'core.middleware.SubdomainMiddleware', 'corsheaders.middleware.CorsMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] my urls.py: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), # path('api/', include('api.urls', namespace='api')), path('backoffice/', decorator_include([login_required, ], (backoffice_urlpatterns, 'backoffice'))), path('', include('web.urls', namespace='web')), … -
Live Search in Django
I am working on a Django application that requires the implementation of live search i.e. filtering and displaying the search result every time the form input is changed. For example: Consider I wanted to search my database for books when a book "name" is provided. Now, I want to suggest books which has a "name" similar to the "name" provided as input. And, I want these suggestions to be live - every time the input field for "name" is changed, my application should provide new and more accurate suggestions. How should I go about doing that? I have two solutions in mind. Solution - 1 Use jQuery and do AJAX calls to fetch new suggestions, every time the content of the input field for "name" is changed. Solution - 2 Fetch all the books available in the database and store it in a JS array and then use this array to provide suggestions. I think solution - 2 would not be feasible for large databases as we will not able to create arrays of such large sizes. So, solution - 1 is the only option left for large databases. Or are there any other ways to implement this "live search" … -
Run a command, after return, python
I have come across this issue, where I want to return something and call another function afterwards (in python) heres my current code: def new_user(request): '''Takes a request and enters it in the database IF that wallet id is not in the database! ''' data = request.body if data != '': user_info = eval(data) if type(user_info) != type({}): ... more code here ... send_email(vCode) return HttpResponse(response) I want to call send_email after returning a response. I have tried a few things here: -calling both new_user and send_email in another function but I need to return some sort of HttpResponse (so I can't call new_user without returning it...) so this does not work - tried to yield a request, cannot call another function after yield -tried threading, had a similar issue -Currently trying asyncio but i'm running into issues with that aswell, is there anything else I can do? -
Django - accessing app settings in another app
I am very new to Django so this might be a basic question but I am not able to find how to implement it. So I have an app in my Django project, lets call it player. In the apps.py I want to add some settings that are specific to this app. So the code is like: from django.apps import AppConfig class PlayerConfig(AppConfig): name = 'player' player_key = 'GJHGJGJJKJK' Now I have another app named engine. This has a serializer.py in which I want to create to create a player_engine and pass the player.player_key to it. so my serializer has a piece of code that looks like this: from engines import player_engine class EngineSerializer(serializers.ModelSerializer): class Meta: # some meta configuration values here ... def validate(self, data) player_engine = PlayerEngine(player.player_key) #in above method, I want to know to pass player.player_key ... I know there might be better way to structure this etc, however this is a legacy Django implementation and I cannot restructure things, so I would really appreciate if anyone can point me to a solution keeping this structure intact. Ideally I want to know if there is way app level settings can somehow be clubbed into the settings available … -
Ordering in get_list_or_404 in Django
I am making a query in Django, which consists in an array of product Ids in a nonarbitrary order, and a list of the products which correspond to these Ids: product_ids= [109, 33, 76, 332, 112] products_inventory = get_list_or_404(Products, id__in=product_ids) The query works fine. However, products_inventory doesn't have necessary the same order than the elements defined by product_ids (namely, the first element in products_inventory is not the one with id:109). How can I get the same order in products_inventory which is defined by the product_ids ?