Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I don't care about milliseconds, what is the most stable server setup for Django on a small server?
I have a personal open source project for a website that will handle important quantity of medicine related metadata. I dont think that there will be a hudge trafic because the topic is very specialized but the site will handle complicated researchs in scientific publications using several external APIs. I don't care about miliseconds. I want something very stable. It will write on external databases and I don't want it to stop in the middle of the process. Also, I don't want to spend my free time in server maintenance. My VPS is quite small. 1 VCore, 4GB of RAM. I was thinking about NGINX + uWSGI because uWSGI is self healing (they say...) but I also heard that Gunicorn would consume less RAM. Also, I'm not 100% sure for NGINX as Apache seems to be very stable. I'm new to this and a bit lost in the "They says". Is there something I can rely one to get a stable setup ? -
how can i add message on clicking logout in Class Based auth LogoutView
I am using Django's Default logoutview , i want to know how can i add a message on homepage when user clicks on logout(user is logged out and redirected to homepage on clicking logout). -
React-Redux action fails with Axios
My app fails with an error message of "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at eval (listings.js:69)". When I make a get request to the same URL with Postman it works fine. According to my redux dev tools the "LISTINGS_LOADED" action is called and after that the error happens. The line number 69 is the one with the "returnErrors" function. I'm using a django REST API. # listings.js // Get listing by id export const getListingById = id => dispatch => { dispatch({ type: LISTINGS_LOADING }); axios .get(`/api/listings/${id}`) .then(res => { dispatch({ type: LISTINGS_LOADED, data: res.data }); }) .catch(err => { dispatch(returnErrors(err.response.data, err.response.status)); # this is the line number 69 dispatch({ type: LISTINGS_ERROR }); }); }; # messages.js // Return errors export const returnErrors = (msg, status) => { return { type: GET_ERRORS, data: { msg, status } }; }; # serializers.py class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = '__all__' # api.py class ListingViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) serializer_class = ListingSerializer queryset = Listing.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) # urls.py router = routers.DefaultRouter() router.register('api/listings', ListingViewSet, 'listings') router.register('api/mylistings', MyListingViewSet, 'mylistings') urlpatterns = router.urls -
Correct django.conf file for apache server for django wsgi production
I am able to run sudo systemctl start httpd without any errors but it doesn't show anything when i go the the url in the browser and i'm hoping it has something to do with the way i configure my django.conf file My file structure home βββ user βββ projects βββ myapp βββ app β βββ <All Code for Webapp including static dir> βββ env (virtualenv) βββ manage.py βββ new β βββ settings.py β βββ urls.py β βββ wsgi.py βββ requirements.txt And i hoping someone can see a mistake in my django.conf located in my further down in my httpd folder. And hoping these are the endpoints i'm looking for django.conf Alias /static /home/user/projects/myapp/app/static <Directory /home/user/projects/myapp/app/static> Require all granted </Directory> <Directory /home/user/projects/myapp/new> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/home/user/projects/myapp:/home/user/projects/app/env/lib/python3.6/site-packages WSGIProcessGroup myapp WSGIScriptAlias / /home/user/projects/myapp/new/wsgi.py I'm not sure if these are pointing to all the right places and was hoping someone could give me a second look. And i havent touched wsgi.py and was wondering if i am missing any logic there. my wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new.settings') application = get_wsgi_application() Like i said the server runs with no errors but i am getting β¦ -
MySQL query: how write in Django?
I'm a beginner in Django: how can I write this mysql query for combine different tables? (SELECT "fatture_produzione" as tab, id, numero, data, iva, totale, azienda_id as azienda, id_fornitori_id as fornitori FROM fatture_fatture_produzione) UNION (SELECT "fatture_fornitori" as tab, id, numero, data, iva, totale, azienda_id as azienda, fornitori_diversi_id as fornitori FROM fatture_fatture_fornitori) UNION (SELECT "fatture_professionisti" as tab, id, numero, data, iva, totale, azienda_id as azienda, professionisti_id as fornitori FROM fatture_fatture_professionisti) order by data I try this in my view: fatture_fornitori_var = fatture_fornitori.objects.values( id='id', data='data', numero='numero', totale='totale', iva='iva', azienda='azienda_id', fornitori='fornitori_diversi_id').filter(azienda_id=azienda).order_by("data") fatture_professionisti_var = fatture_professionisti.values(id='id', data='data', numero='numero', totale='totale', iva='iva', azienda='azienda_id', fornitori='professionisti_id').objects.filter(azienda_id=azienda ).order_by("data") fatture_produzione_var = fatture_produzione,values(id='id', data='data', numero='numero', totale='totale', iva='iva', azienda='azienda_id', fornitori='id_fornitori_id').objects.filter(azienda_id=azienda).order_by("data") And... with itertools: fatture_dare = sorted( chain(fatture_fornitori_var, fatture_professionisti_var, fatture_produzione_var), key=attrgetter('data')) but I can't output in template: {% for fattura in fatture_dare %} <tr role="row" class="odd"> <td><nobr>{{ fattura.data|date:"d-m-Y" }}</nobr></td> <td>{{fattura.azienda}}</td> <td>{{fattura.numero}}</td> </tr> {% endfor %} Thank you! -
Error in manage.py script when running cron job for django inside docker container
I have a docker container runnning a django application that is also running a cron job inside it. The managed command keeps failing due to this error: Line 14 in manage.py line 14 ) from exc ^ SyntaxError: invalid syntax My cron job looks like this: 0 1 * * 1-5 python manage.py myCommand I tried changing it to this to see if that would do the trick: 0 1 * * 1-5 /usr/local/bin/python /absolute/path/to/project/manage.py myCommand -
Is there any widgets available for `DurationField` in Django?
I want DurationField 's widget for admin site. In below PromoCode class have DurationField namely duration. But in admin it shows TextInput as input. Is there any widgets available? class PromoCode(models.Model): """ Promo Code model to maintain offers """ code = models.CharField(_("Code"), max_length=60, help_text="Promo code") # Validations and constraints for promo code start_date = models.DateField(_("Start date"), null=True, blank=True, help_text="Start date of promo code offer") end_date = models.DateField(_("End date"), null=True, blank=True, help_text="End date of promo code offer") duration = models.DurationField(_("Duration"), null=True, blank=True, help_text="Validity period of promo code") ... ... admin.py class PromoCodeAdmin(admin.ModelAdmin): """ Model admin for promocodes """ list_display = ('code', 'description', 'start_date', 'end_date',) fields = ( 'code', 'description', 'discount', 'start_date', 'end_date', 'duration', 'sitewide_countdown', 'user_countdown', 'coin_currencies', 'fiat_currencies',) Below image is just for reference, duration field is not in human readable format. What is best way to make it easy? -
web real time analytics dashboard: which technologies should use? (node/django, cassandra/mongodb...)
we want to develop a dashboard to analyze geoespatial data. This is a small and close approach to what we want to do: http://adilmoujahid.com/images/data-viz-talkingdata.gif Our main concerns are about the backend technologies to be used. (front will be D3.js, DC.js, leaflet.js...) Between django and node.js, we think that we will use node.js, cause we've read than its faster than django for this kind of tasks. But we are not sure and we are open to ideas. But about Mongo or Cassandra, we are so confussed. Our data is mostly structured, so store it in tables like Cassandra would make it easy to manage, also Cassandra seems to have better performance. However, we also have IoT devices data, with lots of real time GPS location... Which suggestions can you give to us to achieve our goal? TL;DR Summary; Dashboard with hundreds of simultaneous users. Stored data will be mostly structured text/numbers, but will include also images, GPS-arrays, IoT sensors, geographical data (vector-polygons & rasters) Databases will receive high write load coming from sensors. Dashboard performance is so important. Its more important to read data in eral time, than keeping it uncorrupted/secure. Most calculus/math will be calculated in client's browser, the server β¦ -
pipenv --system option for docker. What is the suggested way to get all the python packages in docker
I use pipenv for my django app. $ mkdir djangoapp && cd djangoapp $ pipenv install django==2.1 $ pipenv shell (djangoapp) $ django-admin startproject example_project . (djangoapp) $ python manage.py runserver Now i am shifting to docker environment. As per my understanding pipenv only installs packages inside a virtualenv You don't need a virtual env inside a container, docket container IS a virtual environment in itself. Later after going through many Dockerfile 's i found --system option to install in the system. For example the following i found: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ COPY ./Pipfile /usr/src/app/Pipfile RUN pipenv install --skip-lock --system --dev https://hub.docker.com/r/kennethreitz/pipenv/dockerfile # -- Install dependencies: ONBUILD RUN set -ex && pipenv install --deploy --system https://wsvincent.com/beginners-guide-to-docker/ # Set work directory WORKDIR /code # Copy Pipfile COPY Pipfile /code # Install dependencies RUN pip install pipenv RUN pipenv install --system So --system is only sufficient or --deploy --system is better way. And --skip-lock --system --dev which is different again. So can some one guide how to get my environment back in my Docker -
Django Errors in terminal
I'm running Django 2.17 and I get many many errors from the dev server, the terminal prints this error 5 or six times on every requestx to the dev server. Trying to add --verbosity 0 to the runserver command does not supress them. I want to print from functions in views, but I don't need the errors from django. Someone on the django IRC channel told me that they were normal... but it looks as if something is not configured correctly to me. During handling of the above exception, another exception occurred: Traceback (most recent call last): Traceback (most recent call last): File "c:\python\Lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "c:\python\Lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "c:\python\Lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\python\Lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\python\Lib\socketserver.py", line 717, in __init__ self.handle() File "c:\python\Lib\socketserver.py", line 717, in __init__ self.handle() File "C:\Python\virtualenvs\tools\lib\site-packages\django\core\servers\basehttp.py", line 151, in handle self.handle_one_request() File "C:\Python\virtualenvs\tools\lib\site-packages\django\core\servers\basehttp.py", line 153, in handle self.handle_one_request() File "C:\Python\virtualenvs\tools\lib\site-packages\django\core\servers\basehttp.py", line 176, in handle_one_request handler.run(self.server.get_app()) File "C:\Python\virtualenvs\tools\lib\site-packages\django\core\servers\basehttp.py", line 176, in handle_one_request handler.run(self.server.get_app()) File "c:\python\Lib\wsgiref\handlers.py", line 144, in run self.close() File "c:\python\Lib\wsgiref\handlers.py", line 144, in run self.close() File "c:\python\Lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], β¦ -
Django: Find all values in a ManyToMany relationship where all elements of the related set match certain criteria
I have two models in a ManyToMany relationship. I want to get a subset of the first model for which every related model matches certain criteria. Scenario: This is for a collaborative dictionary. A Word may have 0 or more Definitions. A Definition may be in a number of states: "complete", "in progress" or "abandoned". I am interested in finding all Words which have either no Definitions or only have "abandoned" Definitions. class DefinitionState(Enum): COMPLETE = 0 IN_PROGRESS = 1 ABANDONED = 2 class Definition(models.Model): text = models.TextField() status = models.IntegerField() class Word(models.Model): text = models.CharField(length=60) definitions = models.ManyToManyField(Definition, related="words") spam = Word.objects.create(text="spam") eggs = Word.objects.create(text="eggs") bacon = Word.objects.create(text="bacon") lobster = Word.objects.create(text="lobster") spam_d1 = Definition.objects.create( text="Processed meat", status=DefinitionState.COMPLETE ) spam_d2 = Definition.objects.create( text="Unwanted email", status=DefinitionState.ABANDONED ) spam.definitions.add(spam_d1) spam.definitions.add(spam_d2) eggs_d = Definition.objects.create( text="Laid by chickens", status=DefinitionState.COMPLETE ) eggs.definitions.add(eggs_d) bacon_d = Definition.objects.create( text="Part of a pig", status=DefinitionState.ABANDONED ) bacon.definitions.add(bacon_d) So I have four Words: spam, which has one COMPLETE definition and one ABANDONED definition; eggs, which has one COMPLETE definition; bacon, which has one ABANDONED definition; lobster, which has no definitions. I want to write a query which will return (bacon, lobster) (in no particular order). I can write the query to β¦ -
Social login(facebook) with Django Rest Framework always return Invalid Token
I build my login through this tutorial. I try make a login by facebook on endpoint .../social/facebook/, and always, a receive this json response: { "errors": { "token": "Invalid token", "detail": "400 Client Error: Bad Request for url: https://graph.facebook.com/v2.9/me?access_token=EAATf9P6TS9YBAOWem3RUZAIaUF5H6p67NfcUlSHx9JuQUBZBZBEIb6jaYQERjfB5a0QzKV0Op7FrNe0ZCZANlozR3YPExI8AarGoL9y5PKSbBRlwThDq5OyAruncW7rdMMsQLt48Uzak6kdMz4ZAJTJElKcynM0OOoPkZC6ZCoVJiRxOZCPWUkxqhhEZB6Th5TVuEZD&appsecret_proof=7ea0621354a3de8cde89cd288443f091634d3b8ab73e1ea93f6a58d1867d17bd" } } My json post is: { "access_token": "EAATf9P6TS9YBAOW****" } Here is my code: My settings: INSTALLED_APPS = [ ... # libs for SignUp in API 'social_django', 'rest_auth', 'rest_framework.authtoken', AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'register.backends.EmailBackend', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = '137214324***' SOCIAL_AUTH_FACEBOOK_SECRET = '*****' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] for key in ['GOOGLE_OAUTH2_KEY', 'GOOGLE_OAUTH2_SECRET', 'FACEBOOK_KEY', 'FACEBOOK_SECRET']: exec("SOCIAL_AUTH_{key} = os.environ.get('{key}', '')".format(key=key)) SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email', 'profile'] SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email'] SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <- this line not included by default 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) I defined the backends, the variables for facebook, it's missing anyone variable? The keys are correct. I am doing my request the right correct? My settings is right? I dont know why the facebook is can't login. -
Insert foregin key in django form
I am building django app where user select a company and then application pass company primary key over url. User is than redirect to the page where he can see all company devices and he can add or remove them from the list. Now I have problem. When I submit the form with all the data, I allways get the same validation error, which tells me that company field is requierd (I added foregin key to the form before validation). What I am doing wrong? views.py: def network_devices(request, pk=None): if pk: if request.method == 'POST': if 'dodajnapravo' in request.POST: devices_form = AddNetworkDevice(request.POST) devices_form.company = pk if devices_form.is_valid(): devices_form.save() return redirect(network_devices) else: messages.error(request, 'VneΕ‘eni podatki niso pravilni!') return redirect(network_devices) elif request.method == 'GET': devices_form = AddNetworkDevice() devices = NetworkDevices.objects.filter(company_id=pk).all() print(devices) return render(request, 'interface/network_devices.html', {'device_form': devices_form, 'page_title': 'Naprave', 'devices': devices}) else: return redirect(add_select_company) forms.py: class AddNetworkDevice(forms.ModelForm): vendor = forms.CharField(required=True, label='Proizvajalec', max_length=100) product = forms.CharField(required=True, label='Produkt', max_length=100) version = forms.CharField(required=False, label='Verzija', max_length=50) class Meta: model = NetworkDevices fields = ('__all__') models.py: class Company(models.Model): class Meta: verbose_name_plural = 'Podjetja' company_name = models.CharField(max_length=150) company_addres = models.CharField(max_length=500) def __str__(self): return str('{}').format(self.company_name) class NetworkDevices(models.Model): class Meta: verbose_name_plural = 'Naprave v OmreΕΎju' company = models.ForeignKey(Company, on_delete=models.CASCADE) vendor = β¦ -
Django - Session management
I wanted to prevent the same user account to have multiple active sessions within my app, and followed the answer from this question. I implement this into my models.py: from django.conf import settings from django.db import models from django.contrib.sessions.models import Session class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) from django.contrib.auth import user_logged_in from django.dispatch.dispatcher import receiver @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions Session.objects.filter(usersession__user=user).delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) It works mostly fine, however, I noticed a weird behavior. If I login with one account, and then open an incognito window and login with the same credentials, the first one is logged out (which is what I wanted). However, if I login with an account, and then close the browser, the next time I want to login I get an error at the line: # save current session request.session.save() with the following traceback (without much info..): UpdateError at / No exception message supplied The console log shows that the error is coming from django.contrib.sessions.backends.base.UpdateError After this, if I refresh the page, I can then login successfully. β¦ -
How to upload an In-memory ZipFile to a FileFIeld in Django 2.1[python]?
I am trying to unzip a zip file uploaded by using python's zipfile.ZipFile() class and then saving it into django's FileField which is connected to a remote object storage. But after trying many combinations ranging from converting the zipfile open object to StringIO, BytesIO , ContentFile and File, etc I fail to solve this error. Please help! My code and error: models.py class FileMeta(AuditModel, StateModel): """ This Model stores the Meta details related to any document in our system. There are model types which reflect on validations too """ IMAGE = 'Image' DOCUMENT = 'Document' IMAGE_AND_DOCUMENT = 'Image and Document' FILE_TYPES = ( (IMAGE, IMAGE), (DOCUMENT, DOCUMENT), (IMAGE_AND_DOCUMENT, IMAGE_AND_DOCUMENT), ) class Meta: verbose_name = 'File meta' verbose_name_plural = "File meta's" name = models.CharField("File Type Name", max_length=100, unique=True, db_index=True) type = models.CharField("File type Accepted", max_length=20, choices=FILE_TYPES, db_index=True, default=DOCUMENT) def __str__(self): return self.name class File(AuditModel, StateModel): """ This Model stores the File related to our system. This model relates to the File Meta to extract te file type for proper validation """ class Meta: verbose_name = 'Document' verbose_name_plural = 'Documents' file_meta = models.ForeignKey(FileMeta, verbose_name="File Definition", on_delete=models.PROTECT) file_id = models.CharField( "The Main ID number of the document provided", max_length=20, blank=True, null=True, ) file β¦ -
logger implementation in django project
I am trying to implement logger in my Django project, I have this in my settings.py settings.py LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatter': { 'standard': { # exact format is not important, this is the minimum information 'format': "%(asctime)s] %(levelname)s [%(name)s.%(module)s:%(lineno)s] %(message)s", }, 'console': { 'format': "%(asctime)s %(name)-12s %(levelname)-8s %(message)s", }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console', }, # Add Handler for Sentry for `warning` and above # 'sentry': { # 'level': 'WARNING', # 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', # }, 'file': { 'level': 'INFO', 'class':'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs.log'), 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, }, 'loggers': { # root logger '': { 'level': 'DEBUG', 'handlers': ['file'], 'propagate': False, }, }, } and in views.py i have this views.py import logging logger = logging.getLogger(__name__) class ProjectAPIView(ModelViewSet): serializer_class = AccountSerializer def create(self, request, *args, **kwargs): logger.info('account is created') problem logs.log file is created but logger is not writing any messages in the logs.log file. I do not know what is going wrong, please suggest anything if you think i should change in my settings.py. -
How to get a models with highest value grouped by related model in django?
I would like to perform this query in django: For each sensor, select it's latest message In SQL it would be something like SELECT * FROM (SELECT * FROM messages order by date_entered DESC) GROUP BY sensor_id Is it possible to achieve this in django? -
Django Restframework βGot AttributeError when attempting to get a value for field `section_type` on serializer `QuestionSerializer`
This is my model. class QuestionSection(models.Model): section = models.CharField(max_length = 100, null = True, blank = True) max_marks = models.IntegerField() def __str__(self): return self.section class Question(models.Model): question_section = models.ForeignKey(QuestionSection, on_delete = models.CASCADE, related_name = 'questions') section_type = models.CharField(max_length = 10,) questions = models.CharField(max_length = 350, null = True, blank = True) image = models.CharField(max_length = 10, null = True, blank = True) no_of_images = models.IntegerField(null = True, blank = True) marks = models.IntegerField() shop_view = models.CharField(max_length = 30, null = True, blank = True, choices=(('critical', 'critical'), ('major', 'major'))) what_to_look_for = models.CharField(max_length = 350, null = True, blank = True) def __str__(self): return "{}-{}".format(self.section_type, self.marks) This is my serializer class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class QuestionSectionSerializer(serializers.ModelSerializer): questions = QuestionSerializer(read_only = True) class Meta: model = QuestionSection fields = '__all__' I am not able to figuring out how to it. The serializer will be like Question_section fields and inside that Question fields will be there. -
django-filter Defining filter on Detail View
On my existing view I am trying to add filter view (by field "Sprint" in Issue - working in Issue model as foreign key). Below is my code: #models.py class Sprint(models.Model): sprint_type = models.TextField(default='Sprint', editable=False) name = models.TextField() goal = models.TextField() start_date = models.DateField() end_date = models.DateField() project = models.ForeignKey(Project, on_delete=models.CASCADE) class Issue(models.Model): ISSUE_PRIORITY = ( ('Critical', 'Critical'), ('High', 'High'), ('Medium', 'Medium'), ('Low', 'Low'), ) issue_type = models.TextField(default='Issue', editable=False) issue_id = models.AutoField(primary_key=True) # slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) initiative = models.ForeignKey(Initiative, on_delete=models.CASCADE, null=True, blank=True) epic = models.ForeignKey(Epic, null=True, blank=True, on_delete=models.CASCADE) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, null=True, blank=True) priority = models.CharField(max_length=8, choices=ISSUE_PRIORITY, default='M') I am using django-filter library. #filters.py import django_filters from .models import Issue class BacklogFilter(django_filters.FilterSet): sprint = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Issue fields = ['sprint'] Using class-based view, I defined: class ProjectBacklogView(DetailView): model = Project template_name = 'project-backlog.html' context_object_name = 'backlog' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return ListView.dispatch(self, request, *args, **kwargs) def get_queryset(self): try: self.filter = BacklogFilter(self.request.GET, queryset=Issue.objects.all()) return self.filter except: return Issue.objects.all() def get_context_data(self, **kwargs): context = super(ProjectBacklogView, self).get_context_data(**kwargs) context['project'] = Project.objects.all() context['issue'] = Issue.objects.all() # context['epic'] = Epic.objects.all() # β¦ -
How to draw multiple charts in Django
What I Did till now Views.py def drop(request): category = csvdata.objects.all() df_category = read_frame(category) pname = request.POST.get('catagery_id'); data_frame = df_category.loc[(df_category['Category'] == pname)] pivot_data1 = data_frame.pivot_table(index='Technology', values='Count', aggfunc=[sum], fill_value=0) pivot_data2 = data_frame.pivot_table(index='Location', columns='Technology', values='Count', aggfunc=[sum], fill_value=0) p = pivot_data1.plot(kind='bar', align='center') pivot_data2.plot(kind='barh', align='center') totals = [] #find the values and append to list for i in p.patches: totals.append(i.get_height()) #set individual bar labels using above list total = sum(totals) # # set individual bar labels using above list for i in p.patches: p.text(i.get_x() - .03, i.get_height() + .5, \ str(round((i.get_height() / total) * 100, 2)) + '%', font size=8, color='black') plt.tight_layout() plt.title('Job Opening In Jan According To Technologies',fontsize=10) plt.ylabel('No Of Opening',fontsize=5) plt.xlabel('Technology Name',fontsize=10) plt.legend().set_visible(False) buffer = io.BytesIO() plt.savefig(buffer) buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') return render(request,"myapp/visual.html",{'graphic': graphic}) It's only render one image..I want multiple Image with different Data..I know I am doing in wrong way But I have no idea How to do iN django..I am not much familiar with Django [I want Something like this][1] -
Sort objects by a substring of a model field in django
Im trying to find best solution to sort through all Machine objects in my db and find last deviceSerialNo used. deviceSerialNo is a character field and has a structure like this: AB12-12344. My task is to sort all Machine objects by a substring of deviceSerialNo field(everything after '-' in deviceSerialNo. My current solution that kind of works last = Machine.objects.all().order_by('-deviceSerialNo').first().deviceSerialNo or last2 = Machine.objects.all().order_by('-deviceSerialNo').annotate(search_index=StrIndex('deviceSerialNo', V('-'))).first().deviceSerialNo Can someone help me sort it as I mentioned above? -
how to display the a line of text in li tag in Django template?
I have text saved in my mysql records which looks like this: Handmade item Materials: wooden handcrafted handle, professional laser engraved rubber, brown cardboard special gift box, authorial stamp passport i want to display each line in <li> tag to appear like that: <ul> <li><p>Handmade item</p></li> <li><p>Materials: wooden handcrafted handle, professional laser engraved rubber, brown cardboard special gift box, authorial stamp passport</p> </li> </ul> using linebreaks filter will not apply <ul> default style (showing bullets). thanks in advance! -
How can I send url with user's unique_id and token in Django?
I created a Django App ("Invigilator Management System") for college. I didn't include any login authorisation as it will be only used by college adminstrator. In this app, I have one task left, I have to send availability form in mail for all the users which are in database asking for them to fill form whether they are available for that day or not, based on their response I have to store their availability status in database. How can I send form in mail? or should I send them a link for the form ? If I have to send link, how can I prevent one user accesing other user's form just by changing link they got, any idea how to add token along with thier unique id ? -
Django unittesting fails with CIText and Sqlite
I use CIText from django.contrib.postgres, how can I carry on using SQlite with my unit tests ? At the moment django dies trying to run my tests with: django.db.utils.ProgrammingError: type "citext" does not exist LINE 1: ...gmodel" ALTER COLUMN "name" TYPE citext USING "name"::citext -
Limit model choices on foreign key Django
I have the following field target_contenttype = models.ForeignKey(ContentType, blank=True, null=True, related_name="target_object", on_delete=models.PROTECT, limit_choices_to={'model__in':( '' )}) On limit_choices_to i can't find the documentation on how to limit related model located on different app. Can someone help.