Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url parameter error
Here is my problem : Using the URLconf defined in Rase.urls, Django tried these URL patterns, in this order: admin/ [name='index'] bio/<slug:username>/$ [name='bio'] The current path, bio/bussiere/, didn't match any of these. the url is : http://localhost:8000/bio/bussiere/ If you have any idea ? Thanks and regards -
Django creates all model tables in both databases
I made two databases in my django project, one app writes it's data to one database, second - to other. But when I make migration, all models from both apps create their tables in both databases, though they still remain empty (just one null row in every table) Is it possible to tell Django (Django, don't do it=) not to create extra tables which I don't need in both databases? Here is my code routers.py from django.conf import settings class DatabaseAppsRouter(object): def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in settings.DATABASE_APPS_MAPPING: return settings.DATABASE_APPS_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in settings.DATABASE_APPS_MAPPING: return settings.DATABASE_APPS_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label) db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in settings.DATABASE_APPS_MAPPING.values(): return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in settings.DATABASE_APPS_MAPPING: return False return None settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'tracking_db': … -
Django query unsupported format character '"' (0x22)
I'm passing a store_id field from a link on my index page to the view in order to look it up and provide a show store page. I'm using a sqlite backend but the Model.objcts.get() function won't return the object. It throws this error pointing at my .get line: ValueError at /store/1001946/ unsupported format character '"' (0x22) at index 192 Request Method: GET My views .py def store(request, store_id): print(type(store_id)) sto = StoreStat.objects.get(storeid=store_id) return render(request, 'stores/store.html', {'store': sto}) I've tried changing the type to an integer, played with encoding, but nothing seems to work. I also tried .filter() because its similar but I get the same error -
Making content type read only for log entries in the Django admin
In my admin.py I have class LogEntryAdmin(admin.ModelAdmin): readonly_fields = ( 'user', 'content_type_id', 'object_id', 'object_repr', 'action_flag', 'change_message' ) def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False and admin.site.register(LogEntry, LogEntryAdmin) While I figured out adding 'user' rather than 'user_id', I can't figure out what to add instead of 'content_type_id' to make the content type read only. -
how return relational name on foreingkey django
how i can return the name from the model relational : code: Inactive = 0 Active = 1 state_choices = ( (Inactive, 'Inactive'), (Active, 'Active') ) class Tipe(models.Model): name = models.CharField(max_length=50) details = models.CharField(max_length=100) state = models.IntegerField( max_length=1, choices=state_choices, default=Active, ) class People(models.Model): name=models.CharField(max_length=100) phone=models.CharField(max_length=9, null=True) state = models.IntegerField( max_length=1, choices=state_choices, default=Active, ) tipe = models.ForeignKey(Tipe, on_delete=models.CASCADE, null=True) the question is how i can return tipe.name from model Tipe when i run this: People.objects.all().filter(state=1) this case only return the foreingkey dont the name from my model relational. maybe any suggest please.. thanks -
django models.py field tags has one error
py make: tags = TaggableManager() But when it's done, Error is given! pleas help me!!!! error is : -
How to use dots in Django url?
I am using the following url patterns for accessing my api's. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api_module/api/1.0/', include(router.urls, namespace='api')), ] I created the sql data by posting the following data in Swagger. { "description": "My Test", "name": "SK.Test" } But while accessing in swagger by GET by Id method, I gave the id as name SK.Test and I am getting api not found error. Like this, " Not Found : /api_module/api/1.0/mytest/SK.Test " But if created like, { "description": "My Test", "name": "SK_Test" } /api_module/api/1.0/mytest/**SK_Test** I can able to get the details. I want to get the details by get by id method using with dots. Hope you understood my doubt. Can any one clarify my doubt? -
Using ManyToManyRelationship using 'trough'
I have 2 Entities/Models Person and Event. There is a many to many connection between Person and Event, a Person can participate to multiple events, on an Event multiple Persons are going. A person is not necessary to participate to an Event, an event can be empty. I can do this in Django: class Person(models.Model): name = models.CharField(max_length=100) event = models.ManyToManyField(Publication) This creates a related table with: id | person_id | event_id But I need a person to have more attributes related to Event, besides the keys, like Person's event number, Person's booth etc. In Django documentation I found 'trough' model. What is not clear(didn't found) is related to create/update/delete using forms so I need some examples and how querysets work; Example: In a form I want to select and Event from a list and associated with the Person, and complete in the form the Person's event number, Person's booth etc. How can I use 1) as a formset, for the user on the same form/page to link multiple events to a Person. If an Event or a Person is deleted, is the 'trough' model record deleted automatically or need to do something manually ? -
multiple table/formset in a single form
I am trying to combine 3 different formsets in on form and get user input and save them into DB back. I tried to use inline formset and model formset but both didnt work. This is my DB schema enter image description here Views.py def addDatabase(request, vlan_id=None): SubnetsFormSet = inlineformset_factory(Vlans, Subnets, fields=('subnet', 'dhcp', 'dhcp_start', 'dhcp_end', 'dns', 'rdp',), fk_name=vlan_id, can_delete=False, form=SubnetsForm) GatewaysFormSet = inlineformset_factory(Vlans, Gateways, fields=('vip','master', 'backup', 'nat',), can_delete=False) if request.method == 'POST': vlanFormSet = VlansForm(request.POST, prefix='vlan') subnetsFormSet = SubnetsFormSet(request.POST, request.FILES, instance=vlan_id, prefix='subnet') gatewaysFormSet = GatewaysFormSet(request.POST, request.FILES, instance=vlan_id, prefix='gateway') if vlanFormSet.is_valid() and gatewaysFormSet.is_valid() != False: vlanFormSet.save(commit=False) gatewaysFormSet.save(commit=False) return render(request, 'niro/output.html', { 'vlanFormSet': vlanFormSet, 'subnetsFormSet': subnetsFormSet, 'gatewaysformset': gatewaysFormSet }) else: vlanFormSet =VlansForm(prefix='vlan') gatewaysFormSet = GatewaysFormSet(prefix='gateway', instance=vlan_id) context = {'vlanFormSet': vlanFormSet, 'subnetsFormSet': subnetsFormSet, 'gatewaysFormSet': gatewaysFormSet } return render(request, 'niro/addDatabase.html', context) models.py from django.db import models class Subnets(models.Model): subnet = models.TextField(primary_key=True) # This field type is a guess. vlan = models.ForeignKey('Vlans', on_delete=models.CASCADE, blank=True, null=True) dhcp = models.NullBooleanField() dhcp_start = models.GenericIPAddressField(blank=True, null=True) dhcp_end = models.GenericIPAddressField(blank=True, null=True) dns = models.GenericIPAddressField(blank=True, null=True) rdp = models.NullBooleanField() class Meta: managed = True db_table = 'subnets' class Gateways(models.Model): vip = models.GenericIPAddressField(primary_key=True) vlan = models.ForeignKey('Vlans', on_delete=models.CASCADE, blank=True, null=True) master = models.GenericIPAddressField(blank=True, null=True) backup = models.GenericIPAddressField(blank=True, null=True) nat = models.GenericIPAddressField(blank=True, null=True) vhid … -
i can't see all data in the templates
in my rider_detail.html I should be able to see a table with the rider's score, but i can't see it my model.py: class Rider(models.Model): id_rider = models.IntegerField(default = 0,blank= True, primary_key=True) [...] def __str__(self): return self.display_name class Risultato(models.Model): TYPE_CHOICES = (('SR','sr'),('ITT', 'itt'),('HC', 'hc'),('1C','1c'),('TTT','ttt')) id_ris = models.IntegerField(default = 0,blank= True, primary_key=True) id_rider = models.ForeignKey(Rider,related_name='rider', on_delete=models.CASCADE) id_stage = models.ForeignKey(Stage,related_name='team', on_delete=models.CASCADE) type_ris = models.CharField(choices=TYPE_CHOICES,max_length = 256,blank= True) rank = models.IntegerField(default = 0,blank= True) punti = models.IntegerField(default = 0,blank= True) def __str__(self): return str(self.id_ris) my view.py: class RiderDetails(DetailView): model = Rider template_name = 'game/rider_detail.html' def get_context_data(self, *args, **kwargs): context_data = super().get_context_data(**kwargs) context_data['risultato_qs'] = Risultato.objects.filter(id_rider=self.object) return context_data my rider_detail.html {% extends 'game/base.html'%} {% block content %} <h1>{{ rider.display_name }}</h1> <p> <h3>age:</h3>{{rider.age}} <h3>nationality:</h3>{{rider.nationality}} <h3>height:</h3>{{rider.height}} <h3>weight:</h3>{{rider.weight}} <h3>team:</h3>{{rider.team}} </p> <h3></h3> <h2> Score history</h2> <table> <tbody> {% for risultato in risultato_qs %} <tr> {{ risultato }} <td>{{ risutato.type_ris }}</td> <td>{{ risutato.punti }}</td> ... etc ... </tr> {% endfor %} </tbody> </table> {% endblock %} screen of the page i've installed django debug toolbar to see if my queries were right, and they are. in fact we see 2 results one with 100 points ("Punti") and one with 50 screen of query results in django dubug toolbar -
Categories and subcategories Django
I need to show a subcategory, depending on the type of category that was shown. Models.py class ProductCategory(models.Model): name = models.CharField(max_length=64, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) -
Passing request.POST vs the request itself to a django form
I am using following form to upload multiple images. class AlbumForm(forms.Form): album_name = forms.CharField(label='Titel', max_length=100, required=True) album_description = forms.CharField(label='Beschrijving', widget=forms.Textarea) images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) In the receiving view i noticed that when i pass request.POST to the form I cannot access the images in the form. On the other hand when i pass the request itself to the form i can access the files but cannot use the form.isValid() method. Only the multiple image file is not available, the two other values are available as usual. def post(self, request, *args, **kwargs): images_form = AlbumForm(request) ... if images_form.is_valid(): images = images_form.data.FILES.getlist('images') Imgur().create_album(title=images_form.album_name, description=images_form.album_description, images=images) ... Following is the html code for the form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{images_form|crispy}} <input class="" type="submit" value="save"> </form> What is the reason for this difference or what am i doing wrong? -
django/celery/SQS multiple queues
I have tried several variations on routing tasks to 2 different SQS queues with no success -- and lots of conflicting instructions from the docs and other posts. If I leave OFF the default queue, it consistently creates the "celery" queue, which I don't want. In my settings.py I have tried both with and without the default queue: CELERY_DEFAULT_QUEUE = 'elastic-broker.fifo' CELERY_ROUTES = { "reindex.tasks.reindex": {"queue": "user-actions-broker.fifo"}, "reindex.tasks.rebuild": {"queue": "elastic-actions-broker.fifo"}, } Upon another SO thread I moved this into celery.py: task_exchange = Exchange('default', type='direct') task_create_missing_queues = False task_queues = [ Queue('user-actions-broker.fifo', task_exchange, routing_key='user'), Queue('elastic-actions-broker.fifo', task_exchange, routing_key='elastic'), ] task_routes = { "reindex.tasks.reindex": {"queue": "user"}, "reindex.tasks.rebuild": {"queue": "elastic"}, } My reindex/tasks.py: @app.task(bind=True, name="reindex", max_retries=3) def reindex(self, env,type,id): try: index(env,type,id) except Exception as e: self.retry(e=e, countdown=180) #named differently so it uses another queue @app.task(bind=True, name="rebuild", max_retries=3) def rebuild(self, env,type,id): try: index(env,type,id) except Exception as e: self.retry(e=e, countdown=180) This is python3, django 2.0, celery 4.1.0, boto3 1.4.7, kombu 4.1.0 -
AWS or Google cloud for deploy - Django
I'm developing a django app that is basically for student surveys. Which application is best to do the deployment in the cloud, AWS or Google Cloud?, taking into account that my project is developed with the following features: Python 3.6.4 Django 2.0.3 DB: Postgres I hope that the app will resist 1000-1500 simultaneous users, this would be the extreme case. Generally there would only be 100 users online at certain times of the day. The rest of the time only a few are connected. What would be the best choice between AWS and GoogleCloud, taking into account ease of deployment, cost and stability of the app? I ask this because in the official AWS and Google Cloud tutorials they have tutorials to do it but they mention that it must be with python 2.7 which is not supported by Django 2.0.3. -
Django two projects on two separate servers with one database
I have a Django application that does quite expensive computation and then populates a database. I would like to serve the results using the Django Rest Framework. I would like to keep the application and the API on separate server instances so that I can ensure that the outgoing API is never deprived of resources. This means that both projects will be using the same tables in a shared database. Is there a way to achieve this without at least one of the projects having to perform raw SQL queries? I.e. Can I share both the database and the models (with querysets etc) between two projects on separate servers? Or is that not possible? Note: I've looked at a lot of similar questions but the answers were not useful. Thanks! -
how to two apps from django to conect one db postgresql
I have a little question. I have an app in Django rest framework with PostgreSQL(the project called djangoFall), and I build other projects with Django called djangoRuim, but I don't know how to connect and read the tables in the djangoRuim for example djangoFall connect with the PostgreSQL is working DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'colonybitdb0', 'USER': 'postgres', 'PASSWORD': 'root2017', 'HOST': '127.0.0.1', 'PORT': '5432', } } in here I can read tables like this from djangoFall.profile_clbt.models import HelperNotificationMsg djangoRuim connect with the same connect PostgreSQL DB is working but I don't how to read the tables DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'colonybitdb0', 'USER': 'postgres', 'PASSWORD': 'root2017', 'HOST': '127.0.0.1', 'PORT': '5432', }} in here I can't read the same table from .models import HelperNotificationMsg # wrong true ? because here I don't have models. please help me, how to read these tables. -
Display row number in django
Here is the situation: I have a Transaction model that is supposed to register some financial transactions and I want to know the actual number of the transaction. Initially I used the primary key but I wanted to have a separate field to keep track of this because, if a row is deleted, I want the number of the line to be decremented. For instance, if I have 10 rows, I add the number 11, I delete it and when I add a new line, it will be number 11 (and not 12 with the primary key). I realize that this solution is fine only if the last row is deleted. What I did was to create a model (Meta_Stuff) to store the actual transaction number. Then I created methods to decrements and increments the transaction number when a transaction is deleted or created. Here is the code: class Meta_Stuff(models.Model): # only one instance transac_number = models.IntegerField(default=1) def __str__(self): return self.transac_number @classmethod def get_lastnumber(cls, default=1): return cls.objects.get(pk=1).transac_number # number = get_object_or_404(cls, pk=default) # return number.transac_number @classmethod def increment_lastnumber(cls): new = cls.objects.get(pk=1) new.transac_number += 1 new.save() @classmethod def decrement_lastnumber(cls): new = cls.objects.get(pk=1) if new.transac_number >1: new.transac_number -= 1 new.save() class Transaction(models.Model): … -
change variables defined in __init.py in django from other file
my init.py in django project from pymodm.connection import connect, _get_db from pymongo import MongoClient client = MongoClient() entity_record_clctn = client['platform_configuration'].entity_record_model entity_clctn = client['platform_configuration'].entity_model my tests.py in django project from data_upload import client, entity_clctn, entity_record_clctn class EntityRecordsTests(unittest.TestCase): @classmethod def setUpClass(cls): print("setup") global client global entity_clctn global entity_record_clctn entity_record_clctn = client['test_database'].entity_record_model entity_clctn = client['test_database'].entity_model i am not able to change variables defined in init.py when these varibles are used in other files like views.py where i use them they point to the earlier values only can i do it? how? this is my view.py from data_upload import entity_clctn, entity_record_clctn def get_entity_keys_by_name(name): entity = entity_clctn.find_one({"name": name}) return [entity['entity_primary_key'], entity['entity_display_name']] -
Expiring session on browser close
I've read that you can put the following line of code in settings.py to expire a user's session on browser close: SESSION_EXPIRE_AT_BROWSER_CLOSE = True I've implemented this, but when I close the browser, I can reopen it and the user is still logged in. Any thoughts on this? Thanks! -
Error on create choice field
i'm creating a choice field but dont show my dropdown on the template: my model: Inactive = 0 Active = 1 state_choices = ( (Inactive, 'Inactive'), (Active, 'Active') ) class Tipe(models.Model): name = models.CharField(max_length=50) details = models.CharField(max_length=100) state = models.CharField( max_length=1, choices=state_choices, default=Active, ) class People(models.Model): name=models.CharField(max_length=100) phone=models.CharField(max_length=9, null=True) state = models.CharField( max_length=1, choices=state_choices, default=Active, ) tipe = models.ForeignKey(Tipe, on_delete=models.CASCADE, null=True) the forms.py: class PeopleForm(forms.Form): name = forms.CharField(max_length=100) name.widget.attrs.update({'class':'form-control', 'required': 'true' }) phone = forms.CharField(max_length=9) phone.widget.attrs.update({'class':'form-control', 'minlength':'9'}) optionState = (('1', 'Active'),('0', 'Inactive'),) state = forms.ChoiceField(choices=optionState ) state.widget.attrs.update({'class':'form-control', 'required':'true'}) tipe = forms.ModelChoiceField(queryset=Tipe.objects.filter(state=1), widget=forms.Select) this return on my template for type: <select id="id_tipe" name="tipe"> <option value="" selected="selected">---------</option> <option value="1">Tipe object</option> <option value="3">Tipe object</option> </select> dont show values on my dropdown only show Tipe object dont names of tipes models. please any suggest.. thanks !! -
Django-Weasyprint image not rendered
I have used Weasyprint to render my HTML file into a PDF. However,the image is not being displayed. I tried the solution for a similar problem posted here and rewrote my code as so: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % emp_id pdf_doc = HTML(string=render_output,base_url=request.build_absolute_uri()).render() pdf_doc.write_pdf(response) return response I have define the img tag in my template like below: <img class="logo" src="static/app/nineleaps.png" alt="Not Found"> The PDF does not display the image and displays "Not Found" instead of it. Is there a solution to this? Other html to pdf converters don't render my template as accurately as this, so I would prefer something that uses WeasyPrint only. -
How to work with Djangp-filters?
I must to do some interesting filter. I must to do 2 lists: 1. tag_type - user can choise several tag_type 2. tag_value - user can choise several tag_value for choised tag_type. I'm starting in Django and I have no idea how can I do this. How to relate tag_type with tag_value? User choise tag_type User choise tag_value for choised tag_type and the filter should output the selected tag_type with selected properties(tag_value) Models: enteclass TagsEpisodes(models.Model): tag_id = models.AutoField(primary_key=True) episode = models.ForeignKey('Episodes', models.DO_NOTHING) tag_type = models.ForeignKey('TagsTypes', models.DO_NOTHING) tag_value = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.episode class Meta: managed = False db_table = 'tags_episodes'r code here template: {% block sidebarcontent %} {% if not user.is_authenticated %} <p>-----</p> {% else %} <aside> <form action="" method="get"> {% crispy filter.form filter.form.helper %} <input type="submit" value="Filter"/> </form> </aside> {% endif %} {% endblock %} filters: class TagsEpisodesListFilter(df.FilterSet): tag_type = df.ModelMultipleChoiceFilter( name='tag_type', queryset=TagsTypes.objects.all(), label=' Mark tag types', ) tag_value = df.CharField( name='tag_value', lookup_expr='contains', label='Select tag values, you can use commas', ) class Meta: model = TagsEpisodes fields = { 'tag_type': [], 'tag_value': [], } views: class TagsEpisodesList(LoginRequiredMixin, PagedFilteredTableView): model = TagsEpisodes table_class = TagsEpisodesTable filter_class = TagsEpisodesListFilter formhelper_class = TagsEpisodesListFormHelper template_name = 'data_analysis/tags_episodes.html' login_url = 'login/' … -
List(array) of HTML element with django 2.0.6
I'm passing a list of HTML element to the views.py from html through post but Im just getting the last value. here is the html code that i used, multiple lines of this one <input name="idborrow[]" id="borrow" value='+element[i].id+'> and here is my code in the views.py if request.method == 'POST': idborrow = request.POST.get('idborrow[]', '') print (idborrow) in the console, it just prints the last value, how to get the whole list of values -
Problems with testing in django (dev db - postgresql, test db - sqlite)
I'm writing a project in python / django, which uses the postgresql database. Now I want to write tests for some of my models, views, etc., but I want them to work with a separate in-memory database (SQLite3). The problem is that in the postgresql database all tables are in some scheme, i.e. my model looks like this: class Service(models.Model): # some fields # ....... class Meta: # double quotes are required for the correct # migration to the existing postgresql db!!!! db_table = '"processing"."service"' As far as I know, in SQLite databases there is no concept of "schema", so I created tables in the SQLite test database in this way: CREATE TABLE `processing.service` (...) But when I execute migrate commands the error is displayed: File "/home/dm/Projects/python/toolkit/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/dm/Projects/python/toolkit/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 301, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: unknown database "processing" If I created a table with the following query: CREATE TABLE `"processing"."service"` (...) migrate command are successful completed, but command Service.objects.all() raised the error: File "/home/dm/Projects/python/toolkit/venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/dm/Projects/python/toolkit/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: processing.service I understand why it is output, … -
Sum of objects' prices in Django template
I would like to compute the total of a shopping cart in my template: This is my template with a table of products. I tried to use a Generator expression in my cart method but it doesn't work. Any thoughts? cart.html <table> {% if not cart_list %} {{ "The cart is empty" }} {% else %} <tr> <th>Name</th> <th>Price</th> </tr> {% for product in cart_list %} <tr> <td>{{ product.name }}</td> <td>${{ product.price }}</td> </tr> {% endfor %} <tr> <td>{{ Total }}</td> <td>{{ total_prices }}</td> </tr> {% endif %} </table> views.py def cart(request): if request.method == 'GET': cart_list = Product.objects.filter(in_cart = True) total_prices = sum(product.price for product in cart_list) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request))