Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in Celery: TypeError("can_read() got an unexpected keyword argument 'timeout'",)
I am trying to integrate celery to my django application. I am following the tutorial provided here Real Python : Asynchronous Tasks When I try to execute the following code: celery -A app_name worker -l info I get the error: [2017-07-12 22:43:16,118: CRITICAL/MainProcess] Unrecoverable error: TypeError("can_read() got an unexpected keyword argument 'timeout'",) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/usr/local/lib/python2.7/dist-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/usr/local/lib/python2.7/dist-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/usr/local/lib/python2.7/dist-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 594, in start c.loop(*c.loop_args()) File "/usr/local/lib/python2.7/dist-packages/celery/worker/loops.py", line 88, in asynloop next(loop) File "/usr/local/lib/python2.7/dist-packages/kombu/async/hub.py", line 345, in create_loop cb(*cbargs) File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 1039, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 337, in on_readable chan.handlers[type]() File "/usr/local/lib/python2.7/dist-packages/kombu/transport/redis.py", line 671, in _receive while c.connection.can_read(timeout=0): TypeError: can_read() got an unexpected keyword argument 'timeout' I am using celery version v4.0.2 What is the reason behind the error and how do I solve it? -
Python dict_values ([...]) is not JSON serializable [duplicate]
This question already has an answer here: Specializing JSON object encoding with python 3 1 answer I'm trying to get up and running with an API that already works for some others (who, of course, I can't consult right now). I get an error for one specific endpoint: TypeError: dict_values([ {'unregistered_users': 2, 'group_name': 'a', 'registered_users': 9, 'total_users': 11}, {'unregistered_users': 0, 'group_name': 'b', 'registered_users': 4, 'total_users': 4}, {'unregistered_users': 0, 'group_name': 'c', 'registered_users': 4, 'total_users': 4}, {'unregistered_users': 4, 'group_name': 'd', 'registered_users': 5, 'total_users': 9}, {'unregistered_users': 0, 'group_name': 'e', 'registered_users': 7, 'total_users': 7}, {'unregistered_users': 0, 'group_name': 'f', 'registered_users': 7, 'total_users': 7}]) is not JSON serializable From what I can tell, this is valid JSON, and there's no reason why it shouldn't be serializable. I have pored through other SO questions regarding lack of JSON serializability and can't find any hints as to why this isn't working. My stack trace: File "/Users/AJ/code/my_app/events/views/event_views.py", line 50, in get return JsonResponse(event) File "/usr/local/lib/python3.5/site-packages/django/http/response.py", line 530, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/usr/local/lib/python3.5/site-packages/django/core/serializers/json.py", line 121, in default return super(DjangoJSONEncoder, self).default(o) … -
DRF: filter nested objects by owner
I'm trying to filter nested objects in API response by the ownership of currently authorized user. Here is my setup: Django 1.8, Django REST framework 3. MODELS class Container(models.Model): container_title = models.CharField(max_length = 50) class Item(models.Model): item_title = models.CharField(max_length = 50, blank = True, null = True, default = " ") item_container = models.ForeignKey(Container, on_delete = models.CASCADE, related_name = 'all_items_in_container') class Notification(models.Model): owner = models.ForeignKey('auth.User', null = True, on_delete = models.CASCADE) item_to_track = models.ForeignKey(Container, default = False, blank = True, null = True, on_delete = models.CASCADE, related_name = 'notifications_for_container') SERIALIZERS class ItemsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('pk', 'item_title') class NotificationSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.IntegerField(source='owner.pk') class Meta: model = Notification fields = ('pk', 'owner') class ContainerSerializer(serializers.ModelSerializer): all_items_in_container = ItemsSerializer(many=True) #notifications_for_container = NotificationSerializer(many = True) # this line returns all existing notifications per Container notifications_for_container = serializers.SerializerMethodField('get_current_user_notifications') def get_current_user_notifications(self, obj): user = self.context['request'].user user_notifications = Notification.objects.filter(item_to_track=obj, owner=user).exists() serializer = NotificationSerializer(user_notifications) return serializer.data class Meta: model = Container fields = ('notifications_for_container', 'pk', 'container_title', 'all_items_in_container') DRF VIEW class ContainerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Container.objects.all() def list(self, request, *args, **kwargs): queryset = self.queryset serializer = ContainerSerializer(data = [], many = True, ) if serializer.is_valid(): new_serializer = ContainerSerializer(queryset, many = True) data = new_serializer.data[:] return Response({'data':data}) … -
Send file using requets in python
Basically I have PHP base and now I am learning python. My problem is, I am uploading multiple files from HTML form, but form is quite different. i have minimum two input fields for a file. First one is the name of file and second one is file input. <input name="form_filed[]" placeholder="Params name" type="text"> <input name="form_files[]" type="file"> First filed hold the name and second has file which user want to upload. And one more thing, these can be multiple according to user requirement. And in my view.py field_name = request.POST.getlist('form_filed[]') files = request.FILES.getlist('form_files[]') all_files = {} if raw_form: f = 0 for param_name, param_value in raw_form.items(): if param_name != '': print("------------------------") print(files) #all_files[f] = (param_name, (param_name, open(files[f], 'rb')), 'application/x-www-form-urlencoded') all_files[f] = {param_name: open(files[f],'rb')} f += 1 res = requests.post(user_url, headers=all_headers, data=all_params, files=all_files) Output after executing this code: ------------------------ [<InMemoryUploadedFile: file.text (application/octet-stream)>] Internal Server Error: /app/client_requests/ Traceback (most recent call last): File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pa kages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pa kages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pa kages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Programs\Python\RestClient\client\views.py", line 105, in handleRequ sts all_files[f] = {param_name: open(files[f],'rb')} TypeError: invalid file: <InMemoryUploadedFile: file.text (application/octet … -
MEDIA_URL Page 404 Error Django
I am running on a local server and when I go to http://127.0.0.1:8000/media/ in my browser it says page not found. Settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' Root URL: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^polls/', include('mysite.polls.urls')), url(r'^admin/', admin.site.urls), url(r'^submit/', include('mysite.uploads.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Model for User Upload: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) Following the Django documentation: Serving files uploaded by a user during development During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.contrib.staticfiles.views.serve() view. This is not suitable for production use! For some common deployment strategies, see Deploying static files. For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) https://docs.djangoproject.com/en/1.10/howto/static-files/ -
Python Django models or admin issue?
I am building a website and for some reason I cannot add something through my admin site. My models: class Deal(models.Model): name = models.CharField(max_length=100) amount = models.IntegerField() my admin: admin.site.register(Deal) full traceback: Traceback (most recent call last): File "C:\Users\bruno.rojas\AppData\Local\Continuum\ Anaconda3\lib\socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "C:\Users\bruno.rojas\AppData\Local\Continuum\ Anaconda3\lib\socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\bruno.rojas\AppData\Local\Continuum\ Anaconda3\lib\socketserver.py", line 696, in __init__ self.handle() File "C:\Users\bruno.rojas\AppData\Local\Continuum\ Anaconda3\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle handler.run(self.server.get_app()) File "C:\Users\bruno.rojas\AppData\Local\Continuum\Anaconda3\ lib\wsgiref\handlers. py", line 144, in run self.close() File "C:\Users\bruno.rojas\AppData\Local\Continuum \Anaconda3\lib\wsgiref\simple_se rver.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' I am very confused because I have done this multiple times but for some unknown reason I cannot get it done with this site. Any help would be great. -
Django redirecting to signin after success login
I`m working on an old system with python 1.4 & Django 1.3, when i copied the system to workspace, all works fine, when i connected the database to workspace, and changed in settings.py the database to _workspace, the system let me signin, and redirect me to the home page, but when i`m refreshing the page, the auth session has been remove. when i return the main space table, all working fine. Thanks for any help. -
Django query to compare two foreignkey fields?
I have these sample database models class Book(models.Model): name = CharField() price = IntegerField() class Author(models.Model): name = CharField() book = ForeignKey(Book, related_name='authors') type = CharField(choices=('high','medium','low')) class Shop(models.Model): book = Foreignkey(Book, related_name='shops') type = CharField(choices=('high','medium','low')) rank = PositiveIntegerField() Database Objects:- b1 = Book('book1', 25) b2 = Book('book2', 30) Author('author1', b1, 'high') Author('author2', b1, 'medium') Author('author3', b1, 'medium') Author('author4', b2, 'low') Author('author5', b2, 'low') Author('author6', b2, 'low') Shop(b1, 'high', 1) Shop(b1, 'medium', 2) Shop(b1, 'low', 5) Shop(b2, 'low', 3) Shop(b2, 'high', 0) Shop(b2, 'medium', 0) Notice that there is a shop for book b1 with: 1.high=1 that means there must be just one author for book b1 2.'medium=2' that means there must be just two authors for book b1 'low=5' that means there must be just five authors for book b1 Book b2 has correct data as there are 3 authors with type=low and there is shop with type=low and rank=3 So I want to filter Book objects like b1. How to write Django query for this operation? -
Detecting the correct device information
I am using django_users_agent to obtain the device information. But I am not able to find the original browser type when I use Chrome's developer device mode. The Device mode provides me with that particular device information, but I would like to get the actual browser i.e Chrome's information. -
Django 1.9+ firebird connection
I have been trying to connect to firebird using Django 1.9.13 and the django-firebird from https://github.com/maxirobaina/django-firebird but I stil getting this error: django.core.exceptions.ImproperlyConfigured: 'firebird' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I folowed all the steps and requirements from the README section of the plugin (install but still the same. It seems to be incopatible with Django 1.9+ because of this error at the end of the log: cannot import name getLogger Is there any solution to have Django 1.9+ connected to Firebird 2.x Databases? -
Celery: Unrecoverable error: AttributeError("Can't pickle local object 'Pool.__init__.<locals>.Process'",)?
when i launch this code celery -A newstudio worker -l info so nothing work help meeee pls! who can help. i'll be waiting for you! Redis server and redis cli running! Full traceback > [2017-07-12 22:16:00,188: CRITICAL/MainProcess] Unrecoverable error: > AttributeError("Can't pickle local object > 'Pool.__init__.<locals>.Process'",) Traceback (most recent call last): > File > "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\worker\worker.py", > line 203, in start > self.blueprint.start(self) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bootsteps.py", > line 119, in start > step.start(parent) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bootsteps.py", > line 370, in start > return self.obj.start() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\concurrency\base.py", > line 131, in start > self.on_start() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\concurrency\prefork.py", > line 112, in on_start > **self.options) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\pool.py", > line 1008, in __init__ > self._create_worker_process(i) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\pool.py", > line 1117, in _create_worker_process > w.start() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\process.py", > line 122, in start > self._popen = self._Popen(self) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\context.py", > line 383, in _Popen > return Popen(process_obj) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\popen_spawn_win32.py", > line 79, in __init__ > reduction.dump(process_obj, to_child) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\reduction.py", > line 99, in dump > ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'Pool.__init__.<locals>.Process' > > (td11) C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio>Traceback (most > recent call last): File "<string>", line 1, in <module> File > "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\spawn.py", > line 159, in spawn_main > new_handle = steal_handle(parent_pid, pipe_handle) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\billiard\reduction.py", > line 121, in steal_handle > … -
Pinax project does not load any static file in pythonanywhere server
I have a pinax account project working fine in my local environment and I want to deploy it to a serve. When I try it to do it, it happens the same problem as if I install the pinax account project in the pythonanywhere server, the website shows everything but it cannot access any static file. MEDIA_URL = "/site_media/media/" STATIC_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "static") STATIC_URL = "/site_media/static/" STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, "static", "dist"), ] Everything looks good, I follow the documentation, I run the migrate, makemigrations and collectstatic and I tried a lot of things but still I do not get it what is wrong. Might be bad installation of the pinax projects? I tried to do it manually and with pinax-cli as well I also modified my WSGI: path = '/home/manolodewiner/mysite' os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' In my local environment it works perfect, so what could be the problem? -
Django model doesn't show on admin panel when created through Celery
I am creating some dynamic Django models through a celery process. When I created these models without using celery, they appeared on the admin panel, but when I ran the process through celery, the models do not appear on the admin page. I know the model are created because when I run makemigrations after, it does recognize the newly created models. My code is something like this: signals.py @disable_for_loaddata def email_change(sender, instance, **kwargs): from email.tasks import update_email update_email.delay(instance.pk) tasks.py @shared_task def update_email(id): from email.views import save_email save_email(id) views.py def save_email(id): from email.models import EmailType instance = EmailType.objects.get(pk=id) model = type(instance.__str__(), (Email,), attrs) admin.site.register(model, admin_opts) reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() call_command('makemigrations') call_command('migrate') Can anyone point out why this makes the model not show up on the admin panel? -
Django filter without spacing
if i have two records in database like something 00 and something00. I want to get both of them if i write down something 00 or something00. I tried: Item.objects.filter(name__icontains="something 00") but it doesn't work and i only get one result. Any other solutions? -
django "edit" function not working, while trying to edit my Song and Albums (object) model
i am getting error everytime i try to write the 'edit' function for the Album and Song instance. could anyone point out the mistake, which i have been making in 'edit' function to edit my albums and songs ? models.py - from django.db import models class Album(models.Model): album_title=models.CharField(max_length=50) date=models.DateTimeField(blank=True,null=True) def __str__(self): return self.album_title class Song(models.Model): song_title=models.CharField(max_length=50) genre=models.CharField(max_length=50) album=models.ForeignKey(Album,on_delete=models.CASCADE) def __str__(self): return self.song_title views.py- def formm(request): if request.method=='POST': songform = SongForm(request.POST) albumform=AlbumForm(request.POST) if songform.is_valid() and albumform.is_valid(): album = albumform.save(commit=False) album.date = timezone.now() album.save() song = songform.save(commit=False) song.album = album song.save() return redirect("result") else: albumform=AlbumForm() songform=SongForm() return render(request,"musicapp/formmpage.html", {'songform':songform,'albumform':albumform}) edit.py- def edit(request,pk): post = get_object_or_404(Song, pk=pk) if request.method=='POST': songform = SongForm(request.POST,instance=post) albumform=AlbumForm(request.POST,instance=post) if songform.is_valid() and albumform.is_valid(): album = albumform.save(commit=False) album.date = timezone.now() album.save() song = songform.save(commit=False) song.album = Album song.save() return redirect("result") else: albumform=AlbumForm(instance=post) songform=SongForm(instance=post) return render(request,"musicapp/formmpage.html", {'songform':songform,'albumform':albumform} -
Django- getting a list of foreign key objects
Lets say I have the following models: class ParentModel(models.Model): name = models.CharField() child = models.ForeignKey("ChildModel") class ChildModel(models.Model): name = models.CharField() Now, given some filter on ParentModels, I want to retrieve a list of all children models. I have tried: children = ParentModel.objects.values_list('child', flat=True) However this returns a list of ChildModel ids, rather than the full objects. Is there a queryset function that will accomplish what I am trying to do or do I need to write an additional filter query using the returned ids? I.e.- instead of: children => [51L, 53L, 54L] I want: children => [<ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>] -
Django 1.11: How to include translation in a JavaScriptCatalog?
I can`t include locale\ru\LC_MESSAGES\django.po in JavaScriptCatalog. settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', _('English')), ('ru', _('Russian')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) urls.py urlpatterns += i18n_patterns( url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) shell django-admin makemessages -l ru I'm adding a translation in locale\ru\LC_MESSAGES\django.po shell django-admin makemessages -d djangojs -l ru django-admin compilemessages But the response from the http://127.0.0.1:8000/ru/jsi18n/ does not contains translate from locale\ru\LC_MESSAGES\django.po -
How to show more GET request HTTP Django?
I'm building an application for managing student accesses in an area through swiping the badge. In particular, at the beginning all students are absent, then via a HTTP request GET indicating name and surname are added to the present. The problem is that when I do the GET requests I find, in the template, only one present overwriting the previous GET request. This is the code: Views.py: def stutente(request): cog = request.GET['cognome'] nom = request.GET['nome'] utenti = Utente.objects.order_by('cognome') utenti_presenti=Utente.objects.filter(cognome__icontains=cog,nome__icontains =nom).order_by('cognome') utenti_assenti=utenti utenti_assenti=Utente.objects.filter(~Q(cognome__icontains=cog,nome__icontai ns=nom)).order_by('cognome') return render(request,"accesso/stato.html",{ 'utenti_presenti' : utenti_presenti, 'utenti_assenti' : utenti_assenti, }) template: <div style="float: left; text-align: justify; width: 47%;padding:20px;"> <h1>Presenze:{{ utenti_presenti.count}}</h1> {% for utente in utenti_presenti %} <div id="content2"> <div class="articolo2"> <img src="{{ utente.image.url }}"> <h3>{{ utente.cognome }} {{ utente.nome }}</h3> <h6>Orario accesso: {{ utente.timestamp.now.time}}</h6> </div> </div> {% endfor %} </div> <div style="float: right; text-align: justify; width: 47%;padding:20px;"> <h1>Assenze:{{ utenti_assenti.count }}</h1> {% for utente in utenti_assenti %} <div id="content2"> <div class="articolo2"> <img src="{{ utente.image.url }}"> <h3>{{ utente.cognome }} {{ utente.nome }}</h3> <!-- <h6>Orario accesso: {{ utente.timestamp.now.time}}</h6> --> </div> </div> {% endfor %} </div> If I do a tip request: http://127.0.0.1:8000/stat/?nome=giovanna&cognome=baffo In the template will appear in the present:Giovanna Baffo. After If I do a tip request: http://127.0.0.1:8000/stat/?nome=mario&cognome=rossi will appear … -
How to send an object back to Django view and access it by indexing
In my HTML I have an object data .Data was originally retrieved from a SQL query in Django in views.py and passed on to the HTML using render() data looks like this data1= { 0:{ pk:1, model:"binaryQuestionApp.painting", fields: {title:'Pearl',artist:"vermeer"}, }, 1:{ pk:2, model:"binaryQuestionApp.painting", fields: {title:'Sand',artist:"vermeer"}, } } I use the following JS so send data back to views.py (I create csrftoken using this question) function post_data() { var postdata = { 'data': data, 'csrfmiddlewaretoken': csrftoken }; $.post('', postdata); // POST request to the same view I am now }; Now, data is being send back to the server, but I'm having trouble accessing it. I have this in my views.py if request.method == 'POST': data = request.POST # so far it works. But i can not index like this: print(data[0]['pk'] # instead I need to index it strangely, like this: print(data['data[0][pk]']) # note the entire key is a string How can I send data to Django so that i can access it in views.py using data[0]['pk']? -
Django-import-export can't import MultiSelectField Checkbox
I am using django-import-export in an app of my web project. my class.py file is the following: class Article(models.Model): siret = models.CharField(max_length=16) newspaper = models.CharField(max_length=200) writer = models.CharField(max_length=1000) TOPIC_TYPE = ( ('Sport', 'Sport'), ('Food', 'Food'), ('Business', 'Business'), ('Music', 'Music'), ('Art', 'Art'),) topics = MultiSelectField(choices = TOPIC_TYPE) Note that topics is a MultiSelectField. In admin.py I simply followed the django-import-export tutorial, hence: class ArticleResource(resources.ModelResource): class Meta: model = Article exclude = ('is_true', ) class ArticleAdmin(ImportExportModelAdmin): resource_class = ArticleResource admin.site.register(Article, ArticleAdmin) The issue while importing data is as you guess with the "topics" variable. I first exported an xlsx file to see the way this variable is exported. This is literally how: siret ... topics ----------------------------------- 0000068591590 ... Music, Art 0000068591595 ... Business, Beauté 0000068591600 ... Art The issue, is with data importing. I simply tried to import back the above exported file, by changing "siret" numbers. Once imported, in the admin interface, I was surprised, Django laughed at me by selecting only the first topic for each article in the available CheckBoxes (only Music for 0000068591590, only Business for 0000068591595). Hence I tried to import through: Music, Art (as exporting way) ['Music','Art'] [Music, Art] 'Music', 'Art' However It's not working. Ty -
Customizing django admin, should I be editing the files under site-packages or should I be overriding?
I started my project using the typical django-admin startproject mysite command. When I jump to method in visual studio on admin functions/methods I notice it brings me to the python environment site-packages, where all of the admin code resides. Should I be editing the code in these files or overriding them in other areas of my application? Tree view of what I'm talking about: +---env | +---Lib | | +---site-packages | | | | easy_install.py | | | | | | | +---django | | | | | shortcuts.py | | | | | __init__.py | | | | | __main__.py | | | | +---contrib | | | | | | __init__.py | | | | | | | | | | | +---admin | | | | | | | actions.py | | | | | | | apps.py | | | | | | | checks.py | | | | | | | decorators.py | | | | | | | exceptions.py | | | | | | | filters.py | | | | | | | forms.py | | | | | | | helpers.py | | | | | | | models.py | | | … -
Solr with Django-Haystack: 'Cannot create tester'
I am trying to create a search engine with django haystack with solr. So far I followed the documentation below and installed solr-6.6.0 on my server. http://django-haystack.readthedocs.io/en/master/installing_search_engines.html#solr But with the command ./bin/solr create -c tester -n basic_config I keep receiving the error: Failed to determine the port of a local Solr instance, cannot create tester! What can be the problem? -
Command silk_clear_request_log doesn't delete anything
I am running Silk on my staging server. I want to clear space in this database, so I run the following command. ../../bin/python manage.py silk_clear_request_log --settings ServiceName.settings.staging I expect to see output that it deletes things, but I don't get any output. After a few seconds, the prompt returns. No data is cleared in the database. What could be causing this behavior? How would I start debugging this issue? -
Django : Multiple column form not being saved to the database
I am new to django so please pardon me if this sounds ridiculous. I have gone through the django docs and all similar questions but i cant seem to figure it out.I have a form that takes in the marks of multiple exams of multiple students in the form of a table( using datatables). What I basically need is, for a table to be displayed, which will show the values currently present in the database but which can be edited and saved again. And although the entire table is displayed, editing only few of the table cells should also be allowed. In the table , the roll numbers of the students are from the database and since those don't change I am not passing them to the forms . The problem I face is ,though there isn't any error, the form.is_valid() returns true but form.save() doesn't save the values to the database. What i suspect the problem to be is that it probably doesn't know the roll no. pertaining to the row of data that its received and thus cannot place it in the database. I don't really know the mistake. Help will be deeply appreciated. Thank you. html form … -
Django ORM query guidance
My model includes a company, pub_date, and report_type fields. I have written two model methods: num_prev_covered and is_active and created a model manager. num_prev_covered: every new 'open' report is an increment of 1 is_active: if 'open' report has been created, but no 'close' report Model methods cannot be used in Django query filters (Django, query filtering from model method) Question: How do I write a query that performs the same functionality as the is_active method? SAMPLE DATA: +---------------------------------+----------+-------------+-------------------+------------------+ | COMPANY | PUB DATE | REPORT TYPE | NUM PREV COVERED* | ACTIVE COVERAGE* | +---------------------------------+----------+-------------+-------------------+------------------+ | Harley-Davidson, Inc. (HOG) | 11/20/10 | open | 1 | FALSE | | Harley-Davidson, Inc. (HOG) | 05/05/12 | close | 1 | FALSE | | Harley-Davidson, Inc. (HOG) | 03/15/14 | open | 2 | TRUE | | Harley-Davidson, Inc. (HOG) | 03/15/15 | nothing | 2 | TRUE | | Harley-Davidson, Inc. (HOG) | 06/06/16 | nothing | 2 | TRUE | | Textron Inc. (TXT) | 12/05/16 | open | 1 | TRUE | | Synchronoss Technologies (SNCR) | 06/02/17 | open | 1 | TRUE | +---------------------------------+----------+-------------+-------------------+------------------+ *model methods DJANGO MODELS: class PublicationManager(models.Manager): @staticmethod def active_pubs(): return [pub for pub …