Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send POST via AJAX when two jquery variables have been defined?
I'm guessing there's more than one error in this code - but the main thing I'm trying to figure out is how to send the AJAX when a condition is met - which is product and platform variables are defined and not null. With the following code - I think that line only gets evaluated once. I don't know if I need to add some type of listener or how this would work with jQuery. I am entirely new to jQuery. How do I adjust my code so that a POST is sent when platform and product are defined? Essentially what I'm wanting is for a user to be able to select a product via checkbox and a platform via another checkbox - and if these conditions are met send a POST with these params and accept the query results on return. html <H3>Product</H3> {% for product in products %} <input type="radio" name="{{ product }}"> {{ product }} <br> {% endfor %} <H3>Platform</H3> {% for platform in platforms %} <input type="radio" name="{{ platforms }}"> {{ platforms }} <br> {% endfor %} js <script> $(document).ready(function(){ $('input').iCheck({ checkboxClass: 'icheckbox_minimal-red', radioClass: 'iradio_minimal-red', increaseArea: '20%' // optional }); // if product has a checkmark … -
Django timestamp
Is there a way to use the Django timestamp without using a model? I want to write the timestamp to a file. The reason I want to use the Django one and not datetime or time from python is because I already set the Time Zone for it in settings so it would be more convenient if I could just use that. -
Get Data from PostgreSQL to Django and display it in html
I have a table in PostgreSQL database that contains two columns ID and Name. I am using django framework to get the data from the database and I want to display the data into html page. The problem is that the retrieved data is without columns name. It looks like this, and in order to use it in the html page it has to have a key for each tuple. [(2, 'abc'), (3, 'subhi')] I've tried to get the columns name but they are only table columns without data. Below is my Code: models.py import psycopg2 import pprint def main(): conn_string = "host='localhost' dbname='music' user='postgres' password='subhi123'" column_names = [] data_rows = [] with psycopg2.connect(conn_string) as connection: with connection.cursor() as cursor: cursor.execute("select id, name from music") column_names = [desc[0] for desc in cursor.description] for row in cursor: data_rows.append(row) records = cursor.fetchall() # print out the records using pretty print # note that the NAMES of the columns are not shown, instead just indexes. # for most people this isn't very useful so we'll show you how to return # columns as a dictionary (hash) in the next example. pprint.pprint(records) print (type(records)) print("Column names: {}\n".format(column_names)) if __name__ == "__main__": main() views.py from … -
sqlite3 Database not correctly configured in Django project
I'm currently continuing a django project on windows originally written by a mac user, and I am using the PyCharm IDE. I had a lot of trouble getting the database set up for the project (using the default sqlite3). My DATABASE settings are correct, and when I check the connection the the database when running manage.py shell it says that it is connected. The only issue is that every variable that is there to access data in the database is highlighted in red, which is typically a sign of an error in the JetBrains IDEs that I've worked with. I'm still able to host the site locally what could be the cause of this issue/error? I've a couple examples of what I mean below: example 1 example 2 -
Filter IF in FOR Django
I am developing an application in Django 2.0 of courses, each course contains modules, and obviously I have the users. model.py Class Course(models.Model): name = models.TextField() ..... Class Module(models.Model): name = models.TextField() containt = models.TextField() ..... Class UserCourse(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) flat = models.BooleanField(default=False) Class UserModule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) module = models.ForeignKey(Module, on_delete=models.CASCADE) When the user enters the module, the registry is created in the UserModule model to know that it has already entered the module. My idea is to show in the template all modules of the courses, but if the user has already made the module disable the option, otherwise allow to enter the module. views.py def course(request, idCourse): course = Course.objects.get(pk=idCourse) module = UserModule.objects.filter(user = User.objects.get(pk=request.user.id),module__course=course.id) return render(request, 'course.html',{'course':course,'module':module}) This query was sent to the course template {% for x in course.module_set.all %} {% if x in y module %} <i class="fa fa-check-circle"></i> {% else %} <a href="module"><i class="fa fa-check-circle"></i></a> {% endif %} {% endfor %} But unfortunately I do not get what I need to show the link if the module has not been done -
Getting Migrate Error on Model Field that doesn't exist
Ran my server today and realized I had 'two unapplied migrations'. I ran the command makemigrations and it detected no change, so naturally I then ran migrate. I get this error code on my terminal: Applying Campaigns.0016_campaignrecruit_date...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", l ine 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", l ine 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/migrat e.py", line 200, in handle fake_initial=fake_initial, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/executor.py", lin e 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/executor.py", lin e 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/executor.py", lin e 244, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/migration.py", li ne 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/operations/fields .py", line 84, in database_forwards field, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 306, in add_field self._remake_table(model, create_field=field) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 178, in _remake_table self.effective_default(create_field) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/base/schema.py", li ne 240, in effective_default default = field.get_db_prep_save(default, self.connection) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 767, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1276, in get_db_prep_value value = self.get_prep_value(value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1271, in get_prep_value return self.to_python(value) … -
Change BoalenField from False to True when message is opened
I've created my own message engine on Django framework to let users send messages to each others, here is my message model models.py class Message(models.Model): sender = models.ForeignKey(UserModel, related_name="sender", on_delete='CASCADE') receiver = models.ForeignKey(UserModel, related_name="receiver", on_delete='CASCADE') msg_title = models.CharField(max_length=150, verbose_name='عنوان الرسالة', default='رسالة جديدة من مستخدم فوستانيا') msg_content = models.TextField(max_length=1200,verbose_name='محتوى الرسالة') created_at = models.DateTimeField(auto_now=True) read = models.BooleanField(default=False) Then am listing messages for the user , they can see the messages with read=False as new message , they are able to click it to see the full message , i want the read to be changed to True after the user clicks the message from the template ,, How to do it ! -
How to add csrf_token in react components while having Django as backend?
I am working on a project with React-Django stack. There is a form which was earlier entirely built in a react component but Django threw csrf_token not present error For now, I have declared the form tags and the submit button in html and the components of the form in react. Is there a solution in which I can create the whole form in react along with the csrf token ? -
Passing dict through views
I have a view in which I create a dictionary, let's say: my_dict = {str(v): v*2 for v in range(2,8)} my_dict['Total'] = {'Tip': 'Reconsider life choices'} # bit of humour here >> {'2': 4, '3': 6, '4': 8, '5': 10, '6': 12, '7': 14, 'Total': {'Tip': 'Reconsider life choices'}} I pass it to my context dict as 'my_dict_json': json.dumps(my_dict). In my template, I reconstruct it with: <button id="btn_exp" type="button" class="btn btn-primary" onclick="sendDicts()"> <script> var d = JSON.parse('{{my_dict_json|safe}}'); // This is a function I bind to the onclick attr of a button function sendDicts(){ $.ajax({ url: '{% url 'my_model:intended_view' %}', type: 'POST', contentType: 'application/json', data: { 'my_dict': d, 'another_dict': d2 }, dataType: 'json' }); } </script> I'm not sure if it makes a difference but my intended view is decorated with @csrf_exempt, anyways, when I inspect (debug) the intended view, I notice that the request var has no data on it's POST and what seems to be the dictionaries are on request.body as a binary string with a lot of %s, if I try to use json.loads(request.body.decode()), it fails miserably with: JSONDecodeError: Expecting value: line 1 column 1 (char 0) What am I missing here? -
Django Rest Framework, Allow: POST not being set in generic view
I have a DRF generic view that inherits CreateModelMixin, but the Allow header does not include POST: class OrdersView(CreateModelMixin, ListModelMixin, GenericAPIView): filter_backends = (DjangoFilterBackend, OrderingFilter) filter_fields = ('product', 'team', 'buy', 'open') queryset = Order.objects.all() serializer_class = OrderListSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) A request to the url doesn't include POST in the Allow header: # OPTIONS /orders/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "name": "Orders", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ] } The view does process POST requests though. I would like the Allow header to be accurate though. -
Django rest framework add data to serializer
I am trying to add data to my serializer. What I have is a Game model and a Game can have multiple Match models attached to it. The thing is, the Game model doesn't know about this relationship. The relationship is on the Match model as a foreign key to the Game. However, there are times when I am getting a Game I want to include the Match models with them. Here is my serializer for a Game: import uuid from django.db import models from django.utils import timezone from patches.models import Patch class Game(models.Model): created_at = models.DateTimeField(editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4) updated_at = models.DateTimeField(editable=False) def __str__(self): return self.title def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Analysis, self).save(*args, **kwargs) class Meta: db_table = "games" And my Match model: import uuid from django.db import models from django.utils import timezone from games.models import Game from characters.models import Character from stages.models import Stage class Match(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.DateTimeField(editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4) updated_at = models.DateTimeField(editable=False) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Match, self).save(*args, … -
blog/posts.category.get_absolute_url, didn't match any of these
I am stuck at url problem. I suppose it is because of my 'blog.urls', or the href is my 'models.py'.But I am not sure how to change it. I am a programmer beginner. Sorry for the question if it is too simple. The issue is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/posts.category.get_absolute_url Using the URLconf defined in djangotest.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='list_of_post'] blog/ <slug:slug>/ [name='post_detail'] blog/ category/<slug:slug>/ [name='list_of_post_by_category'] The current path, blog/posts.category.get_absolute_url, didn't match any of these. blog/urls: from django.conf.urls import url from django.urls import path from . import views app_name = 'blog' urlpatterns =[ path('',views.list_of_post,name='list_of_post'), path('<slug:slug>/',views.post_detail,name='post_detail'), path('category/<slug:slug>/',views.list_of_post_by_category,name='list_of_post_by_category') ] list_of_post.html: {% extends 'blog/post/base.html' %} {% block title %}List of blog post{% endblock %} {% block content %} {% for posts in post %} <h2><a href="{{posts.get_absolute_url}}">{{ posts.title }}</a></h2> <p>Written by {{ posts.author }} on {{ posts.published}} in <a href="posts.category.get_absolute_url">{{posts.category}}</a></p> <hr> {{ posts.content | truncatewords:40 | linebreaks}} {% endfor %} {% endblock %} model.py: class Category(models.Model): name = models.CharField(max_length = 250) slug = models.SlugField(max_length=250,unique=True) class Meta: ordering = ['name'] verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('blog:list_of_post_by_category',args=[self.slug]) def __str__(self): return self.name -
Django: Query path parameter in foreignkey
I have a path with the structure: <slug:company>/<str:phone_number>/ Additionally I would like to filter paths based on: <slug:company>/ and: <str:phone_number>/ The kwarg "company" actually is a slug that sits in the Company model. The paths use a view for the listing. I tried to overwrite the get_object method for the detailview to filter the queryset based on the kwargs company and phone_number. This does however not work. Does anyone have a clue what is going wrong? urls.py urlpatterns = [ path('<slug:company>/<str:phone_number>/', CompanyDetailView.as_view(), name='detail'), ] models.py class Company(models.Model): name = models.CharField(max_length=120, blank=False, null=False) slug = models.SlugField(unique=True) class Listing(models.Model): phone_number = models.CharField(max_length=10) company = models.ForeignKey('Company', on_delete=models.DO_NOTHING) views.py class CompanyDetailView(DetailView): model = Company def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() number = self.kwargs.get('phone_number') company = self.kwargs.get('company') # Look up by phone number. if phone_number is not None and company is None: queryset = queryset.filter(phone_number=number) # Look up by company. if phone_number is None and company is not None: queryset = queryset.filter(company__slug=company) # Look up by phone number and company. if phone_number and company is not None: queryset = queryset.filter(phone_number=number, company__slug=company) # Raise Http404 error is phone number and company are None. if phone_number and company is None: raise Http404 try: … -
ImportError Django 2.0.6
Im trying to make my first django project, but i have this error on early stages when i execute "python3 manage.py runserver": ImportError: No module named 'gestordesarrollo' code where the error could be happening: apps.py: from django.apps import AppConfig class GestordesarrolloConfig(AppConfig): name = 'gestordesarrollo' settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gestordesarrollo.apps.GestordesarrolloConfig', ] project/urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('servidor.gestordesarrollo.urls')), path('admin/', admin.site.urls), ] Im aware that there are other posts with this error, but any answer fixed this for me -
Django: How do i make a form for a key-value model?
Am new to django and i was trying to remake Reddit's ThingDb database,where there are defaults in the Thing data table and and the keys:values(which are Title,Urls etc) go to the LinkData table linked with a ForeignKey I have these in models.py class LinkThing(models.Model): ups = models.IntegerField(default=0) down = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) score = models.IntegerField(default=0) thing_type = models.CharField(default='link',max_length=250) author = models.ForeignKey(User, on_delete=models.CASCADE) class LinkData(models.Model): thing_id = models.ForeignKey(LinkThing, on_delete=models.CASCADE) key = models.CharField(max_length=250)#title #Url value = models.CharField(max_length=250)#title_value #url_value How do i write the form for the keys and values table? I basically want to have the LinkData table to look like this in the database thing_id = 001,key = Title, value= How to something thing_id = 001,key = Url , value= how_to_something.url Here is how the ThingDb looks like reddit database -
How to *always* log exceptions and stacktraces in django with DEBUG = False
How do I set DEBUG = False, but ensure exceptions (wherever they may be thrown) are properly logged, including a stack trace. Here is my logging configuration: LOGGING = { 'version': 1, 'filters': { 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}, 'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue'} }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], 'level': 'DEBUG' }, 'django.server': { 'class': 'logging.StreamHandler', 'formatter': 'django.server', 'level': 'INFO' }, 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], 'level': 'ERROR' } }, 'root': { 'level': 'DEBUG', 'handlers': ['console'] }, 'loggers': { 'django.request': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, 'django': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, 'django.template': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'django.security': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, }, } -
How can I show elapsed time in Django
So, I'm trying to show elapsed time on a page for recent-visited history. On my model, I have the following attribute. models.py class History(models.Model): ... created_on = models.DateTimeField(auto_now_add=True) ... I already checked the date documentation, but it doesn't have a way to represent elapsed time from creating time to now. Doesn't Django support the feature? then should I implement it on my own? -
Updating Django Imagefield
Is it possible to update a django imagefield after a model is saved? I can display the images fine, but I cannot figure out how to update the fields. Any help? Simple examples? Thanks a bunch. -
Calling Python CLI program from django views and displaying the results back asynchronously?
I have a django project having a web interface where you can upload files and after the upload is successful it calls the cli version of the software to process it and returns the result after it's successful execution Here, is a bit of snippet I use in my views.py from cliproject.main import clirunner # Some code for file upload and saving clirunner() This will run the command line python script main.py which is present inside cliproject/ directory and it will do some stuff and saves the output The problem is, this whole process is Synchronous at this moment. Hence, the user page loads after they upload the file from the UI and until it gets processed by Python CLI script behind the scenes. The flow is as Django UI | (User upload files) views.py gets request and saves it somewhere | (views run clirunner() to give python cli program control) cliproject runs | (After doing the stuff which is intended, it saves the output file) views.py resumes | (Reads the output file) Django UI displays the output file So, we can see the problem here that I am calling a different CLI program from views.py to do the stuff … -
Reverse for 'detail' with keyword arguments '{'slug': 'hello-world'}' not found in django
I am trying to build a blog app using django. Now I need to show article details using slug. When I used bellow RegEx to use as slug for details url I am getting this error. Would someone help me please to solve this problem? In articles - app urls.py is - from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.article_list, name="list"), url(r'^(?P<slug>[\w-]+)/$', views.article_detail, name="detail"), ] And views.py is - from django.shortcuts import render from .models import Article from django.http import HttpResponse # Create your views here. def article_list(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): return HttpResponse(slug) And article_list.html is - {% extends 'base_layout.html' %} {% block content %} <h1>Article List:</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="{% url 'detail' slug=article.slug %}">{{ article.title }}</a></h2> <p>{{ article.snippet }}</p> <p>{{ article.date }}</p> </div> {% endfor %} </div> {% endblock %} -
Django: how to render same webpage after submit form
I have a index.html file which has the submit button. I want the functionality that when I click submit button, python function should get called in background but the rendering view of index.html should stay same. Right now every time I click on submit button a new copy of index.html is getting loaded. Here are my codes index.html <form action = "submit" method = "post"> <p>latitude <input type = "text" id = "Latbox" name = "Latbox" /></p> <p>Longitdue <input type = "text" id = "Lonbox" name = "Lonbox" /b></p> <p><input type = "submit" value = "submit" /></p> </form> My views.py file is as follow : from django.shortcuts import render from django.views.generic import TemplateView class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) def submit(request): LAT=request.POST['Latbox'] LON= request.POST['Lonbox'] print (LAT, LON) return render(request,'index.html',context=None) I am new to django. Can I get some pointer or answer as to how to solve this. -
Favicon Not Showing in Google Chrome
Until yesterday favicon.png on my website was showing very well. But today I made few changes in nginx file, after that it's showing in other browsers but not in Google Chrome. Here's the meta tag, <link rel="icon" type="image/png" href="/static/home/favicon.png"> Here's the nginx configuration, server { listen 443 ssl; . . . location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project; } location /media/ { autoindex on; root /home/user/project; } location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { root root /home/user/project; expires 365d; } location ~* \.(pdf)$ { expires 30d; } } How can we solve this problem? -
UNIQUE constraint failed
I am going through Tango with Django and I can't solve this excercise. I get django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category.name error. This is after I try to implement views attribute to Category object. This is a excerpt from my database population script. I though maybe that I should makemigrations and then migrate to update models for DB. However, this didn't help. cats = { 'Python' : {'pages': python_pages, 'views':128}, 'Django': {'pages': django_pages, 'views':128}, "Other Frameworks": {'pages':other_pages, 'views':128}, } for cat, cat_data in cats.items(): c = add_cat(cat, cat_data['views']) for p in cat_data["pages"]: add_page(c, p['title'], p['url']) for c in Category.objects.all(): for p in Page.objects.filter(category=c): print("- {0} - {1}".format(str(c), str(p))) def add_cat(name, views): c = Category.objects.get_or_create(name=name, views=views)[0] c.views=views c.save() return c -
Django template order swap in listing data?
I have an easy listing data, When ı move selected data then change order number. I do this like this listing data When I change order changed data Those numbers are not swap each other. How can ı fix this problem? api put code: stop: function(event, ui) { var fav_id = $('#fav_id').text(); var positon = ui.item.index(); var dep = $('#dep_id').text(); var url = "/api/v1/dep-favorite/"+fav_id+"/"; $.ajax({ type: "PUT", headers:{"Content-type":"application/json", 'X-CSRFToken': csrftoken}, url: url, data: JSON.stringify({department: dep, order: positon}), success: function(data, textStatus, xhr){ if (xhr.status === 201) { } } }); } my Api ViewSet: class DepFavoriteViewSet(ModelViewSet): queryset = DepartmentFavorite.objects.all() serializer_class = DepFavoriteSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = DepFavoriteFilter # permission_classes = (XHROnly, AuthenticatedUserOnly, DomainOnly) def get_queryset(self): if self.request.user.is_authenticated() and self.request.user.is_active: return DepartmentFavorite.objects.filter(user__exact=self.request.user) else: return DepartmentFavorite.objects.all() def perform_create(self, serializer): if self.request.user.is_authenticated(): dep_id = serializer.validated_data['department'] serializer.validated_data['user'] = self.request.user user_id = self.request.user.id favs = DepartmentFavorite.objects.filter(department_id__exact=dep_id, user_id__exact=user_id) if not favs: serializer.save() else: if favs.count() > 1: favs.delete() serializer.save() else: raise Http404 def perform_destroy(self, instance): if self.request.user.id == instance.user.id: instance.delete() Thanks for your help! -
Creating a temporary file in Django to be passed to a Shiny application. Is this bad practice?
I have a Django app. that will ultimately pass a bunch of data to a Shiny app. Now, there's apparently no "good" way to transfer data between the two—so I've decided on generating a temporary CSV file w/ the Django app. and reading it from the Shiny app. The Django code will look something like: csv_file = tempfile.NamedTemporaryFile() # Write CSV to temporary file csv_file.seek(0) return redirect('/shiny?filename=' + csv_file.name()) And the Shiny code will look something like: server <- function(input, output, session) { file_name <- session$clientData$filename data <- read.csv(filename) ... } The server function in Shiny is called once per session; that is, this file will only be opened once when the user is redirected. Presumably, closing the browser or any other such action will end the session and close/delete the file. Now, as per this post, a return within a with block acts like finally. How does it act outside of a with block? Am I relying too heavily on there being some lag-time in between Django closing the file as it redirects, and Shiny opening the file?