Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid import-time database access in Django?
My Django app has a number of categories for things which I store in a Category model. I reference these frequently in code, and so I've found it useful to have a module with references ("constants") to these categories and groups of them, so typos will fail fast. This also provides the benefit of caching. And finally, it's the actual model so it has all the related functionality. It looks something like this: def load_category(name): return Category.objects.get(name=name) DOGS = load_category("dogs") CATS = load_category("cats") However, this results in import-time database access and causes various issues. After adding a new category with a reference like this, I must run a data migration before ./manage.py will function. I just hit a new problem while switching to using Django's test framework, which is that these load from the default (e.g., dev or prod) database rather than the test one as explicitly mentioned in this warning. If your code attempts to access the database when its modules are compiled, this will occur before the test database is set up, with potentially unexpected results. For example, if you have a database query in module-level code and a real database exists, production data could pollute your tests. … -
How to send an entire XML file through Curl in the POST request in django rest
I need to send a XML file through curl as a data . But I am not able to see the top and bottom part of the file in request.body . Only the middle part of the XML file is present in the request.body . Using the Curl I tried to invoke my Django rest endpoint DELETE method. Curl Command went through but the file got stripped off on the top and bottom on the receiving end.(i.e) the request.body content contains only the middle part curl -k -i --user user:passwd -H "Content-Type: application/xml" -X DELETE --data "@sample.xml" https://sample_machine:8000/api/test/ Please let me know what went wrong here. Even I tried a smaller file sending as an input.But the same thing happened. -
Add streamfield to search index in Wagtail
I struggle to add my streamfield to the wagtail search index. This affects boths the available or the custom blocks. From what I've found in the mailing list, a custom block should implement get_searchable_content which all blocks do. here is my model which I'd like to index: class BlogPage(Page): author = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField("Post date") main_category = models.ForeignKey('blog.BlogCategory', related_name='main_category', default=1, on_delete=models.PROTECT) categories = ParentalManyToManyField('blog.BlogCategory', blank=True, related_name='categories') readtime = models.IntegerField(blank=True, null=True) subtitle = models.CharField( verbose_name=_('subtitle'), max_length=255, help_text=_("The page subtitle as you'd like it to be seen by the public - also the blog post teaser."), ) body = StreamField([ ('heading', general.TitleBlock()), ('paragraph', blocks.RichTextBlock()), ('image', general.FillImageChooserBlock()), ('subtitle', general.SubTitleBlock()), ('pullquote', general.PullQuoteBlock()), ('blockquote', general.BlockQuoteBlock()), ]) cover = models.ForeignKey( 'wagtailimages.Image', on_delete=models.PROTECT, related_name='+' ) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('subtitle'), FieldPanel('date'), FieldPanel('main_category', widget=forms.Select), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ImageChooserPanel('cover'), FieldPanel('author'), ], heading="Blog information"), StreamFieldPanel('body'), ] search_fields = Page.search_fields + [ index.FilterField('date'), index.FilterField('main_category'), index.SearchField('body'), index.SearchField('subtitle'), ] def get_context(self, request): context = super().get_context(request) context['posts'] = BlogPage.objects.exclude(id=self.id).order_by('-date')[:10] return context def save(self, *args, **kwargs): if self.body.stream_data: self.readtime = read_time_as_minutes(self.body.stream_data) return super().save(*args, **kwargs) thx for any hints :) -
How to handle a list of forms with django?
For my django app, I have a form from a ModelForm as it is made to modify one property on objects in database. It works well for one object, but I would like to display a page where I can modify all the objects at once. What I have now: form django import forms class FruitForm(forms.ModelForm): class Meta: model = Fruit fields = ('score',) widgets = {'score': forms.RadioSelect(),} the model: from django import models class Fruit(models.Model): name = models.CharField(max_length=20) score = models.ChoiceField(choices = [('bad',), ('neutral',), ('good',)]) the view: def fruit_score(request): name = Fruits.objects.get(name='Orange') if request.method == 'POST': form = FruitForm(request.POST) if form.is_valid(): form.save() else: form = FruitForm(None, initial={'name': name}) return render(request, 'fruit/test_fruit.html', locals()) and the following template: {%extends "base.html"%} {%block content%} {{name}} <form action="{% url "fruits.views.fruit_score "%}" method="post"> {%csrf_token%} {{form}} <input type="submit" value="Submit"> </form> {%endblock%} The result I would like looks like satisfactory survey: a table on which each row is composed of a label and a choice field (radiobutton rated from 'bad' to 'good'). Moreover, I would like to add a submit button for each row and a submit button for the whole page such that the user can decide to submit only few anwser or all the answer … -
search place with the search result
I am doing a autosuggestion box using ajax,jquery,solr,django. It's almost done but i am getting a problem that while searching autosuggestion is working fine and after clicking enter or waiting sometime the result is also coming but in that case i am not getting the search button. Only the result is there. I want the result just below that search place. I am uploading just my html file. Please help me where to change it to get the result as well as that search place. Thanks in advance..:) <!DOCTYPE html> <!-- jQuery !--> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <div class="ui-widget"> <label for="places"></label> <input type="text" id="places" name="places" placeholder="Search..."> {% csrf_token %} <br/> <br/> </form> </div> <script> $("#places").keypress(function(event){ if(event.which != 13){ $("#places").autocomplete({ source: "/api/get_places/", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 1, }); setTimeout(function() { $.ajax({ crossDomain:true, type : "post", async:"false", url : "/search/", data : { csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,term:document.getElementById('places').value}, success : function(result) { $(".ui-widget").html(result); {% for r in result %} document.writenl(r); document.write("\n"); {% endfor %} return result; }, error : function(event) { alert("error"), console.log("ERROR:",event); }, done : function(event) { alert("Done") //console.log("DONE"); } }); }, 5000); } else{ $.ajax({ crossDomain:true, type … -
Django-Memsql Initial Migration Error
I am getting the following error on my initial migration with django 1.10 with mysql backend connected to a 3 node MemSQL cluster. django.db.utils.OperationalError: (1895, "The unique key named: 'django_content_type_app_label_76bd3d3b_uniq' must contain al l columns specified in the primary key when no shard key is declared") I believe that this is the issue: MemSQL - Surrogate key as Primary and different unique keys at the same time in table creation Any workaround/solution will be much appreciated. Cheers -
Firebase structure data model
i'm new to firebase and while using firebase with swift/Xcode , i got some questions. it seems like firebase does not support data structure modeling. the data is just getting created by the data which is uploaded. the problem is that i can't set the data model at firebase console. unlike django or asp.net. i wish i could create the data model and easily read/write and (de)serialize it. any ways to do that? or any other service that supports what i want? -
How can we make admin content visible in user page in django
I have created a music app in django 1.9.I have created a login and register page. I created several options such as add songs, add album.My problem is that I want to show admin albums in other users albums page. Please help me out!! -
LookupError: No installed app with label 'django_messages'
I am trying to use https://github.com/arneb/django-messages and followed instructions as below pip install django-messages INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'oauth2_provider', 'api', 'localflavor', 'django_localflavor_us', 'django_countries', 'haystack', 'django_messages', ] urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('api.urls')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^messages/', include('django_messages.urls')), ] When i logged in to django shell and tried the following In [1]: from django_messages.models import Message In [2]: Message.objects.all() Out[2]: <QuerySet []> It worked fine and i can able to import Message model but when i try to register it in admin it is saying the below error from django.contrib import admin from django_messages.models import Message admin.site.register(Message) Error: Internal Server Error: /admin/ Traceback (most recent call last): File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 229, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 211, in inner return view(request, *args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project/lib/python2.7/site-packages/django/contrib/admin/sites.py", … -
Django RemoteUserBackend Not Cleaning Username
From the instructions, I have successfully activated django's remote user authentication (see associated snippet below from SETTINGS.py). Active Directory is being used for remote authentication. # snippet from SETTINGS.py MIDDLEWARE_CLASSES = ( ... 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ) AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ] As expected, when a user logs in for the first time, because the user doesn't exist yet, django will create the user. However, when the user is created, the user's username field has a <domain>\<username> format (e.g. "Domain1\PersonA"). In an attempt to remove domain from username, following django docs, I have updated the clean_username() method within the RemoteUserBackend class: def clean_username(self, username): return username.split('\\')[1] But, newly created user objects still have the username incorrectly set to the <domain>\<username> format. What am I missing? -
Router data to several Databases with my Django website
I would like to handle several databases with my Django Project but I need some advices about possibilities from my process. I have 3 applications in my project and I would like to separate databases like these : Database 1 : EC_local auth_* (auth_user, auth_group, ...) django_* (django_session, ...) application 1 Database 2 : EC_global application 2 application 3 Why this process ? Because my Django project will be deploy in 10 institutions. Each institution has to keep secret authentification key, users, ... in EC_local Database. However, all institutions have to share some informations thanks to application 2, application 3, ... in EC_global Database. I'm trying to simulate some virtualservers with both Databases but there are some things, especially Database routers that I don't understand. In my settings.py file, I have : DATABASES = { 'default': {}, 'global': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'EC_global', 'USER': 'osx', 'PASSWORD': '******', 'HOST': '******', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET innodb_strict_mode=1', }, } 'auth': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'EC_local', 'USER': 'osx', 'PASSWORD': '*****', 'HOST': '******', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET innodb_strict_mode=1', }, } } Then, I created a file which is named : routers.py At this moment, I don't really know what I have … -
Django makemigrations Issue
I am stumped. I have a custom model field class that looks for two arguments: app_name and file_dir. In my model definition I have this: files = MultiFileUploadAndViewer(app_name = getAppName(), file_dir='RequestedFiles', blank=True) getAppName() is: #appconfig imported from apps.py def getAppName(): return <appConfig>.name And the custom field definition is: class MultiFileUploadAndViewer(models.FilePathField): def __init__(self, *args, **kwargs): print(kwargs['app_name']) self.app_name = kwargs.pop('app_name') self.file_dir = kwargs.pop('file_dir','') + '\\' self.path = MEDIA_ROOT + '\\' + self.app_name + '\\' + self.file_dir self.upload_url = reverse(self.app_name +':File Upload') + '\\' + self.file_dir kwargs.update({'path':self.path}) super(MultiFileUploadAndViewer, self).__init__(*args, **kwargs) I deleted everything in the migrations folder except for init.py. Upon running makemigrations, it throws a KeyError complaining that 'app_name' is not in kwargs. However, notice the call to print() in the fields init method. That successfully prints the app_name. The KeyError comes after. Is the init function being called twice or something? Thus throwing the error after 'app_name gets popped off of kwargs? How can I address this issue? If I provide a default for app_name in the pop() method, this works, but I want it to error out if app_name (or file_dir) are not present in kwargs. -
Trying to activate Django signal in my test
Hey I am trying to activate a signal in my test - but I can not seem to make it work. This is my receiver @receiver(post_save, sender=models.Allocation, dispatch_uid="close_overdue_invoice_tasks") So how can "activate" it so it will call the method: def close_overdue_invoice_tasks(sender, **kwargs): ... All the signals works and my guess is that you manually have to activate the signals when running the tests. I am using Pytest by the way. -
Return value from html to django with range input every time its value changes
I have a project that takes a value from my website (django framework) and pass it back to django so that it can be used to run some scripts in case to dim the lights of my house (IOT project). I've found this code in django docs tha does this by a submit button but in my case it would be better with range input. What i exactly am looking for is to send the value back every time the slider changes position just like when i press submit button.Thanks in advance. here my code.html file {% extends "personal/header.html" %} {% block content %} <form action="/code/" method="post"> {% csrf_token %} {{ form}} <input type="submit" value="Submit" /> </form> {% endblock %} And this is on my views def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: print(form['your_name']) # outputs for example : <input type="text" name="your_name" value="34" required id="id_your_name" /> I would … -
Django Query Json Result
In my code I create this 'dict' type array: blog_reference = {'reference': kwargs.get('reference')} It is saved into the database table column content_reference: class UsageStatistics(models.Model): content_type_choices = ( ('unspecified', 'Unspecified'), ('blog', 'Blog'), ('newsletter', 'Newsletter'), ('video', 'Video'), ) reference = models.BigAutoField(primary_key=True) access_date = models.DateTimeField(blank=True, null=True) ip_address = models.GenericIPAddressField() passport_user = models.ForeignKey('Passport', models.DO_NOTHING, blank=True, null=True) language_iso = models.TextField() content_type = models.CharField( max_length=12, choices=content_type_choices, default='unspecified' ) content_reference = JSONField() class Meta: db_table = 'usage_statistics' I've wrote a database query which gives the result: <QuerySet [ {'total': 1, 'content_reference': {'reference': '160'}}, {'total': 1, 'content_reference': {'reference': '159'}}, {'total': 1, 'content_reference': {'reference': '162'}} ]> With this FOR loop I am trying to access all the values of content_reference['reference'] (namely 160 , 159 , 162) and put them into the array in_array. for item in result: content_reference = json.loads(item.content_reference) in_array.append(content_reference.reference) This is the full traceback for the error content_reference = json.loads(item.content_reference) is creating: Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rpiggott/PyCharmProjects/rons-home.net/blog/views.py" in popular 253. result = ServicePopular.search() File "/home/rpiggott/PyCharmProjects/rons-home.net/blog/service/popular.py" in search 34. b = json.loads(item.content_reference) Exception Type: AttributeError at /en/blog/popular Exception Value: 'dict' object has no … -
Django Deprecation Warning - Passing a 3-tuple to django.conf.urls.include() is deprecated
Hellow dear friends, I have a deprecation warning and I have no idea how to solve this one... RemovedInDjango20Warning: Passing a 3-tuple to django.conf.urls.include() is deprecated. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. url(r'^admin/', include(admin.site.urls)) How should I change url(r'^admin/', include(admin.site.urls)) ? I tried to look at the documentation, but I have no clue ... Thanks a lot -
NoReverseMatch error after upgrade Django version
I'm newbie in Django and i read many topic here and not found solution for my case. I believe it's easy, but i can't find the solution. Basically i have the code in my urls.py and the works fine in Django 1.8.4: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^leds/', include('ledscontrol.urls')), url(r'^', 'controli2c.view.view_home'), ] My template file contains {% url 'controli2c.views.view_home' as home_url%} <a href="{% url 'controli2c.views.view_home' %}" {% if request.path == home_url %} class="active"{% endif %} >HOME</a> When i update Django, i get the error "TypeError: view must be a callable or a list/tuple in the case of include()". Then, i change my urls.py code to: from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^leds/', include('ledscontrol.urls')), url(r'^', 'views.view_home'), ] Now, i have the NoReverseMatch when i open the browser (http://localhost:8000): "Reverse for 'controli2c.view.view_home' not found. 'controli2c.views.view_home' is not a valid view function or pattern name." In a post in the forum i found: "The solution is to update your urls.py to include the view callable. This means that you have to import the view in your urls.py. If your URL patterns don't … -
Django ORM, sum of multiple columns
I have a question about how we can filter by SUM of multiple columns. Example: class Foo(models.Model): i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() And I need to filter objects where SUM of i1, i2, i3 is less then 200. I've tried achive it with: Foo.objects.agregate(i_sum=Sum(i1,i2,i3)).filter(i_sum__lt=200) # error Foo.objects.agregate(i_sum=Sum([i1,i2,i3])).filter(i_sum__lt=200) # error Thanks. -
How to create a custom related manager in Django?
class ModelA(Model): pass class ModelB(Model): modela = ForeignKey(ModelA, on_delete=CASCADE) class ModelC(Model): modelb = ForeignKey(ModelB, on_delete_CASCADE) In this case Django will automatically create a few additional managers for us. For example, if ma is an instance of ModelA, then we can write: ma.modelb_set.all(), and if mb is an instance of ModelB, then we can write: mb.modelc_set.all(). It would be convenient to be able to reference all ModelC instances related to ModelA. Of course, if ma is an instance of ModelA, we can always write: ModelC.objects.filter(modelb__modela=ma).distinct(). However, it would be more convenient if we could define a manager for ModelA that would allow us to write: ma.modelc_set.all() How to write such a manager for ModelA? -
Can't override checkbox style using crispy forms
While creating forms for my app I had to make a custom checkbox (I am terrible with css so this was not easy). I got it to work and it looks like this when I create the form manually: But when using the wrapper_class attribute on a crispy forms Field it displays as standard: I tried using a custom Div template but I couldn't get it to work. In the docs all I could find was the wrapper_class. Am I missing something simple or could someone point me in the right direction? -
django1.9 run or debug error
my error its : Unhandled exception in thread started by .wrapper at 0x7f24ca04dae8> Traceback (most recent call last): File "/usr/lib/python3.4/logging/config.py", line 557, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.4/logging/config.py", line 725, in configure_handler result = factory(**kwargs) File "/usr/lib/python3.4/logging/init.py", line 1006, in init StreamHandler.init(self, self._open()) File "/usr/lib/python3.4/logging/init.py", line 1030, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/var/log/test/shemshad.log' -
RuntimeError: Model class django_messages.models.Message doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am trying to use https://github.com/arneb/django-messages package for my messaging stuff and tried the following pip install git+https://github.com/arneb/django-messages.git INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_messages', ] urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^messages/', include('django_messages.urls')), ] and when i run python manage.py runserver i got the below error Unhandled exception in thread started by <function wrapper at 0x107cedaa0> Traceback (most recent call last): File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_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/shivakrishna/shiva/Office_projects/iPitch/project /project /urls.py", line 23, in <module> url(r'^messages/', include('django_messages.urls')), File "/Users/shivakrishna/.virtualenvs/project /lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = … -
ValueError: invalid literal for int() with base 10: '09:50:13'
I am struggling to find a solution to this django error. I am inserting twitter object values into the database and 09:50:13 is time i think but i am getting an int() problem here are my django code: #models class Hermtweets(models.Model): tweet_id = models.BigIntegerField(default=None) tweet_date = models.DateTimeField(default=timezone.now()) tweet_favour_count = models.CharField(default=None, max_length=200) tweet_recount = models.BigIntegerField(default=None) tweet_text = models.TextField(default=None) tweet_timestamp = models.IntegerField() tweet_media_entities = models.URLField(default=None) #views tweets = Hermtweets() for x in e: tweets.tweet_date = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(x['created_at'],'%a %b %d %H:%M:%S +0000 %Y')) tweets.tweet_id = x['id'] tweets.tweet_recount = x['retweet_count'] tweets.tweet_favour_count = x['favorite_count'] tweets.tweet_text = x['text'] tweets.tweet_timestamp = x['timestamp_ms'] tweets.tweet_media_entities = x['source'] tweets.save() class HermtweetsList(APIView): def get(self, request): tweets = Hermtweets.objects.all() serializer = HermtweetsSerializer(tweets, many=True) return Response(serializer.data) def post(self): pass and this error: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, … -
Django Looping through input data (new rows generated by jQuery) from template
Hi I'm trying to read in data from input forms in template to Django view function. This is brief pictorial explain def student_add(request): <body style="height:100%;"> <div class="container" style="min-height:80%;"> <div class="col-sm-12 text-center"> <div class="formbox"> <form action="#" name="student-registration" method="post" class="signup-form"> {% csrf_token %} <table class="student-list"> <tr> <td>First Name</td> <td>Last Name</td> <td>Birthday</td> <td>Parent's Email</td> <td>Parent's Number</td> <td>Student's Number</td> </tr> <tr> <td><input class="input_box" type="text" name="first_name" id="first_name" placeholder="first name" required/></td> <td><input class="input_box" type="text" name="last_name" id="last_name" placeholder="last name" required/></td> <td><input class="input_box" type="text" name="birthday" id="birthday" placeholder="yyyy/mm/dd" required/></td> <td><input class="input_box" type="email" name="parent_email" id="parent_email" placeholder="parent's email" required/></td> <td><input class="input_box" type="text" name="parent_number" id="parent_number" placeholder="parent's number" required/></td> <td><input class="input_box" type="text" name="student_number" id="student_number" placeholder="student's number" /></td> </tr> </table> <div class="text-right" style="display: inline-block"> <button type="button" name="add" class="add_more">Add more</button> <button type="submit" name="submit">submit</button> </div> </form> </div> </div> </div> <script> var counter = 1; jQuery('button.add_more').click(function (event){ event.preventDefault() counter++; var newRow= jQuery('<tr><td><input class="input_box" type="text" name="first_name' + counter + '" required/><td><input class="input_box" type="text" name="last_name' + counter + '" required/><td><input class="input_box" type="text" name="birthday' + counter + '" required/><td><input class="input_box" type="text" name="parent_email' + counter + '" required/><td><input class="input_box" type="text" name="parent_number' + counter + '" required/><td><input class="input_box" type="text" name="student_number' + counter + '" required/></td></tr>'); jQuery('table.student-list').append(newRow); }); </script> </body> This is how i'm posting my data and when add more button is … -
Is there a way to have dictinary-like field in Django model?
Suppose, I am making a movie rating app. A logged-in user should be able to rate the movie with stars (in the range 1 to 5). I want to quickly access all the rater's name along with their rating. If a user rates the movie again, the rating should be updated. At the same time, if a user decides to withdraw his rating i.e. provide zero rating, I would like to remove the entry from the field. I believe dictionary would be the best choice to achieve the same. However, I am open for suggestions.