Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is my api key auth secure solution in django?
Is this solution correct and secure? It works, but is it a correct way? Model (user is default from Django): class DataAPI(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) user_key = models.CharField(max_length=20, null=False) sec_key = models.CharField(max_length=20, null=False) When user wants to generate new DataAPI instance (user_key is always the same for user, sec_key is new): class APIView(View): def post(self, request, *args, **kwargs): from django.core.signing import Signer import string signer = Signer("yes") current_user = request.user dataAPI = DataAPI() dataAPI.user = current_user dataAPI.user_key = signer.sign(current_user.username).split(":")[1] string = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) dataAPI.sec_key = signer.sign(string).split(":")[1] dataAPI.save() return redirect('apikeys') And authentication as decorator with example APIView: def my_auth(func): def wrapper(_,request, *args, **kwargs): try: userkey = request.headers['userkey'] seckey = request.headers['seckey'] try: user = DataAPI.objects.get(user_key=userkey, sec_key=seckey).user # find user by his keys, if exception won't happend -> auth correct return func(_,request, *args, **kwargs) except Exception as e: print(e) return Response("Wrong data") except: return Response("Missing data") return wrapper class TestAutoDecorator(APIView): @my_auth def get(self, request, format=None): all_images = Image.objects.all().values() return JsonResponse({"image": list(all_images)}) And usage: -
Django | Does not filter questions using categories
Web that does not filter questions using categories. Where is the error? Thanks! template {% for categoria in categorias %} <a href="{{ url 'preguntas'}}/{{ categoria.id }}"><p>{{ categoria.categoriaEUS }}</p></a> {% endfor %} models.py class Pregunta(models.Model): categoria = models.ManyToManyField(Categoria, null=True, blank=True) textoES = models.TextField(null=True, blank=True) textoEUS = models.ManyToManyField(Euskara, null=True, blank=True) class Categoria(models.Model): categoriaES = models.CharField(max_length=50, null=True, blank=True) categoriaEUS = models.CharField(max_length=50, null=True, blank=True) views.py def pregunta_list(request,categoria_id): preguntas = Pregunta.objects.filter(categoria='categoria_id').order_by('id') paginator = Paginator(preguntas,1) page = request.GET.get('page') preguntas = paginator.get_page(page) return render(request, 'pregunta/pregunta.html', {'preguntas': preguntas}) def categoria_list(request): categorias = Categoria.objects.all() return render(request, 'pregunta/categoria.html', {'categorias': categorias}) urls.py path('', views.pregunta_list, name='preguntas/<int:pk>/', ), -
Why my javascript does not load in django template?
In my django project I'm using the adminlte 3 templates. All works perfectly, but I don't understand how can add a new javascript src in the template. Ad example I want to add to my project the following javascript source: <script src='http://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js'></script> <script src='https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js'</script> I have tried to add it in different place, but does not works nobody. Here the structure of my project: __base.html __script.html __app.html The base are the following: .... {% block javascript %} {% include 'adminlte/lib/_scripts.html' %} {% endblock %} Scripts are the following: {% load static %} {% block scripts %} <script src="{% static 'admin-lte/plugins/jquery/jquery.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/jquery-ui/jquery-ui.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/chart.js/Chart.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/bootstrap/js/bootstrap.bundle.min.js' %} "></script> {% block datatable_js %} {% endblock %} {% endblock %} And finlay I have the app.html: {% extends 'adminlte/base.html' %} {% load static %} {% load crispy_forms_tags %} {% include 'adminlte/lib/_main_sidebar.html' with active_menu_item=active_menu_item %} .... {% block content %} {% include 'adminlte/lib/_scripts.html' %} <table id="myTable" class="table table-sm"> {% endblock content %} {% block javascript %} <script> $(document).ready(function() { $('#myTable').DataTable( { "language": { "lengthMenu": "Visualizza _MENU_ records per page", "zeroRecords": "Nothing found - sorry", "info": "Showing page _PAGE_ of _PAGES_", "infoEmpty": "No records available", … -
Django REST validator. Multiple users can have records with same value, but that record is unique for each user, how to do that?
I am trying to accomplish the following with Django REST framework. I have model Records, which has field. It has foreign key to User. Each user can create multiple records with different numbers, but cannot create more than one record with the same number for themselves. However, each other user can create a record for itself with same number. E.g. Users Joe and Jill. Joe can create a record with number 123 only once, if he tries to make another record with 123, he should not be allowed. However Jill can create 123 once for herself, but not allowed more again. My guess is to create a validator inside the serializer, which is class RecordSerializer(serializers.HyperlinkedModelSerializer): '''Serializer for Record''' class Meta: model = Record fields = [ 'user', 'number', 'otherfield', ] validators = [ UniqueValidator( queryset= Record.objects.filter(user=<current user>), ) ] However, I cannot get the current user inside validator property, or how can I accomplish this otherwise? -
Django-Bootstrap - LIVE Feed, (without page refresh)
can someone please advise on a solution for providing a live news feed on w page that can update live, or to s set schedule, without requiring a page refresh? I am aggregating multiple news feeds via RSS into a database, and then providing a unified feed out to a news service. Ideally updating live, or every 5 minutes. I am using Python/Django/Bootsrap, so a solution that fits with these frameworks. Thanks in advance. -
Adding multiple slugs in one URL path in Django 3
I want to add multiple slugs in one URL path like this: path('<slug:firstslug>/<slug:secondslug>/<slug:thirdslug>/', views.mydetailview, name='detailview') I tried many ways but it didn't work. I want to use normal class based views. All slugs are coming from same model of the same app. -
How can we create asynchronous API in django?
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause. import time def wait(): time.sleep(10) return "ok" # views.py def api(request): return wait() I have tried celery for the same as follows where I am waiting for celery response in view itself: import time from celery import shared_task @shared_task def wait(): time.sleep(10) return "ok" # views.py def api(request): a = wait.delay() work = AsyncResult(a.id) while True: if work.ready(): return work.get(timeout=1) But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received? -
ImportError: The curl client requires the pycurl library Docker + Django
I'm dockerizing Django 2.2 application and using Pipenv for environment management. I want to use SQS as broker with Django celery. I have installed the pycurl library using Pipenv [packages] ... pycurl = "*" When I run celery locally pipenv run celery -A qcg worker -l info It works but when I run using docker image docker run app:latest celery -A qcg worker -l info It gives error ImportError: The curl client requires the pycurl library. The command in Docerkfile used to install dependencies RUN set -ex \ && BUILD_DEPS=" \ build-essential \ libpcre3-dev \ libpq-dev \ libcurl4-openssl-dev libssl-dev \ " \ && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ && export PYCURL_SSL_LIBRARY=nss \ && pipenv install --deploy --system \ \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $BUILD_DEPS \ && rm -rf /var/lib/apt/lists/* -
How to Display contents(str) of a dynamic list as a dropdown menu using Django
I want to display a dynamic list and another one after that based on the first one's selection (maybe something like a Dependent Dropdown) after a button is clicked. I have a button, whose onClick function activates a div where i want to display the Dropdown menu but i am not sure how to send the lists from the function in views.py. My views.py from django.shortcuts import render from .forms import sampleForm def get_Nodes(request): form = sampleForm() if request.method == 'POST': form = sampleForm(request.POST) send_list = ['sender1','Sender2'] #Size of the list is unknown send_uuid = ['ID1','ID2'] #List is created based on sender_list selection and also dynamic form2 = action(request.POST) tmp = { 'form': form, 'form2': form2, } return render(request, 'form.html', tmp) My forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Button class sampleForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( 'RDS', Button('submit', 'Submit', onclick="showDiv()") ) class listForm(forms.Form): #something may go here My template <body> <div id="form1"> {% csrf_token %} {% crispy form form.helper %} </div> <div id="form2" style="display: none;"> {% csrf_token %} {{ form2 }} </div> </body> <script> function showDiv(){ document.getElementById("form2").style.display = "block"; } </script> -
Long-polling once per second using Django and Celery
I am new to Celery, so please bear with me. My goal is to register a celery beat task from a Django view that would run forever once per second, so I have a code like this: my project structure: - proj -proj settings.py celery.py -app1 tasks.py views.py settings.py CELERY_BROKER_URL = 'redis://localhost:6379' BROKER_TRANSPORT = 'redis' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERYBEAT_SCHEDULE = {} celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from android_blend.settings import PROJECT_APPS os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('android_blend') app.config_from_object('django.conf:settings') app.autodiscover_tasks(PROJECT_APPS) In most importantly, in my views.py, I do something like this: from proj.celery import app def test_view(request): app.conf.beat_schedule = { 'add-every-second': { 'task': 'tasks.add', 'schedule': 1.0, 'args': (...) }, } ... I have my worker and beat jobs run, but I see nothing happen. Am I missing something fundemantal? The celery doc seems to be very bizarre and sketchy... -
how can i resolve django-admin is not recognized as internal or external command , operable program or batch file in atom ide terminal
I have tried activating my virtual environment on my atom terminal ,I tried to start a project when I got nmessage django-admin is not recognized as internal or external command , operable program or batch file. -
Fatal error: run() received nonzero return code 1 while executing! - TDD
Anyone ever experienced dealing with this error when trying to run the test ? Please see this link to understand where I am currently standing at: https://www.obeythetestinggoat.com/book/chapter_server_side_debugging.html I ran into this error below at multiple times when I ran the rest using test_my_lists against the staging server. "Fatal error: run() received nonzero return code 1 while executing!" After the above message is displayed, here's what it showed as: Requested: ~/sites/superlists-staging.bdienter... ~/sites/superlists-staging.bdienter... create_session edith@example.com Executed: /bin/bash -l -c "export DJANGO_DEBUG_FALSE=\"y\" SITENAME=\"superlists-staging.bdienter...\" DJANGO_SECRET_KEY=\"xxxxxxxxx" EMAIL_PASSWORD=\"xxxxxxx" YAHOO_PASSWORD=\"xxxxxxx\\$\" && ~/sites/superlists-staging.bdienter... ~/sites/superlists-staging.bdienter... create_session edith@example.com. It started aborting then this raised 'e' then performed SystemExit: 1.... Pls let me know if I have a SSH issue or am missing something else to get it to work. Thank you in advance for your help! -
How to access ForeignKey-Objects in Django
Every user in my Django project has a list of Reports. I now want to display the user his list of receipts. But how can I get all receipts which belong to a specific user? Report-Model from django.db import models from django.contrib.auth.models import User # Create your models here. class Report(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False) department = models.CharField(max_length=256, blank=False, null=False) workshop = models.CharField(max_length=256, blank=False, null=False) teacher = models.CharField(max_length=256, blank=False, null=False) hours = models.IntegerField(blank=True, null=False, default=4) date = models.DateField(blank=True, null=False) -
Django: field validator and UNIQUE constraint are not applyed
I have a Randomisation model with pat field that should be unique and have a specified format. I defined unique=true and and validators but neither are applyed For example, FRA-0001 sould be valid and if I try to registered this code twice it should raise an error validation message on my form (but not crash database). But currently, I can registered FRA for example and if I registered it twice I raise database error UNIQUE contraint failed models.py class Randomisation(models.Model): ... pat = models.CharField("Patient number", max_length=8, unique=True, null=True, blank=True, validators = [ RegexValidator( regex='^[A-Z]{3}-[0-9]{4}$', message= 'L\'identifiant doit être au format XXX-0000', code='invalid_participant_id' ), ], ) ... forms.py class RandomizationEditForm(forms.Form): def __init__(self, request, *args, **kwargs): super(RandomizationEditForm, self).__init__(*args, **kwargs) self.user_country = Pays.objects.get(pay_ide = request.session.get('user_country')) # self.language = request.session.get('language') # print(self.language) self.user_site_type = request.session.get('user_site_type') PAYS = Pays.options_list(self.user_country,self.user_site_type,'fr') SEXE = Thesaurus.options_list(2,'fr') STRATE_1 = Thesaurus.options_list(3,'fr') STRATE_2 = Thesaurus.options_list(4,'fr') YES = [(None,''),(0,'Non'),(1,'Oui'),] self.fields["pat"] = forms.CharField(label = "Numéro patient (XXX-0000)") self.fields['pat'].widget.attrs.update({ 'autocomplete': 'off' }) self.fields["ran_nai"] = forms.IntegerField(label = "Date de naissance (année)", widget=forms.TextInput) self.fields['ran_nai'].widget.attrs.update({ 'autocomplete': 'off' }) self.fields["ran_sex"] = forms.ChoiceField(label = "Sexe", widget=forms.Select, choices=SEXE) self.fields["ran_st1"] = forms.ChoiceField(label = "Gravité de la maladie COVID-19", widget=forms.Select, choices=STRATE_1) self.fields["ran_bug"] = forms.BooleanField(label = "Recours à la procédure de secours ?", required … -
I can't get Django-registration working with Custom user model
I'm a newbie to Django and I'm using django-registration because I like how it solves registration in two phases in a simple way. My drawback is that when modifying my model (User) I can't find a way to make the user registry work. I know I need to define a RegistrationForm but I can't get it to work. Thank you. models.py class Usuario(AbstractBaseUser): email = models.EmailField('email', max_length=254, unique=True, help_text="Email válido") username = models.CharField('username', max_length=100, unique=True, help_text="Username (i.e juan-perez)") first_name = models.CharField('nombre', max_length=200, blank=True, null=True, help_text="Nombres") last_name = models.CharField('apellido', max_length=200, blank=True, null=True, help_text="Apellido") date_joined = models.DateTimeField('fecha de alta', auto_now_add=True) last_login= models.DateTimeField('último login', auto_now=True) birth_date = models.DateTimeField('fecha de nacimiento', blank=True, null=True, help_text="Fecha de nacimiento: (DD/MM/AAAA)") country= models.CharField('país', max_length=50, blank=True, null=True, help_text="(i.e Argentina)") city= models.CharField('ciudad', max_length=50, blank=True, null=True, help_text="") is_admin= models.BooleanField(default=False) is_active= models.BooleanField(default=True) is_staff= models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'country'] forms.py class registroForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = Usuario urls.py urlpatterns = [ path('accounts/register/', RegistrationView.as_view(form_class=registroForm), name='django_registration_register',), path('accounts/', include('django_registration.backends.activation.urls')), ] -
Update newest row of database with same column value
I have a table like below: ------------------------------------------------------ | year | month | publish_date | status | -----------|-------------|---------------|-----------| | 2020 | 03 | datetime_obj | 0 | | 2020 | 03 | ... | 0 | | 2020 | 03 | ... | 0 | | 2020 | 03 | ... | 0 | | 2020 | 04 | ... | 0 | | 2020 | 04 | ... | 0 | ------------------------------------------------------ and i want update status for newest publish date in any year and month group but i dont have any idea for this for example : select all rows for 2020/03 and update stauts of newest publish_date to 1 and then do same operation for 2020/04 until the end ... i want use this in django so please explain with pythonic way or sql query thank you so much -
Return user's schedule
I'm trying to return the logged in user's schedule. I've tried overriding the get_queryset in the view but it's still returning all the rows. What am I doing wrong? Model: class Schedule(models.Model): plan = models.ForeignKey(Plan, related_name='schedule_plan', on_delete=models.CASCADE, default='0') user = models.ForeignKey(User, related_name='schedule_user', on_delete=models.CASCADE) startTime = models.DateTimeField() Serializer: class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = '__all__' View: class SelfScheduleViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAdminUser ] serializer_class = ScheduleSerializer def get_queryset(self): return Schedule.objects.all().filter(user=self.request.user) def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [permissions.IsAuthenticated] return [permission() for permission in permission_classes] -
Django, how to delete validation message from form?
I'm trying to set the layout of my inline formset. But If the form is not valid, django give me the following result: It's possible to delete the doble message and get only the one above the form? (in red color in the image). Here my forms: class RicaviForm(forms.ModelForm): class Meta: model = Ricavi fields = "__all__" def __init__(self, *args, **kwargs): super(RicaviForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False RicaviFormSet = inlineformset_factory( Informazioni_Generali, Ricavi, form=RicaviForm, fields="__all__", can_delete=True, extra=1 ) -
In Django, how do we access images located in an array?
I allow users to save multiple images when posting to a blog that is stored in a database. This works well, but I'd like to iterate through the images and display them on a different page, but there is no .url associated with lists. What would be a better method? def profile_detail(request, username): selected_id = User.objects.filter(username=username).first().id context = { 'selectedUser': User.objects.filter(username=username).first(), 'images': Post.objects.filter(user=selected_id).order_by('-timestamp'), # 'posts': User.objects.filter(username=username).first().id } return render(request, 'users/profile-detail.html', context) #TODO - Can't seem to produce an image#} {% for i in images %} {% for j in i.images %} {{ j.url }} <img src="{{ j.url }}"> {% endfor %} {% endfor %} -
Django AJAX: Access data from Dynamic multiple forms
Each form's input is associated with a unique data-comment-pk. I'm trying to access the value of data-comment-pk of the input which is submitted. Currently, the AJAX success function's alert(comment_pk) is only fetching me the comment_pk of the first form. How can I access the comment_pk of the form which is submitted instead of getting the comment_pk of the first form? html template {% for comment in object_list %} <h3>{{comment.comment}} by {{comment.username}}</h3> <form class="score-form"> <input type="submit" value="Up" name="up" class="Up" data-comment-pk="{{comment.pk}}" /> <input type="submit" value="Down" name="down" /> </form> {% endfor %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script> $(".score-form").submit(function (e) { e.preventDefault(); var comment_pk = $(".Up").attr("data-comment-pk"); var url = comment_pk + "/vote"; console.log(url) $.ajax({ type: 'GET', url: url, data: { "up": 'UP' }, success: function (response) { if (response["valid"]) { alert(comment_pk); } }, error: function (response) { console.log(response) } }) }) </script> models.py class CommentModel(VoteModel, models.Model): comment = models.TextField() username = models.ForeignKey(User, on_delete=models.CASCADE) views.py class CommentView(ListView): model = CommentModel def comment_vote(request, comment_id): if request.is_ajax and request.method == "GET": # do some stuff return JsonResponse({"valid": True}, status=200) -
Why don't I receive my Django Channels Websocket message on the frontend?
It is connecting just fine but I don't receive the message I want to send. The terminal just shows this WebSocket Connected WebSocket CONNECT /api/ [127.0.0.1:52360] WebSocket HANDSHAKING /api/ [127.0.0.1:52362] WebSocket Connected WebSocket CONNECT /api/ [127.0.0.1:52362] Here is the backend project repo : github.com/prateekamana/tempstack which means async def send isn't working. I also tried to change it to async def receive, still it doesn't work. -
How to programmatically store S3 images in Django
As noted in this previous question linked here, I am doing the reverse of saving images in Django that get uploaded to S3. The images already reside in S3 and I want to programmatically add the images to Django by creating media objects. Django storages S3 - Store existing file My class looks like this: class Media( models.Model ): asset_title = models.CharField( 'Title', max_length=255, help_text='The title of this asset.' ) image_file = models.ImageField( upload_to='upload/%Y/%m/%d/', blank=True ) In my view, I have this: bucket = s3.Bucket('my-bucket') for my_bucket_object in bucket.objects.filter(Prefix='media/upload/2020'): djfile = Media.objects.create(asset_title=my_bucket_object.key, image_file=my_bucket_object) I'm currently getting an AttributeError: 's3.ObjectSummary' object has no attribute '_committed' -
Django, Big integer and url
I was looking for the answer, but I couldn't find it. In PostgreSQL I have primary key, which is autofield which is BigInt type. In url path I have to reference it with something like "int:pk". If I use int for this purpose, will I fall in trouble later on, when numbers will exceed the limits of integer type? Which type I better use for bigint in url? It doesn't take BigInt or BigIntegerField, which are Django's type for bigint. Do I have to use patterns like <'$> instead of int? Thank you for the help! -
Django select option
I have a form which has a select field (your color). In front of the select field, I have a button that produces a popup which allows users to create new color before they submit. I am submitting that color form via Ajax. After adding a new color to the database, the popup closes. I want the newly added color to show in the select list without reloading the page. Is this possible? -
Django ORM: Retrieve first measurement from every day in big dataset
I have a Django project about temperature measurements. I'm using PostgreSQL as database backend. Let's say my model is: class TemperatureMeasurement(models.Model): time = models.DateTimeField(db_index=True) temperature = models.FloatField(null=False) I've taken measurements every minute for the last 6 months or so, meaning I have about ~270k rows in this table. I'm writing an API which should return the first temperature record for every day, for a given date range. I have something like this: def TemperatureBetween(APIView): # ... def get(self, request, *args, **kwargs): date_from = datetime.strptime(kwargs['date_from'], '%Y-%m-%d') date_to = datetime.strptime(kwargs['date_to'], '%Y-%m-%d') all_measurements = TemperatureMeasurement.objects.filter( time__gte=date_from, time__lt=date_to, ).order_by('time') r = [] current_day = date_from while current_day < date_to: day_measurement = all_measurements.filter( time__gte=current_day, ).first() r.append([day_measurement.time, day_measurement.temperature]) current_day += timedelta(hours=24) return Response(r) I'm aware that this approach if probably far from being optimal, because as I understand, I'm making at least as many database queries as days in the time range (that's also what Django Debug Toolbar tells me). I've read about Django's Q() objects, but I'm unsure about how I can use them in this case. I've thought something like: # ... query = Q() while current_day < date_to: query |= Q(time__gte=current_day).first() current_day += timedelta(hours=24) temperature_measurements = TemperatureMeasurement.objects.filter(query) # ... process data... But this …