Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to upload js array data to database using django
I'm new to django. I'm now building a web app with couple slide bar in it. Once user drag these slide bars there data will be stored into an javaScript array. btw I'm using mysql . So, my question is how to upload the whole JS array into database using django? and for django is there a way to change js code just like changing the HTML code? thanks a lot! -
Django Template session not updating values
I am developing a human vs human chess app in django. The part for pawn promotion is not working. The session values are changing,but not getting updated to django template. The promote view def promote(request): #Update board with promoted piece board = request.session['board'] target = request.session['promote_target'] board[target[0]][target[1]] = request.POST['piece'] request.session['board'] = board request.session['promotion'] = False request.session['player'] = 1 request.session.modified = True return render(request,'chess_app/Default.htm') The js Function to call server function promotion(piece){ //Function to promote pawns //Add a confirm message $.ajax({url:"{%url 'promote'%}",data:{'piece':piece},type:'post',success:function(){location.reload()}}); } Everything works fine, but the session is not getting updated It would be great if you can help. -
How to serve files in Django without "/static" prefix
I have an angular 2 front-end with already written links between html js, css and other files such as images, that I would like to serve using Django. The structure from Angular 2 looks like following: -->index.html -->test.js -->test.css HTML file: <!doctype html> <html lang="en"> <head> <link href="test.css" rel="stylesheet"/> </head> <body> <script type="text/javascript" src="test.js"> </body> I wouldn't like to change the given paths from the angular 2 app, instead I would like to know the workaround to serve this files in django without using "/static/< appname>/" or "/static/" prefix or template tags in every link. Thank you in advance! -
Rendering different templates to the same url pattern based on a condition in django views
What i am trying to do ? I am trying to render index.html page if javaScript is enabled in the browser otherwise i want to render jsDisabled.html page if javaScript is disabled but i want both the pages to be rendered on the same url pattern for eg: 127.0.0.1:8000 should either render index.html if javaScript is enabled in the browser or it should render jsDisabled.html page if javaScript is disabled. I am not able to find a way out. Here is my code so far: base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> </head> <body class="noJs"> ... <a href="{% url 'index' 0 %}"> abc </a> ... <noscript> <style type="text/css"> .noJs { display: none; } </style> <meta http-equiv="refresh" content="{% url 'index' 1 %}"> </noscript> </body> </html> urls.py: from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ ... url(r'^(?P<flag>[0-1])$', views.index, name='index'), ] views.py: from django.shortcuts import render def index(request, flag): if (flag): return render(request,'jsDisabled.html') else: return render(request,'index.html') -
create a calculated field form other models field
I'm new in django. I want to create a table includes some fields which calculated from other models field. class Student(models.Model): name = models.Charfield(max_length = 30) ... class Subject(models.Model): student = models.ForeignKey(Student, related_name = "student_subject") point = models.IntegerField(default = 0) ... How can I create a queryset to get average point for each student? -
Selenium: assert file download
I have following problem. Is there any way I can assert start of file download after button click using python selenium? Thanks in advance! -
Changing model field values through the view
I have this model: class UserNotification(models.Model): user = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=6) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.user) It records a user's action in regards to another user's post so that the owner of the post can be notified. I then have this view: class NotifyMarkRead(RedirectView): def get_redirect_url(self,pk): obj = get_object_or_404(UserNotification,pk=pk) if obj.read != True: obj.read == True else: obj.read == False return obj.get_absolute_url() This is the view that handles the user clicking on the notification. This view is supposed to check if read is equal to True or False (it is false by default). If the user clicks on the notification the view is supposed to update read to True. However, it isn't doing that. So how do I update the read field in my model when a user goes through this view? Also I'm no that the page is being accessed however it just goes to /notify/1/read/ instead redirecting back to /notify/. Just sure if that's important here. Here are my urls: from django.conf.urls import url from notify import views app_name = 'notify' urlpatterns = [ url(r'^$',views.UserNotifications.as_view(),name='user_notifications'), url(r'^(?P<pk>\d+)/read/$',views.NotifyMarkRead.as_view(),name='user_notify_toggle'), ] -
Customize label tag and message error in Django AuthenticationForm class
I'm new in django. Is it possible to customize label tag if I want to use email as username login? However if the user doesn't introduce valid information, the error message shows username instead of email. -
--fake and --fake-initial explained
I've been a user of Django for about 2 years now and there is a feature I have always been affraid of using : faking migrations. I've looked pretty much everywhere and the most information I can get is from the documentation where it states that: --fake Tells Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema. This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly. --fake-initial Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial … -
Django CMD Nested plugin inside parent plugin
I have rather a general question or a feature request, not sure. Looks like a very common use case, but I couldn't find any useful information though. I'm trying to prepare around 10-15 custom "high-order" plugins that will consist of simple: text image link h1-h7 elements I'd like these "high-order" to be available for the user in the plugin dropdown and when he selects one - it will add that plugin with nested plugins automatically. So say I have a list of the following "high-order" plugins: image-1 Another example - let's assume I'm creating a plugin that looks like this bar: image-3 I imagine it will automatically add multiple buttons, text and header fields as nested/child plugins into my parent plugin. Is that easily possible within Django CMS? I was googling for nested plugins, but couldn't find any useful information about it. -
Webpack 3.1 Issues with Semantic UI imports
After migration to newer version of Webpack (from <2 to 3.1.0) I have a problem with Semantic UI imports. Consider following template structure: There is root template: <head> {% render_bundle 'global' 'css' %} {% block stylesheets %}{% endblock %} {% render_bundle 'global' 'js' %} {% block header_javascripts %}{% endblock %} </head> and there is second level template: {% extends "core/_global.html" %} {% load render_bundle from webpack_loader %} {% block stylesheets %} {% render_bundle 'accounts/register' 'css' %} {% endblock %} {% block javascripts %} {% render_bundle 'accounts/register' 'js' %} {% endblock %} Previously I had required Semanic UI imports in global.js: global.js (old) import '../semantic/dist/components/modal.min.css' import '../semantic/dist/components/modal.min.js' ... import '../styles/global.scss' $(document).ready(function() { }); With such structure I had access to required Semantic UI components from withing register.js. For instance I could call modal inside register.js: register.js (old) $(function() { init_modal(); function init_modal() { $("#terms_modal_link").click(function() { $('#terms_modal').modal('show'); }) } }) After switching to newer Webpack components imported in global.js are not visible inside register.js. I have to explicitly import required components inside register.js in following way: register.js (new) import '../../semantic/dist/components/modal.min.css' import '../../semantic/dist/components/modal.min.js' $(function() { init_modal(); function init_modal() { $("#terms_modal_link").click(function() { $('#terms_modal').modal('show'); }) } }); The change seems to be not so critical, … -
A page's urls are not worked properly
A page's urls are not worked properly.I made common header's html(header.html). I wrote in it {% load static%} <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'header.css' %}"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><a class="icon_head" href="send">SEND</a></li> <li class="top-menu-item"><a class="icon_head" href="see">SEE</a></li> <li class="top-menu-item"><a class="icon_head" href="know">KNOW</a></li> </ul> <a class="logout_button" href="logout_view">LOGOUT</a> </header> In index.html,header.html is read like <html lang="ja"> <head> <meta charset="UTF-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/accounts/detail.css"> <link rel="stylesheet" href="/static/bootflat/css/bootflat.min.css"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>WEB SITE</title> </head> <body class="relative"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/accounts/header.css"> {% load static%} <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'header.css' %}"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><a class="icon_head" href="send">SEND</a></li> <li class="top-menu-item"><a class="icon_head" href="see">SEE</a></li> <li class="top-menu-item"><a class="icon_head" href="know">KNOW</a></li> </ul> <a class="logout_button" href="logout_view">LOGOUT</a> </header> <main> <div class="container"> <p>Hello World</p> </div> </main> <footer> <div class="footers"> <ul class="bottom-menu"> <li class="bottom-menu-item"><a class="bottom_index" href="">XOXO</a></li> </ul> </div> </footer> </body> </html> When I put header's SEND&SEE&KNOW links,they worked properly. On the other hand,I wrote in detail.html like <html lang="ja"> <head> <meta charset="UTF-8"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/css/bootflat.min.css"> <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/js/jquery.fs.selecter.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/js/jquery.fs.stepper.min.js"></script> <title>WEB SITE</title> <body class="relative"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><i class="fa … -
Issues with pre-signed Image urls in S3
I am uploading files to AWs S3, Everything is working fine, images are getting upload and in return I am getting a pre-signed url But when I am trying to access that image I am getting below error. PermanentRedirectThe bucket you are attempting to access must be addressed using the specified endpoint. I can solve this issue by using AWS_S3_CUSTOM_DOMAIN but then pre-signed url will not be genertaed. The main aim is to genertae pre-signed urls. My settings are as follows: AWS_STORAGE_BUCKET_NAME = '********' AWS_ACCESS_KEY_ID = '****************' AWS_SECRET_ACCESS_KEY = '***************' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' DEFAULT_FILE_STORAGE = '******.PrivateMediaStorage' AWS_DEFAULT_ACL = 'private' AWS_QUERYSTRING_AUTH = True AWS_S3_ENCRYPTION = True S3_USE_SIGV4 = True AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } PrivateMediaStorage : class PrivateMediaStorage(S3Boto3Storage): location = getattr(settings, 'AWS_PRIVATE_MEDIA_LOCATION', 'media/private') default_acl = 'private' file_overwrite = False custom_domain = False -
django get user's client list tree from database
I had asked a question few days ago that is (django reverse lookup query within three tables). That answer helped me so much but I want implement something more. So is it possible to make a query that fetch all clints in my tree. here we are fetching clients that are created by me only. For example here I'm a reseller and I make clients which can be resellers and end clients also. So now I want fetch all clients that are in my tree. -
how to attach variable inside a dictonary in django application
{% with alertnames as name %} {{name}} I have data in this variable {{name}} and now If I want to attach in a dictionary as "Dictonary.name" and display it.How can I do that? -
Categories in wagtail not resolving
This is kind of a long shot, but will be glad if I can get help at this point, this is the only thing stopping me from completing this project. P.S been at it for 2 days. Can someone please point out what I am doing wrong here? as I keep getting can't resolve Keyword categories into Field Error. The exception thrown on this line services = services.filter(categories__category__name=category) However, looking through the code, one would see that there is a relationship between service_categories field and ServiceCategory through ServiceCategoryServicePage which has a related name of 'categories. So I was thinking that shouldn't throw an exception error of Cannot resolve field. Any help at this point will be extremely appreciated. def get_service_context(context): context['all_categories'] = ServiceCategory.objects.all() context['root_categories'] = ServiceCategory.objects.filter( parent=None, ).prefetch_related( 'children', ).annotate( service_count=Count('servicepage'), ) return context class ServiceIndexPage(Page): header_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) heading = models.CharField(max_length=500, null=True, blank=True) sub_heading = models.CharField(max_length=500, null=True, blank=True) body = RichTextField(null=True, blank=True) def get_context(self, request, category=None, *args, **kwargs): context = super(ServiceIndexPage, self).get_context(request, *args, **kwargs) services = self.get_children().live().order_by('-first_published_at') #.prefetch_related('categories', 'categories__category') if category is None: if request.GET.get('category'): category = get_object_or_404(ServiceCategory, slug=request.GET.get('category')) if category: if not request.GET.get('category'): category = get_object_or_404(ServiceCategory, slug=category) services = services.filter(categories__category__name=category) # Pagination … -
Best aproach in limiting django model entries
I have a model Events that has a ForeignKey to Users. What will be the best approach to limit users to post only one event. In the models, in the view or both? I've set a variable in settings.py because at some point the users will be able to increase their "quota" of events so a OneToOneField isn't an option. -
publish 5 words from model title django [duplicate]
This question already has an answer here: how to show first 50 words of a text field in django template 1 answer I have a model : class publish(models.Model): publish_time=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User, on_delete=models.CASCADE) Publish_Your_Story=models.TextField() def __str__(self): return '{}'.format(self.Publish_Your_Story) I have views.py : class Index(ListView): model=publish Template: <h1>Articles</h1> <ul> {% for article in object_list %} <li>{{ article }}</li> {% empty %} <li>No articles yet.</li> {% endfor %} </ul> Now i want to publish only 10 words from Publish_Your_Story row from models as article in Template . Kindly help . -
What is better performance between ManyToMany and a model with two forigen keys?
The case is I have a model User which is the teacher and student and I differ between them using a flag type, Now Teachers may have many students and vice versa so.. Which is better as a performance Case 1: class UserAccount(AbstractUser): type = models.PositiveSmallIntegerField(choices=TYPES, default=1) grp = models.ManyToMany("self",blank=True) Case 2: class UserAccount(AbstractUser): type = models.PositiveSmallIntegerField(choices=TYPES, default=1) class Group(models.Model): teacher = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students') student = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='teachers') For sure I can handle this based on the type in the form.. etc, but Now I can't determine which is better as a performance and code modularity -
Error while reading csv file in pandas
I am reading a CSV file whose name I have stored in Django session in function1 in views.py : request.session['filename'] = csvfilenamenew Here csvfilenamenew is the name of the CSV file.When I try to read this file using pandas in function2 in views.py, csvname = request.session['filename'] df = pd.read_csv(csvname) I get the KeyError error.I have also tried the following for retrieving the filename from Django session: csvname = request.session.get('filename', None) In this case, I get ValueError at /userlog/ Invalid file path or buffer object type: What am I doing wrong? -
Django - remove primary_key=True from an existing model?
I have a table that I've already migrated into the MySQL database and one of the fields has primary_key = True. I realized this needs to be different and I need to remove the primary_key = True. I'd like Django to create its own auto incrementing primary key fields (like it does with all models if you don't specify a primary_key). If I simply remove the primary_key = True, Django complains because it can't auto-assign an auto-increment value to its new id field (which is now the primary key field). What's the best way to change this one field to not have primary_key = True? This particular model doesn't have any records yet in the database, so I think I'm in a better position than if I had records in there. I'm not sure if I should just drop the table and migrate as if it's a brand new table or if I need to take some other approach? -
Webpack 3.1. jQuery is added multiple times
After migration to Webpack 3, I have noticed that jQuery inclusion works not as I expected. My template structure has core/_global.html root template in which I render common js and css assets like: <head> {% render_bundle 'global' 'css' %} {% block stylesheets %}{% endblock %} {% render_bundle 'global' 'js' %} {% block header_javascripts %}{% endblock %} </head> Second level templates extend the root template and add additional js and css to html: {% extends "core/_global.html" %} {% load render_bundle from webpack_loader %} {% block stylesheets %} {% render_bundle 'accounts/register' 'css' %} {% endblock %} {% block javascripts %} {% render_bundle 'accounts/register' 'js' %} {% endblock %} In previous verions of Webpack at the beginning of global.js I had: import 'expose?jQuery!expose?$!jquery' After removing this line and changing webpack.config to: plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", }), I have following problem - each of the rendered files, global.js and register.js contain jQuery. As result the size of each file is increased by appr. 300 kb. I expect jQuery should be loaded only once and it should be accessible both in global.js and register.js Are there any workarounds which allow to include jQuery in such way and have access to it … -
How best would I keep track of frontend version in a Django app?
I currently deploy frontend and backend together, but I'd like to split them into two independently deployable components. For the backend I use Django. What I'd like to know is how best to manage versioning from Django. For example, I have just pushed a new frontend deploy, which means I now have a new bundle-{VERSION}.js sitting in S3, where {VERSION} is the commit-hash. I now need to update Django to serve new pages so that {VERSION} is correctly sent down with templates. What's the best way to store a global variable like this, in such a way that it can be updated easily? I don't want to add a database hit to every pageload, so storing in the database is not ideal. I could save it to a file, but that's not great either. In order to use settings.py, I'd have to restart the server process every time I deploy the frontend, which is not ideal. Is there a way of storing the version so that it's stored in memory in the server process, but it can be updated easily? -
Django-IIS - FastCGI exited unexpectedly
I am encountering this FastCGI exited unexpectedly and I do not know how to resolve this error. I have looked around stackoverflow for solutions but the either the suggested solutions don't apply or no answers provided to the question. I want to run very basic django website (in fact I just created it) using IIS server with WFastCGI. Here is my spec: IIS 10.0 Windows Server 2016 Django 1.11.4. Python 3.6.2 wfastcgi 3.0.0 My python installation is in C drive. I am creating a virtualenv in D drive and pointing path to virtualenv's Python when configuring. When I point to virtualenv's Python, this error 'FastCGI process exited unexpectedly'. If I point my path to C's python, this error disappears (There is another python cant find module error but I can resolve that). I do not know the reason for this fastcgi exited issue when I use virtualenv's python. Kindly enlighten me if possible. Here is the detailed error info: Module FastCgiModule Notification ExecuteRequestHandler Handler djangohandler Error Code 0xc0000135 Requested URL http://localhost:8089/ Physical Path D:\inetpub\django\foo Logon Method Anonymous Logon User Anonymous -
Django REST Framework - OneToOne Relation through JSON
I want to create an API that allows to send JSON through a POST request. The JSON should then get passed on to a serializer which takes care of creating a new object and populate it with the existing data. It works fine for the 'simple' cases such as basic character-only inputs like usernames and alike, but I am seriously stuck when it comes to creating a OneToOne relation. Here's the sample code. Function called employee_list in views.py - data['account'] is a valid username, a User instance is successfully being selected! data = JSONParser().parse(request) user_object = User.objects.get(username=data['account']) data['account'] = user_object # this is now a valid User object serializer = EmployeeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) The model class Employee(models.Model) id = models.AutoField(primary_key=True) name = models.CharField(...) surname = models.CharField... account = models.OneToOneField(User) role = ... salary = ... picture = ... And the serializer class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = (...) # all fields of the `Employee` model So far so good, however, the serializer never validates! When I remove the need for a OneToOne relation, it works.. How can I create a new Employee objects with a working OneToOne relationship to a …