Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrfToken is only valid after page refresh - Django
On my SPA, I am encountering an issue where I delete the csrfToken on a specific view and click to another view. In the next view, Django sets a new csrfToken. When I attempt to submit a form on that view, I get the error message: "CSRF Failed: CSRF Token missing or incorrect." even though there is a csrfToken set. I must refresh my page in order to submit my form successfully. I am not sure what is causing this inconsistency of the csrfToken on some use cases that I am testing. -
Error while using Makemigrations in python
I am totally new to django so any help would be appreciate I wrote the following code and in my terminal I used python manage.py makemigrations and got error django Model class ctrybe(models.Model): name = models.CharField(max_lenght=120) def __unicode__(self): return self.name Error in terminal Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Olar/Desktop/tryTen/src/ctrybe/models.py", line 7, in <module> class ctrybe(models.Model): File "/Users/Olar/Desktop/tryTen/src/ctrybe/models.py", line 8, in ctrybe name = models.CharField(max_lenght=120) File "/Users/Olar/Desktop/tryTen/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1061, in __init__ super(CharField, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght' I use python 3.4 -
Django 'Include' template with css/js
I have a generic template, used for including html (ie. a menubar in menubar.html) into other app templates, through the include tag. It has some defined css and js functionality, stored in respective menubar.css|menubar.js files. Is seems much more convenient to contain links to these files within the menubar.html file, as shown below: //At the Start <link rel="stylesheet" href="{% static '<appname>/css/menubar.css' %}" /> //.... other menubar HTML //At the End <script src="{% static '<app_name>/js/menubar.js' %}"></script> I'm worried this isn't good practise, because the template will be loaded with the css not located in HEAD and js not located at the end of BODY. These are described as the standard HTML practises. The clear alternative is to link the css or js in every template that I include the subtemplate, but this seems tedious. I know there is also the possibility of extending a template, however I believe the same issues occur with css/js usage. What's best? -
How to calculate total for all model objects that have another common value
Trying to create a calculation column in a table where it returns the sum of all allocated_hours for any db row that has a matching user_id. Currently I am getting "0" in the column for each item. What am I missing here? Thanks for the help. Note that I am using django tables2. #model.py class Allocation(models.Model): user_id = models.ForeignKey(Resource) project_id = models.ForeignKey(Project) week = models.DateField(default=timezone.now) allocated_hours = models.IntegerField(default=0) actual_hours = models.IntegerField(default=0) def __str__(self): return '%s - %s' % (self.user_id, self.project_id) def allocation_total(self): alltotal = 0 for i in Allocation.objects.values_list('user_id'): if i == Allocation.user_id: alltotal += Allocation.allocated_hours return alltotal - #tables.py class Project_Resource_table(tables.Table): role = tables.Column(accessor='user_id.resource_type') name = tables.Column(accessor='user_id.resource_name') allocation = tables.Column(accessor='allocation_total') class Meta: model = Allocation exclude = ('id', 'user_id', 'project_id', 'week', 'allocated_hours', 'actual_hours') sequence = ('role', 'name', 'allocation') -
Bug in showing django website on android device
I am developing a project in django using bootstrap. The page I have issues on is http://www.askoskar.com/analytics/ If you need to log in using the following: user: admin Password: adminadmin It works on IOS devices but not on android devices. The issue is that there is a big block looking like a footer covering the bottom of the page. Any one know what the issues are using the inspector in android emulator? Thanks! -
change search engine from whoosh to different one
I have got a website based on Django, where I'm using 'haystack' and 'Whoosh'. Everything is working correctly, but Whoosh seems to be too slow (I need to search over ~1 800 rows) In my settings.py it looks like this: WHOOSH_INDEX = os.path.join(os.path.dirname(__file__),'whoosh_index') HAYSTACK_CONNECTIONS = { 'default':{ 'ENGINE':'haystack.backends.whoosh_backend.WhooshEngine', 'PATH':WHOOSH_INDEX, }, } and I've seen somewhere that I can easily change the search engine just by changing the ENGINE in HAYSTACK_CONNECTIONS and don't touch anything else. It is possible ? and which search engine easy to install you would offer me ? Thank you ! -
Django haystack TemplateDoesNotExist
I'm working on an django project that was created using an older version of django. My environment is set up for the latest django version (1.11.4). when I try opening the search url, I get the error "TemplateDoesNotExist at /search/" Here is the log: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/ahmedn1/Documents/Paymob/wallet_executive_panel-master-c109bd6fe9cd1bf793c11a5c2e97d18a1887c3ba/templates/search/search.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/search/search.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/search/search.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/haystack/templates/search/search.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/rest_framework/templates/search/search.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/import_export/templates/search/search.html (Source does not exist) So, I thought of installing the search template manually. I went to the haystack source page: https://github.com/django-haystack/django-haystack/tree/master/haystack/templates but I couldn't find the search.html template at all. So, was it removed and I should change the way I'm using haystack or what? -
django returns 403 Forbidden on background-image
I am currently getting a 403 Forbidden error from the stylesheet loaded by one of my base templates. The path seems correct but the server won't load it. template base.hmtl <!DOCTYPE html> {% load staticfiles %} {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- BOOTSTRAP --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- GOOGLE FONTS --> <link href="https://fonts.googleapis.com/css?family=Lato|Open+Sans|Oswald|Raleway|Roboto+Condensed|Roboto:300,400,900" rel="stylesheet"> <!-- NAV BAR CSS --> <link rel="stylesheet" href="{% static 'static/css/nav_style.css' %}"> <!-- Resource style --> <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <!-- Resource jQuery --> <script src="{% static 'static/js/modernizr.js' %}"></script> <!-- Modernizr --> <script src="{% static 'static/js/nav_main.js' %}"></script> <!-- Resource Nav --> </head> <body> <div class="container"> {% block body_block %} {% endblock %} </div> </body> </html> and my css looks like: nav_style.css .cd-stretchy-nav.edit-content ul a::after { right: 7px; background-image: url(../img/stretchy_nav_cd-sprite-3.svg); } which returns the following error: Failed to load resource: the server responded with a status of 403 (Forbidden) -
How to disable button when required field is empty
Hello i need your help i need to disable this button send when the required field are empty. I am a beginner using django and i don't know how to resolve it. Please i need your help .. i lost my time trying to find a solution. Views.py: def contact(request): form = FeedbackForm(request.POST or None) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.urlencode(values).encode() req = urllib2.Request(url, data=data) response = urllib2.urlopen(req) result = json.loads(response.read().decode()) ''' End reCAPTCHA validation ''' if result['success']: form.save() message = u'You have feedback\nName: %s\nEmail: %s\nPhone: %s\nCountry: %s\nFeedback:\n%s' % ( form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['phone'], form.cleaned_data['country'], form.cleaned_data['feedback']) try: send_mail('NEW FEEDBACK', message, '', settings.DEFAULT_FROM_EMAIL) # to admin send_mail('THANK YOU for contacting us', 'We will be back to you promptly.', '', [form.cleaned_data['email'],]) # to user messages.info(request, 'SUCCESS! Your message has been sent!') form = FeedbackForm() except: messages.info(request, 'Sorry, can\'t send feedback right now.') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return render(request, 'contact.html', {'active_page':'contact','form': form,}) Contact.html: <html> <div class="col-md-6"> <form role="form" class="form" method="post"> {% csrf_token %} {% for field in form %} <label for="{{ field.label }}">{{ field.label_tag }} {% if field.field.required %}<span class="red">*</span>{% endif %}</label>{{ field.errors }}{{ field }} {% endfor … -
one-to-one chatting app in Django and python3
I want to build a simple one-to-one chatting app in a django and python3, where i'll be the admin (i should know if the user is entered the room or not) and the user can enter the chat room by only his name then click "start-chatting" for example and chat with me. One room and two users as simple as that.. So far i have created the whole web site along with the templates (JS,CSS) and setting all the needed components and it is working :).. Now i want to and the chatting functionality. i know i need the django-channles, if any one can help me to start or if you know any website or documents in that area that will be very helpful. Thank you,, -
how to save data to database in django
i want to save data in loop from 3 object like obj1 , obj2 and obj3 i assigned new value every time loop start how to save them in database sqlite3 django version is 1.11.2. python version 3.6 following is just an example: import requests from BeautifulSoup import BeautifulSoup c = 0 n=10; for i in range(0,n): url = 'https://www.youtube.com/watch?v=izP81UySf0Y&list=PLTsU2ohU-nVbA5wRwZgdJDB-SUExEOdlO&index='+str(c) c = int(c) + 1 response = requests.get(url) html = response.content soup = BeautifulSoup(html) obj1= soup.find('a', attrs={'class': 'title'}) obj2= soup.find('p', attrs={'class': 'body'}) obj3= soup.find('p', attrs={'class': 'desciription' }) i want to store these three object to database -
How can I send real-time data using Django WebSockets?
I would like to send real-time data from external API using Django WebSockets. My view with HTTP looks in this way: @permission_classes([GetPermission]) class DataList(GenericAPIView): serializer_class = ObjectSerializer def get(self, request): parameter = self.request.query_params.get('parameter', None) queryset = ExternalAPI().get(parameter, "RSQA") id = Object.objects.get(parameter=parameter).id queryset["id"] = id return Response(queryset) I would like use WebSockets instead of HTTP to send my data constantly. Is it a good solution and acceptable to send it without request? I wonder how it should be done? I will be grateful if example would be shown on my GenericAPIView. -
Compressing file for a Django ImageField below a certain size without changing image dimensinos
As the title basically says, I would like to compress/reduce the file size of Django ImageField images. Ideally, I would just pick a threshold - say 700,000 kb or something like that, and if the file size is above that threshold, I modify it until it's below the threshold I don't want to change the dimensions of the image, just reduce size and/or quality. I'm not sure if there is a simple way to do this, or if there is a fair about of guesswork or math involved, but I have yet to find a straightforward answer. Any help is much appreciated. -
Django i18n - same string used as ugettext and ugettext_lazy
I am in the process of translating a site to multiple languages. When I try to translate our labels for certain classes, I run into some problems because these label-classes are used in both views and models/forms (the very place Django says the distinction between ugettext and ugettext_lazy is) The problem is: I would rather not write every label-class function twice and translate the labels with ugettext & ugettext_lazy respectively. Can this be done in a better way? My main concern is that if the same strings exists two places, there is double the maintenance in the future, can the strings only exists one place? Example of vanilla lable-class: class CurrencyChoice(object): GBP = 10 USD = 20 EUR = 30 def labels(): return ( CurrencyChoice.GBP, u'Great Britain Pound' CurrencyChoice.USD, u'USA Dollar' CurrencyChoice.EUR, u'Euro' ) Example of i18n solution I would like to avoid: from django.utils.translation import ugettext_lazy, ugettext class CurrencyChoice(object): GBP = 10 USD = 20 EUR = 30 def labels(): return ( (CurrencyChoice.GBP, ugettext(u'Great Britain Pound')), (CurrencyChoice.USD, ugettext(u'USA Dollar')), (CurrencyChoice.EUR, ugettext(u'Euro')), ) def labels_lazy(): return ( (CurrencyChoice.GBP, ugettext_lazy(u'Great Britain Pound')), (CurrencyChoice.USD, ugettext_lazy(u'USA Dollar')), (CurrencyChoice.EUR, ugettext_lazy(u'Euro')), ) -
Save dates/time in a list in model Django
I want to save some dates as a list in a Django model and can't get it done properly. So first I tried last_visits = CharField(....) and wrote a function to add values to that Charfield. This did not work since I couldn't make a proper list.I found this(JSONField model attribute for lists), but storing python time into JSON will make problems since Json can't serialize it properly and converting it to str would cause new problems since I would have to convert it back later. So my question is: Is there an easy way to save multiple dates(list/array)? someList = list() global someList def logins(self): someList.append(datetime.datetime.now()) return someList Thats a function I wrote and it works fine but the values are not getting saved. How would I add the old values of the list and add a new one into a model attribute (Charfield/textField/JSONField)? I tried it like the following: #"last_visit" is the model attribute someList.append(self.last_visit) self.last_visit += json.dumps(datetime.datetime.now()) self.last_visit = someList self.last_visit.append(datetime.datetime.now()) self.last_visit.save() but none of these worked. Please note that I didn't used all of these at once I just wanted to give an overview of what I tried. -
Django .only() causing maximum recursion depth exceeded error?
I was using Django's .only() construct to query only the columns I need. ex. Foo.objects.filter(id__in=ids).only('id', 'name') Here is a truncated definition of model class Foo(BaseFoo): def __init__(self, *args, **kwargs): super(VoiceMission, self).__init__(*args, **kwargs) self._prev_state = self.current_state I needed only id and name fields, that's certain. And what was the reason for maximum recursion depth exceeded? -
Is there a way to show a list which based on a ListView Template?
What I want to do is to show a list based on a search that user made. I created a method to filter objects and inserted in a global variable(BTW, I don't know if it is good to do this in Django/Python.) And based on this global variable I want to show the list of objects based on ListView Template. Is it possible? If not, how can I do? search_objects = Model() def search(request): search_objects = Model.objects.filter(field1__icontains=search_text) | Model.objects.filter(fiedl2__icontains=search_text) | Model.objects.filter(field3__icontains=search_text) -
How to execute a GROUP BY ... COUNT or SUM in Django ORM?
Prologue: This is a question arising often in SO: Django Models Group By Django equivalent for count and group by How to query as GROUP BY in django? I have composed an example on SO Documentation but since the Documentation will get shutdown on August 8 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post. Of course I would be more than happy to see any different approach as well!! Question: Assume the model: class Books(models.Model): title = models.CharField() author = models.CharField() price = models.FloatField() How can I perform the following queries on that model utilizing Django ORM: GOUP BY ... COUNT: SELECT author, COUNT(author) AS count FROM myapp_books GROUP BY author GROUP BY ... SUM: SELECT author, SUM (price) AS total_price FROM myapp_books GROUP BY author -
reset/refresh modal data on each click event
Okay so I am trying to have a table displaying results from a query. I want the data in the table to be truncated and the user to be able to see the full data in a modal. I have tried implementing this as seen below. However, the modal is displaying the same result in every column for the first row. It seems as though once the modal takes data it won't change dynamically on iteration to load new data. So my question is what is the best way to handle this type of dynamic request and how would I implement it? Should I try to dynamically load the data with an ajax request or is there a way to reset that modal on each click to load new data? Please see the code below and thanks! Template: <td class='test'>{{ value.4 }}<a href='#' id="trigger_{{ forloop.counter }}"><img src='{% static "img/expand-icon2.png" %}' id="expand"></a> {% if methods %} {% for key2, value in methods %}{% ifequal key2 key %} <div id="classModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="classInfo" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="classModalLabel"> Triples: </h4> </div> <div class="modal-body"> <table id="classTable" class="table … -
How to connect to the Django admin console in AWS Elastic Beanstalk?
I am following this tutorial to understand how to port a Django application from PythonAnywhere (PA) to Elastic Beanstalk (EB). I have been able to create the instance, upload my PA content to EB and deploy it. Unfortunately, when I try to connect to the admin console I get a 500 Internal Server Error message. Here is what I have changed inside the Django framework: in settings.py, I added the EB url for the instance I have created in the ALLOWED_HOSTS field I added a configuration file to specify the location of the wsgi.py script I changed the database settings, since I created a new database instance on RDS and I would like my django application to point to it In the PA version, I used to connect to a url, such as user.pythonanywhere.com/admin in the ALLOWED_HOSTS field, and I was able to login as superuser. This is also what is suggested in the AWS tutorial. What else should I do, which I have forgotten? I have not found so much, I'll eventually edit the question if I find more. Thanks. -
Strange files appear my in Django project
I just noticed some strange files inside my django project. Files are named with modules of my app or python modules for instance: datetime, or myapp. File names got no extensions. I dont know if it could happen somehow and its normal or should I rather call security alarm. Inside files look like imagemagick files. Imagemagick is installed on this server. Example head of file: %!PS-Adobe-3.0 %%Creator: (ImageMagick) %%Title: (hashlib) %%CreationDate: (2017-07-11T12:49:23+02:00) %%BoundingBox: -0 -0 970 907 %%HiResBoundingBox: 0 0 970 907 %%DocumentData: Clean7Bit %%LanguageLevel: 1 %%Orientation: Portrait %%PageOrder: Ascend %%Pages: 1 %%EndComments %%BeginDefaults %%EndDefaults %%BeginProlog % % Display a color image. The image is displayed in color on % Postscript viewers or printers that support color, otherwise % it is displayed as grayscale. % I tried to open them in AdobeAcrobat but there is message that files are corrupted. -
Can't use view variables in template
In view.py: class DisplayView(generic.ListView): def get(self, request, **kwargs): if request.method == "GET": selection = request.GET.getlist("selection") # list of checkbox values with name 'selection articles = Article.objects.all() args = {'articles': articles, 'selection': selection} print(selection) print(articles) return render(request, display.html, args) In display.html: {% extends 'myapp/base.html' %} {%block contentblock %} {% for section in selection %} <h1>{{ section }}</h1> <script language="javascript">console.log(selection, articles)</script> {% for article in articles %} <h2>{{ article }}<h2> {% endfor %} {% endblock %} I can see on my terminal 'selection' and 'articles' printed as expected, meaning that the view correctly got the data from the checkboxes. However, nothing appears in my html and the console.log throws an error meaning the data was not passed to the template... Why? -
Django AttributeError: 'module' object has no attribute 'SubfieldBase'
I'm working on an django project that was created using an older version of django. My environment is set up for the latest django version (1.11.4). when I try python manage.py runserver, I get this: Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/ahmedn1/Documents/Paymob/wallet_executive_panel-master-c109bd6fe9cd1bf793c11a5c2e97d18a1887c3ba/accounts/models.py", line 8, in import timedelta File "/usr/local/lib/python2.7/dist-packages/timedelta/__init__.py", line 11, in from .fields import TimedeltaField File "/usr/local/lib/python2.7/dist-packages/timedelta/fields.py", line 18, in class TimedeltaField(six.with_metaclass(models.SubfieldBase, models.Field)): AttributeError: 'module' object has no attribute 'SubfieldBase' So, it seems the problem is with the django-timedeltafield package. I have the latest (0.7.10) version of that package. So, I don't understand why it still has an issue with the deprecated SubfieldBase. Any ideas how I might solve this issue? -
unsupported operand type(s) for <<: 'str' and 'int' while reading file
I am writing a unit test cases. I create a file objects and reading it, but i am getting this error, i tried some solutions, but not working. Please help. Method: def uploadExamineeDetails(request, exam_id): try: upload_file = request.FILES['upload-file'] except Exception: return [_('Uploaded file is required.')] try: exam = get_object_or_404_from_admin(CourseExam, request, exam_id) book = xlrd.open_workbook(file_contents=upload_file.read()) # further code My testing code: def test_uploadExamineeDetails(self): file = File(open(self.examinee_result, encoding='ISO-8859-1')) uploaded_file = InMemoryUploadedFile(file=file, field_name='upload-file', name='examinee_result.xls', content_type = 'application/vnd.ms-excel', size = file.size, charset = None) self.request.FILES['upload-file'] = uploaded_file response = uploadExamineeDetails(self.request, 1) data in excel file: [{'Enrollment Number': '', 'Username': 'exam_course_manager', 'row_num': 1, 'Obtained Score': 60.0, 'GR Number': ''}, {'Enrollment Number': '', 'Username': 'instructor', 'row_num': 2, 'Obtained Score': 20.0, 'GR Number': ''}] This is what I have done. I create a file, stored it in directory, then open it and made an in memory object, as shown in code. According to error i get it that this error occur when you try to compare a string to int. but i am not getting why this occurring in reading file, and where. Please help. -
Read > 1 GB CSV file from Django server and display in template
I currently have a bunch of huge CSV files on my server (one of them is over 3 GB) that I need to parse through and show on a template. Since this looks like JavaScript stuff, I looked into PapaParse but it seems that I have to pass in a File object to the parse function of PapaParse. The Mozilla link for that File object says that those kinds of objects are created when a user uploads some file, or from the HTML5 Canvas element. But I don't want that. The file is already on my server, and I just need to read through it and display the contents in a tabular format. I tried the manual approach of simply parsing through the entire file from Django and maybe passing it to an AJAX callback in the template but the browser froze, and I had to restart the server.