Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Native with python
I want to make program using python(Django) and React Native. And I have some questions about how to connect them. I want pass text that user will write to Django server. I have question how to do this? I know the method fetch() in React Native but I do not know how to pass exactly that data the user have written. If in fetch I will put link like this: 'http://example.com/?dataId={dataToPass}' but how then I can get exactly this data in Django? Please help me) -
SyntaxError:invalid syntax
I am trying to run server in terminal but it returns a syntax Error, am using Django This is the command response File "C:\Program Files\Python37\lib\site-packages\django\__init__.py", line 22 '/' if settings.FORCE_SCRIPT_NAME is not None force_text(settings.FORCE_SCRIPT_NAME) ^ SyntaxError: invalid syntax '/' if settings.FORCE_SCRIPT_NAME is not None force_text(settings.FORCE_SCRIPT_NAME) -
how to fix dynamic image tag in html
I am rendering an image tag in HTML and i got error like {% for events in events %} <div> <h2><a href="">{{ events.event_title }}</a></h2> <p>published: {{ events.event_release_date }}</p> <p>{{ events.event_description|linebreaksbr }}</p> <img src={{ events.event_title_image }} alt="diagram" " /> views def index(request): return render(request, 'polls/home.html', {}) "model class name and function name should not be samm" def Event(request): events=Events.objects.filter(event_release_date__lte=timezone.now()).order_by('event_release_date') return render(request, 'polls/events.html', {'events':events}) i expect image need to display in web page -
Django ORM Group By Date Range
I've got a Django Model where users can be assigned a status for a specific period, e.g. 'Absent' from 2019-10-01 to 2019-10-20: class Status(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='statuses') status = models.CharField(max_length=100, choices=status_choices) valid_from = models.DateField() valid_to = models.DateField() What I'm trying to calculate: the status for each user, for each week: Mr. A Week 1 Absent Mr. A Week 2 Present Mr. A Week 3 Present Mr. B Week 1 Absent Mr. B Week 2 Absent Mr. B Week 3 Present The only thing I can come up with, is to create a for loop and iterate over all the dates that I want to include: for date in dates: Status.objects.filter(valid_from__lte=date, valid_to__gt=date).values('user__username', 'status')[:1] But as one can imagine, it creates way too many queries.. anyone that knows a way to to this in a single ORM query? -
How can I use pagination when I am using a form to input a date and submitting that form sends a post request and pagination accepts get request?
I am using django to display a webpage. I want to display details of files from database. These files can be of any number. I am using a form to input a date from HTML file which is accepted by a django view function. This function checks if the request is of type POST and returns the data between the mentioned date. Now when I use pagination to display these pages, pressing the next doesn't show anything as this time the request gets changed to GET. In my django view function, data is fetched in a list. Every file's data is in a list. So, all the data consists lists of lists. How will I be able to display these lists using pagination without sending the requests again. Is it possible to do so? -
How to add custom permissions on GET,POST,PATCH,DELETE separately in function based view Django
I am working on a project which has several user types like Admin,coordinator,sub-coordinator and each user can work as a different role in different division. Eg. user A can be a coordinator in DIVISION XX then A can be a admin in DIVISION YY but he cannot have a same role in same division. I am planning to write custom permissions and roles for this. what I have written is something like this: def coordinator(request, uid): if request.method == 'GET': //some logic if request.method == 'POST': //some logic if request.method == 'PATCH': //some logic if request.method == 'DELETE': //some logic what i dont want to do is the below approach: def coordiantor_delete(request, uid): if request.method == 'DELETE': def coordiantor_detail(request, uid): if request.method == 'GET': def coordiantor_create(request): if request.method == 'POST': def coordiantor_update(request, uid): if request.method == 'PATCH': Is there a way to add permissions to specific HTTP methods of a view function without splitting it in various views. Because I only want to have one API endpoint like /coordinator/ and /coordinator/id/ which should support above HTTP methods but with permissions like admin can also delete coordinator from a division and a coordinator himself can also leave a division and no … -
Django channel - logged in but self.scope['user'] is AnonymousUser
I am trying to create a chatweb using django-channel. Right now i am doing the checking user online -offline. When i check the current user it is AnonymousUser. The routing for check user online-offline is localhost:8000/new_user/ In the routing i used AuthMiddlewareStack: source routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns, ) ), }) chat app routing from django.urls import re_path from django.urls import path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer), re_path("new_user/", consumers.NewUserConsumer), ] code consumer.py class NewUserConsumer(AsyncJsonWebsocketConsumer): async def connect(self): print('connect') user = self.scope['user'] print(user) # This print out AnonymousUser await self.accept() await self.channel_layer.group_add("users", self.channel_name) print(f"Add {self.channel_name} channel to users's group") user = self.scope['user'] if user.is_authenticated: await self.update_user_status(user, True) await self.send_status() async def receive_json(self, message): print("receive", message) async def disconnect(self, close_code): await self.channel_layer.group_discard("users", self.channel_name) print(f"Remove {self.channel_name} channel from users's group") user = self.scope['user'] if user.is_authenticated: await self.update_user_status(user, False) await self.send_status() async def send_status(self): users = User.objects.all() html_users = render_to_string("chat/new_user.html", {'users': users}) await self.channel_layer.group_send( 'users', { "type": "user_update", "event": "Change Status", "html_users": html_users } ) async def user_update(self, event): await self.send_json(event) print('user_update', event) @database_sync_to_async def update_user_status(self, user,status): return ChatUser.objects.filter(username_id=user.id).update(status=status) … -
Check if variable exists in template, without causing errors in loggers if it doesn't
I have enabled 'level': 'DEBUG' in LOGGING in settings.py. I'm aware that the proposed solutions to check if a variable exists is using the if template tag {% if variable %} This is proposed in the documentation and questions asking how to check if a variable exists are closed as off-topic and pointed in that direction. Another solution offered here is to compare with None. {$ if variable is not None %} however, in both cases, although it works fine on the user end, the logger saves that as a KeyError, cluttering my log files. How can I avoid this? -
How can I install drivers for MSSQL in CloudFoundry?
I am trying to host Django application on CloudFoundry. The application uses MSSQL in backend. After the application's state changes to "started", When I browse the URL I get ERROR: Exception Value: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)") I have followed a Solution for this error here: Pivotal/Django settings for user provided MSSQL database But, still not able to resolve this. The path is not getting set correctly for the driver. How can I resolve the error? -
Serve django media files locally in Development environment
I use Amazon S3 to store my media files in production using boto3 package, but I don't want to create a bucket for a local development environment. So I was wondering if there is a way to serve media files locally. My storage related settings: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('BUCKET_REGION') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/django_static/' STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT') MEDIA_URL = '/media/' if not USE_S3: MEDIA_URL = "http://localhost:8000" + MEDIA_URL MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In urls I added this: urlpatterns = [ # usual urls... ] if not settings.USE_S3: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It turns out that static method returns empty array if its first parameter has 'http' inside, meaning that I can not use it for serving from my server. If you have faced the same issue and solved it or you know where to look up the solution, plz let me know. -
Give style value from database django
I want to give my progress bar a value from the value that I saved in the my model, but I have a syntax error and don't know how to solve it. the status field is an intfield so when I print x.status outside the class progress-bar I get for example 10 {% for x in info %} <div class="progress mt-2"> <div class="progress-bar bg-warning" style='width:{{x.status}}%;'>In Progress</div> </div> {% endfor %} -
'>=' not supported between instances of 'NoneType' and 'float'
I want to run my code, however, I keep on getting error messages. It is about a form field in which they type in their value. If the value is within a specific range, they'll get 1 Euro. The code is: class Guess(Page): form_model = 'player' form_fields = ['guess'] def is_displayed(self): return self.round_number == 2 def vars_for_template(self): if self.player.guess >= 11.25 and self.player.guess <= 13.75: self.player.cumulative_guthaben = self.player.cumulative_guthaben + 1 else: self.player.cumulative_guthaben = self.player.cumulative_guthaben return { 'current_credit': self.player.cumulative_guthaben, 'anzahlspieler': Constants.number_of_players, 'round_number': self.round_number,} I do know that it is a type error, but I was not successful in fixing it -
Why form field didnt save correct?
I am trying to automatically convert the first character of the model form field to upper case, but the original value is saved. class TechnologyCreatePopup(CreateView): model = Technology form_class = TechnologycreateForm template_name = 'technology_create.html' def form_valid(self, form): """If the form is valid, save the associated model.""" self.object = form.save(commit=False) if form.cleaned_data['name'][0].isupper(): self.object.save() else: name = form.cleaned_data['name'] c_name = name[0].capitalize() + name[1:] print(c_name) ---> print me name with uppercase! form.cleaned_data['name'] = c_name self.object.save() return HttpResponse( '<script>opener.closePopup(window, "%s", "%s", "#id_technology");</script>' % (self.object.pk, self.object)) I also think that this is not a nice solution (I mean using slices, an additional variable and string concatenation). Maybe there is a more interesting way? -
Django rest framework: how to fetch a foreign key based on a specific field (= not id)
I have this relation that works perfectly. The only problem is that DRF filters TaskAppointmentState based on its pk (or id). I would like to filter on another field: not state. To be more precise, instead of doing instance.status_id = state.id in the following code, I would like to do this pseudo code instead: instance.status_id = "SELECT id FROM TaskAppointmentState WHERE state=request.GET['state'] class TaskAppointmentStateSerializer(BaseSerializer): class Meta: model = TaskAppointmentState class TaskAppointmentSerializer(BaseSerializer): owner = SerializerMethodField() performer = SerializerMethodField() state = TaskAppointmentStateSerializer(required=False) @staticmethod def get_owner(obj): return BaseSerializer.get_person_description(obj.owner, None) @staticmethod def get_performer(obj): return BaseSerializer.get_person_description(obj.performer, None) def update(self, instance, validated_data): try: state = validated_data.pop('state') instance.status_id = state.id raise Exception("WWWWWWOOOOOOOOOOOOOOOORKED") except KeyError: pass # ... plus any other fields you may want to update return instance class Meta: model = TaskAppointment fields = ['id', 'owner', 'performer', 'date_start', 'date_end', 'agenda', 'state'] read_only_fields = ['id', 'owner', 'performer', ] -
Execute function from view in Django
i need help with my django project. I am trying to open folder from django view and I came up with idea which will execute python script which will handle this part, because for some security reasons Chrome is not able to directly open file explorer (program). So I tried this. detail.html looks: <form class="form" method='post'> {% csrf_token %} <button style="width:100%;" type='explorer' name='explorer' value='explorer' class="btn btn-info btn-min-width"><i class="fa fa-folder"></i> Navigate to folder</button> </form> actions.py looks: def openexplorer(): return os.system('explorer') view.py looks: def detail(request, Pools_id): try: je = More.objects.get(pk=Pools_id) except More.DoesNotExist: raise Http404("Question does not exist") return render(request, 'rc/detail.html', {'more_identification': je}) if request.method == 'POST': if 'explorer' in request.POST: openexplorer() I am rendring the page and i only want to execute the script when the button is clicked. Can someone please help? I think there is some error in view.py. Thanks a lot ! -
Django queryset update migration
I'm trying to optimize a migration, it's taking too long, about 15 minutes every time you try to run it, because there is a lot of data on this table. It's an old database that have dates like this '14102019' (%d%m%Y) as String, and need to convert them to DateField. I created a DateField for both. Database is MySQL. dtobito and dtnasc are the old strings that need to be converted data_obito and data_nasc are the new DateFields What works (very slowly): def date_to_datefield(apps, schema_editor): Obitos = apps.get_model('core', 'Obitos') for obito in Obitos.objects.all(): if obito.dtnasc and obito.dtnasc != '': obito.data_nasc = datetime.strptime(obito.dtnasc, '%d%m%Y') if obito.dtobito and obito.dtobito != '': obito.data_obito = datetime.strptime(obito.dtobito, '%d%m%Y') obito.save() What doesn't work: Obitos.objects.update( data_nasc=datetime.strptime(F('dtnasc'), '%d%m%Y'), data_obito=datetime.strptime(F('dtobito'), '%d%m%Y') ) What could work, but I don't know how: Obitos.objects.raw(""" UPDATE obitos new, ( SELECT STR_TO_DATE(dtnasc, '%d%m%Y') AS dtnasc, STR_TO_DATE(dtobito, '%d%m%Y') AS dtobito, FROM obitos ) old SET new.data_nasc = old.dtnasc SET new.data_obtio = old.dtobito """) -
Django 2.2.4 unable to server my static files
In my application i was unable to server static files like images and js looks like everything is correct but still i am unable to figure out why it is not loading I have tried few options in stackoverflow none of them worked or me Settings.py STATICFILES_DIR = [ os.path.join(BASE_DIR, "static") ] STATIC_URL = '/static/' My project structure mydjangonginx |-mydjango_app | -urls.py | -views.py | -... |-mydjangonginx | -urls.py | -settings.py | -... |-static | -images | -login.jpg | -js | -my.js mydjango_app/urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('login', views.login, name='login'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) mydjangonginx/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('mydjango_app.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) login.html <html> {% load static %} login <script src="{% static 'js/my.js' %}"></script> <img src="{% static 'images/login.jpg' %}" /> </html> both the js and images are not loading can anyone help on this -
What did my pipenv disappear after python upgrade?
I had an existing project an everything was fine. As Heroku seemed to need a specific python runtime version for deployment, i upgraded python (windows 64) to 3.7.4 When running pipenv shell in my usual folder, i have this message : C:\Users\henry\Desktop\testldc>pipenv shell Creating a virtualenv for this project… Pipfile: C:\Users\henry\Desktop\testldc\Pipfile Using c:\users\henry\appdata\local\programs\python\python37\python.exe (3.7.4) to create virtualenv… [=== ] Creating virtual environment... but this message keeps running (up to 20 minutes)until it freezes ! I've tried to run pipenv shell on another previous project folder, and the problem is the same : installation i didn't ask for, and stuck during the installation. Thanks for your help ! I just wanted to run my usual virtual environment with a newer python version. -
How to query two models under a class view, get specific attributes associated with each models and compare one record against another
I have two models Job and Applicants, the Job model has an attribute years_of_experience and the Applicants model has an attribute applicant_experience. I want to get the applicants years of experience and compare it the required years of experience for each particular job, and return only those that meet the requirement under a view. models.py class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) years_of_experience = models.IntegerField(blank=True, null=True) class Applicants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) views.py class QualifiedApplicantPerJobView(ListView): model = Applicants template_name = 'qualified_applicants.html' context_object_name = 'applicants' paginate_by = 2 @method_decorator(login_required(login_url=reverse_lazy('login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def get_queryset(self): return Applicants.objects.filter(job_id=self.kwargs['job_id']).order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['job'] = Job.objects.get(id=self.kwargs['job_id']) return context applicants.html {% for applicant in applicants %} {% if applicant.experience >= job.years_of_experience %} <div class="col-lg-6"> <div class="box applicant"> <h4>{{ applicant.user.get_full_name }}</h4> <h4>{{ applicant.user.email }}</h4> </div> {% endif %} {% endfor %} I don't want to do it like this, I want to be able to do it in my views, get the number of qualified applicants(count) and return the qualified applicants. What is the best way to approach this. Thanks -
Not able to get the data selected form Django: ChoiceField
My application from an uploaded CSV file, reads header values and passes these headers into another class which extends Form. The goal is to get the selected value from the ChoiceField. The definition of selected is - current value displaying from the ChoiceField, should be considered selected. I am able to read the header values list. But when I am trying to print the selected choice field value expense_form.is_valid() returns False. My question is how could I get the selected data/value out from the ChoiceField. Python Version : 3.7.1, Django Version : 1.9.8 1.visualize_view.html {% extends 'base.html' %} {% block content %} {{ expense_form.as_p }} {% endblock %} 2.urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from uploads.core import views urlpatterns = [ url(r'^$', views.loginForm, name='loginForm'), url(r'^uploads/', views.simple_upload, name='simple_upload'), url(r'^admin/', admin.site.urls), url(r'^visualize_view/', views.visualize_view, name = 'visualize_view'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT) 3.view.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from uploads.core.models import Document from .forms import ExpenseForm def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() fs.save(myfile.name, myfile) return visualize_view(request, myfile) else: return render(request, 'core/simple_upload.html') def visualize_view(myfile): for row in … -
Can we define models.CASCADE only without using on_delete?
As I know is that when we defining foreign key in django we can set like on_delete=models.CASCADE. Recently I have seen code like content_type = models.ForeignKey(ContentType,models.CASCADE). My question is that does django allow to define models.CASCADE without using on_delete ? OR if we define like above does it work differently? content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) -
Generating JSON progress events from Django file upload
I'd like to display an upload status bar in my GUI when uploading a (large) file to my Django backend. My problem is that the 'onprogress' event appears only once when the upload is finished (both in the Django development server as well as in the Apache server (Windows). I suppose I have to code something that reports back a status message, but I seem to be unable to locate any hints at which point or how this could be implemented. Would be glad for any pointers where to start Currently I have this Javascript code: var data = new FormData(); data.append('localvideo',value) data.append('uploader',{% if request.user.id %}{{request.user.id}}{% else %}null{% endif %}) $.ajax({ type: "POST", contentType: false, processData: false, url: ajaxsnippetvideobaseurl, data: data, success: function (result) {ajaxfinished(); console.log(result); /*save(section,[result["id"]])*/}, error: function (result) {errorprofiles (result);}, xhrFields: { onprogress: function (e) { console.log(e)} } }); And this Django code: class VideoSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' class VideoSnippetViewSet(viewsets.ModelViewSet): queryset = VideoSnippet.objects.all().order_by('id') parser_classes = (MultiPartParser, FormParser) serializer_class =VideoSerializer -
DRF: Username still required after customizing Abstract User
I'm trying to write a REST API using Django and DRF. I'm trying to create a user model and use it in my application. But the problem is that it returns a 400 error status code which says: {"username":["This field is required."]} This is my code for models: import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings from django.dispatch import receiver from django.utils.encoding import python_2_unicode_compatible from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from api.fileupload.models import File @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) address = models.CharField('Address', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) The Serializer: class CreateUserSerializer(serializers.ModelSerializer): username = None def create(self, validated_data): validated_data['username'] = uuid.uuid4() user = User.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.phone_no = validated_data.get('phone_no', instance.phone_no) instance.email = validated_data.get('email', instance.email) instance.save() return instance class Meta: unique_together = ('email',) model = User fields = … -
Docker: execute django migration into a db container from inside of the web container
I run a CI pipeline in gitlab. The stage executes several steps: First I start db container: docker run --name db -p 5432:5432 \ -e DJANGO_SETTINGS_MODULE=<myapp>.settings.postgres -d postgres:9.6 Then I check if it worked: docker inspect db true Note that I specify a non-default settings file (which contains my db credentials) Now I build web container with Django 2.2 inside and feed it the DB credentials of the postgres container : docker build --pull -t test_image . --build-arg DB_NAME=<mydbname> --build-arg DB_HOST=db --build-arg DB_USER=<mydbuser>--build-arg DB_PASS=<mydbpassword> That runs Dockerfile sequence of may steps and at some point arives to DB migration: RUN python manage.py migrate --settings .settings.postgres That invariably chokes with this error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (127.0.0.1) and accepting TCP/IP connections on port 5432? Which means to me that the name I gave to the postgres container ("db") does not mean anything inside this (web) container. I checked the db redentials variables before "migrate" step (just printed with echo) - they all made it ok. How do I correctly run "python manage.py migrate " from inside of the build (Dockerfile) of web container AGAINST THE DB IN THE DB CONTAINER … -
Gunicorn no wsgi module
I'm following this tutorial this time: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 But I think it misses out a step, as I am unable to test the dev server is running using manage.py runserver 0.0.0.0:8000, but I never have before, so no biggie there, but I am unable to get gunicorn working as there is no wsgi.py module in my project. I assumed that this gets created by gunicorn itself. What do I have to do to get that working properly please?