Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display a parent-child-child with django
I'm new to Django and get easily lost. I have this app that have items. They are set as a list with parent-child relations. Later I want to display tasks attached to items. But for now. I can't even figure out how to display the parent-childs. This is my simplt model class Item(models.Model): item_title = models.Charfield() item_parent = models.ForeignKey('self') I want to display them as: Item 1 - item 2 - item 3 -- item 4 -- item 5 Item 6 - item 7 -- item 8 --- item 9 I have tried with making a view that take Item.objects.all().order_by('item_parent') And the template with a FOR - IN. But I don't know how to seperate to show first parent then child, and another child is that exist. I just manage to list everthing in order by the item_parent. Which is not the same. Appreciate some expert help to a beginner like me. -
How do I increment a counter variable in a template (Django)?
I have a model with a variable: counter. So I have that counter displayed in the template like this: <h2> Counter is : {%for Click in counter %} {{ Click.counter }}{% endfor %} </h2> But is it possible to have a button that whenever a user clicks on it, it increments that Models variable by 1? models.py class Click(models.Model): counter = models.IntegerField(default=0, null=True) def __str__(self): return '%s' % (self.counter) Thanks in advance -
How to override existing column in Django admin list display?
I'm trying to figure out how to override column values in Django admin list display. My model has field response_bytes which is in list_display in MyModelAdmin. I want admin to show this value in MB or KB etc. class MyModelAdmin(admin.ModelAdmin): list_display = [f.name for f in MyModel._meta.fields] # This contains response_bytes def response_bytes(self,obj): return filesize.size(obj.response_bytes) def request_bytes(self,obj): return filesize.size(obj.request_bytes) Unfortunately it doesn't call methods below. If I created new list_display items with custom names and then rename these methods, it would work. Can I override existing fields or do I have to define new columns? -
Django fixture store bytearray
I'm doing some tests for my front end, so I want to load some fixtures in my DB to test it. This model is part of my fixture: { "model": "ingester.publication", "pk": 1, "fields": { "title": "Test Title, "pages": "1-2", "note": "DBLP NOte", "abstract": "This text is common among all sources", "diff: ?? } }, The diff field is a BLOB field containing serialized content. Something like b' \x8f\xabkeyword_ids\x90\xa6url_id\x92\x01\x03\xafstudy_field_ids\x90\xa6volume\x91\x83\xa9bitvector\x01\xa5value\xa233\xa5votes\x00\xa5title\x92\x83\xa9bitvec0' How can I store this in the fixture? -
I'm getting error when trying to import reserve from urlresolver
when i try to import reverse in my models.py file with the following line: from django.core.urlresolvers import reverse i'm getting this error :ImportError: No module named 'django.core.urlresolvers.I'm learning django from youtube ,and here is the url of the video that i'm watching : https://www.youtube.com/watch?v=eouZwgKuA5k.How can i fix it? -
authtools in django problems with migrations
I am trying to use Authtools for custom users in django. I am following documentation from their site: django-authtools.readthedocs I started a new project, created admin. Then I: inserted authtools in INSTALLED_APPS. inserted AUTH_USER_MODEL = 'authtools.User' in settings.py in urls i did: from django.conf.urls import url,include from django.contrib import admin from authtools import urls from django.contrib import admin from authtools import urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('authtools.urls')),] Finally I ran python manage.py migrate and i received following: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency authtools.0001_initial on database 'default'. I have no idea what is going on. Does anyone understand? Thank you. -
Html does not import css file
Silly question but i can't figure it out and it's too much. In a django project, in the same directory i have base_template.html and base_style.css. In a child folder i have search.html. base_template.html base_style.css folder---- search.html Search.html extends base_template.html like so {% extends "base_template.html" %} Inside base_template.html i import base_style.css <!DOCTYPE html> <html> <head> <title>{% block title %} Base template {% endblock %}</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="base_style.css"> <link rel="stylesheet" type="text/css" href="awesome_font.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat"> <style> {% block Additional_Styles %} {% endblock %} </style> And there's no way it works. **Already tried: ./base_style.css /base_style.css base_style.css"/** If i replace <link rel="stylesheet" type="text/css" href="base_style.css"> with: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> It works, the css loads. I must mention that i just downloaded the css from the link and made no modifications. Why doesnt the import work? -
How to not roll back db transactions created in pytest-django fixture of class scope
I'm using pytest with Django (via pytest-django) and I'm wondering if it's possible to have a fixture of scope class that creates some models in the database and then not have those models removed at the end of each test. For example; @pytest.fixture(scope='class') def expensive(): return MyModel.objects.create() @pytest.mark.django_db() class TestMyModel: def test_a(self, expensive): MyModel.objects.get() # All good def test_b(self, expensive): MyModel.objects.get() # raises MyModel.DoesNotExist This is just a simplified example, in my actual code the fixture expensive is actually doing something that takes some time (and I'm actually using a parametrize test but I imagine that won't make any difference). It appears as if what I'm trying to do might be possible using the fixture django_db_blocker however I was not able to get this to behave as I wanted. -
formset choicefield validate empty form
While I am sure there is an easy answer for this, no amount of googling has brought me closer to one. How can I prevent an empty extra form from being validated? class RulesListModelForm(forms.ModelForm): retailer = forms.ModelChoiceField(queryset=Retailer.objects.can_shop().all(), initial=None) type = forms.ChoiceField(initial='whitelist', choices=SELLER_LIST_TYPES) class Meta: model = RulesList fields = [ 'retailer', 'type', 'sellers', ] RulesListFormset = modelformset_factory(RetailerSellersRulesList, form=RulesListModelForm, extra=1) Even though I've set the initial to what I blieve are the proper values, the formset.has_changed() and form.has_changed() evaluate to True. What am I missing here? -
django+django_webpush: navigator.serviceWorker.register never completes
Using django 1.11 and https://github.com/safwanrahman/django-webpush. Works with runserver localhost:8000 (both on dev host and prod host), completes ok and notifications work. But doesn't work on prod host with runserver 172.31.1.100:8000: register() never completes. I'm total newbie in web development domain, so the only thing I notice is that external IP (88., it's hetzner) is not the same as internal IP (172.). Can it make a difference? I've tried putting webpush_serviceworker.js into root, as advised in Larry's post, didn't help… -
django add placeholder text to form field
In Django I have the below code which is creating a username and password form on an HTML Page: <div class="control-group"> {{ form.username }} </div> <div class="control-group"> {{ form.password }} </div> I want to add "Username" and "Password" placeholder text within the field, and then when the user clicks on the field the word dissapears. What is the best way to achieve this ? -
MongoEngine and dealing with "UserWarning: MongoClient opened before fork. Create MongoClient with connect=False, or create client after forking"
I am using Celery and MongoEngine as part of my Django App with. When a celery task that accesses the database is initialised i am getting this warning: UserWarning: MongoClient opened before fork. Create MongoClient with connect=False, or create client after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#using-pymongo-with-multiprocessing> It clearly has something to do with multiprocessing and pyMongo that is that mongoengine is based on. My question is: What is the best strategy to avoid this issue with mongoengine? Please note that i am connecting to the mongodb with mongoengine in the settings.py: mongoengine.connect('my_mongo_database_name', alias='default') -
Django removes the characters after space automatically
I passing the list of tuples from view to template.While printing the each element of the tuple if spaces is found then Django automatically removes the character after spaces. Here is my view.py def index(request): user_statuses = get_user_status() user_statuses.sort(key=lambda user_statuses: datetime.datetime.strptime(user_statuses[0], '%Y-%m-%d'),reverse=True) return render(request, 'view_status.html', {'lists': user_statuses }) Here is my template: <table> <thread> <th bgcolor="#35a5f0"> <td bgcolor="#35a5f0">Date</td> <td bgcolor="#35a5f0">Project</td> <td bgcolor="#35a5f0">Release</td> <td bgcolor="#35a5f0">Feature</td> <td bgcolor="#35a5f0">Module name</td> <td bgcolor="#35a5f0">Hours spent</td> <td bgcolor="#35a5f0">Comment</td> </th> </thead> <tbody> {%for list in lists%} <tr> <td><input type="checkbox" name="vehicle"></td> {%for i in list%} <td><input type="text" value={{i}}><br></td> {% endfor %} </tr> {% endfor %} </tbody> </table> My List of tuple is as below: [(u'2017-05-02', u'Web Design', u'1', u'UT', u'Redundancy', u'1', u'Add extra information'), (u'2017-05-01', u'Web Design', u'1', u'UT', u'Redundancy', u'1', u'Add extra information')] My output is as below As u can see characters after the spaces are ignored. Please help. -
How to Post csv file in simple Html into Django api?
I tried post FormData using "angular Js" and then using Directly post html to django api But It Will be failure , Anyone Tried it and Known It Please Tell me : html: <form action="http://localhost:55555/collaboratoradmin/test/upload_driver" method="post" enctype="multipart/form-data"> <input type="file" id="file" name="csv_file" accept=".csv" onchange="angular.element(this).scope().getFileDetails(this)" /> <button type="submit" ng-click="uploadFiles()">upload</button> Django api: @api_view(['POST']) def upload_driver(request): if request.POST and request.FILES: csvfile = request.FILES['csv_file'] dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) csvfile.open() reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) # Redirect to the document list after POST return HttpResponseRedirect(reverse('myproject.myapp.views.list')) print(list1) -
Django API to count pings(hits) to a server from Mobile devices
I have a Django Mobile server running. Which uses Django Rest Framework. I want to count the number of hits to particular URL from Mobile Devices. And I want to put them in Graphs and Charts to check analytics daily in my another web server. Is there any ready made Django API ? -
How do I upload an image via Django Rest Framework?
Here is my my model containing ImageField: class Profile(models.Model): user = models.OneToOneField(User) new_article_notifications_enabled = models.BooleanField(default=False) new_comment_notifications_enabled = models.BooleanField(default=False) new_comment_answer_notifications_enabled = models.BooleanField(default=False) userpic = models.ImageField(upload_to='userpics/', blank=True, null=True) city = models.PositiveSmallIntegerField(choices=CITY_CHOICES, default=CITY_CHOICES[0][0]) webpage = models.URLField(blank=True) about_me = models.TextField(blank=True) favorite_brands = models.TextField(blank=True) Serializer: class ProfileChangeSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'new_article_notifications_enabled', 'new_comment_notifications_enabled', 'new_comment_answer_notifications_enabled', 'userpic', 'city', 'webpage', 'about_me', 'favorite_brands', ] def update(self, instance, validated_data): Profile.objects.filter(id=instance.pk).update(**validated_data) return instance View: class ProfileChangeAPIView(generics.RetrieveAPIView, mixins.DestroyModelMixin, mixins.UpdateModelMixin): permission_classes = ( permissions.IsAuthenticated, ) serializer_class = ProfileChangeSerializer parser_classes = (MultiPartParser, FormParser,) def get_object(self): if not Profile.objects.filter(user__id=self.request.user.pk).exists(): return Profile.objects.create(user=self.request.user) return self.request.user.profile def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) So, when I trying to upload userpic via Django Rest Framework interface - it updates hyperlink to image bu does not creates image file in media folder. When I uploading image via django admin interface all works fine. Where I'm wrong? -
Django ORM Filtering
My model looks like this: Person(model.Models): name = model.CharField(max_length=32) date_added = models.DateTimeField(auto_now_add=True) Note(model.Models): person = model.ForeignKey(Person) action = model.CharField(max_length=32, default='call) date_added = models.DateTimeField(auto_now_add=True) owner = model.ForeignKey(User) my view: def get_working_persons(self): relevant_actions = ['call', 'meeting', ...] query = Q(action__in=relevant_note_actions) | Q(date_added__range=[fourteen_days_ago, now]) get_current_person_notes = Note.objects.filter(query).exclude(~Q(owner=request.user)).values('owner', 'action', 'person') This returns a list of notes, where each person has all the notes listed, that are posted within the date_added__range. How do I get the last note for each person in that date range, that meets the other criterias? -
How to serialize list of strings with Django Rest Framework
I have serializer in Django rest framework as follows: class StateSerializer(serializers.ModelSerializer): kilometers = Field(source='mileage') pictures = StatePictureSerializer(many=True, read_only=True) class Meta: model = Inspection # Options fields = ('kilometers', 'inspection_date', 'pictures') And StatePictureSerializer is as follows: class StatePictureSerializer(serializers.ModelSerializer): blob_url = Field(source='public_url') class Meta: model = Inspection_Picture fields = ('blob_url', ) As result I get something as follows: { "kilometers": 64431, "inspection_date": null, "pictures": [ {"blob_url": "path/to/photo"}, {"blob_url": "path/to/photo"}, {"blob_url": "path/to/photo"}, {"blob_url": "path/to/photo"}, {"blob_url": "path/to/photo"} ] } Thus, pictures is an array of objects. What I want is an array of strings, for example: "pictures": ["path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo"] Any idea how to do that? -
How can I improve view in Django?
I have such URL: url(r'^data/$', views.DataList) and view in Django: @api_view(['GET', 'POST']) def DataList(request): try: myData = Data.objects.filter(sth=request.GET.get('sth')) if request.method == 'GET': serializer = DataSerializer(myData, many=True) return Response(serializer.data) except Data.DoesNotExist: if request.method == 'GET': myData = Data.objects.all() serializer = DataSerializer(myData, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = DataSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My problem is that when I have URL http://localhost:8000/data/ and for instance GET request my view doesn't achieve this: if request.method == 'GET': myData = Data.objects.all() serializer = DataSerializer(myData, many=True) return Response(serializer.data) It seems to me that try-except isn't a good solution in this case and this is causing a problem. I wonder what is the best way to solve it? -
How to define user and group being unique together in django
Blockquote How to define user and group being unique together in django ? -
Django app which can search other websites
I would like to make django app which can search another website and group data. For example - website connected to booking.com which can find cheapest hotels in given datas. I made an app with selenium which can search many countries and find cheapest hotels, but I dont know if it is goot solution or how to connect it with django app. Can you give me any tips? Thanks a lot! -
Django: How to organize model structure, one-model or relations between few models?
I have dilemma how to build my models structure. First of all I will explain my situation. I am selling goods on eBay basis on dropshipping, so when I have new order on ebay then I make order on my partner shop. I would like create app where I can organize all orders from two platforms. I will use eBay API, PayPal API, PrestaShop API. My question is: How to plan structure of models? One model with no relations: # eBay App class Order(models.Model): date = models.DateTimeField(default=timezone.now, editable=False) paid = models.BooleanField(default=False) sales_manager_id = models.IntegerField(unique=True) shop_order_id = models.IntegerField(unique=True) # order ID from webshop shop_order_invoice = models.IntegerField(unique=True) # invoice num from webshop Few models with relations: # eBay App class ebayOrder(models.Model): date = models.DateTimeField(default=timezone.now, editable=False) paid = models.BooleanField(default=False) sales_manager_id = models.IntegerField(unique=True) # shop app class shopOrder(models.Model): date = models.DateTimeField(default=timezone.now, editable=False) shop_order_id = models.IntegerField(unique=True) # order ID from webshop shop_order_invoice = models.IntegerField(unique=True) # invoice num from webshop ebay_order = models.ForeignKey(ebayOrder) I must say that I have already created several applications in this project (I am generating ebay listings based on products in local db) so I will not create new app only for shopOrder needs. -
Passing a variable in django template to a django view
Hi i have a list generated by a file. I want to pick 1 of the list to send it to a view in django to do some stuff. How can i pass this variable to a django view?? html <div class="row col-md-9 col-lg-12 bigsep"> <select class="selectpicker" data-live-search="true" multiple data-actions-box="true" data-style="btn" id="empresa_selec"> {% for empresa in lista %} <option value="{{empresa.0}}">{{empresa.1}} </option> {% endfor %} </select> </div> And i want to recive here to do stuff with the variable, something like that Views.py def crear_pdf(request,empresa): #Make Stuff ... -
How update only the children calling save in hierarchy?
I have the following model: class Mother(models.Model): created_at = models.DateTimeField() class Father(Mother): default = models.BooleanField() def save(self, *args, **kwargs): if self.default: Father.objects.update(default=False) super(Father, self).save(*args, **kwargs) class ChildOne(Father): pass class ChildTwo(Father): pass If I call childtwo.save(), how do I make sure all childone do not get updated? Is it possibly to modify the save method in Father's class to distinguish between the children calling save()? -
Django Admin urls
I would like to use administration website directly by reverse url in my Django application but I get this error : No module named admin.site.urls I have urls.py file which looks like : import os from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from BirthCertificate import views from Identity import views from Accueil import views from log import views from Mairie import views from Table import views from Recensement import views from Configurations import views from Mariage import views import debug_toolbar from django.views.generic.base import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name=os.path.join(settings.BASE_DIR, 'Accueil/templates/Choice.html')), name='choice'), url(r'^admin/', include('admin.site.urls')), url(r'^BirthCertificate/', include('BirthCertificate.urls')), url(r'^Identity/', include('Identity.urls')), url(r'^Accueil/', include('Accueil.urls')), url(r'^Home/', include('log.urls')), url(r'^Mairie/', include('Mairie.urls')), url(r'^Table/', include('Table.urls')), url(r'^Recensement/', include('Recensement.urls')), url(r'^Configurations/', include('Configurations.urls')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^Mariage/', include('Mariage.urls')), ] And one of my HTML template has : {% if request.user|has_group:"admin" %} <li><a href="{% url "admin" %}" ><span class="glyphicon glyphicon-log-out"></span> Administration </a></li> {% endif %} Something is wrong ? I don't find How I can solve this error ..