Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error ValueError at /admin/parcare/parking/ 'ParkingForm' has no field named 'parking_off'
I created a nice app, but i got this error when trying to change a filed date ==> ValueError at /admin/parcare/parking/ 'ParkingForm' has no field named 'parking_off'. TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', ) My admin.py class ParkingModelAdmin(admin.ModelAdmin): list_display = ["user", "location","parking_on", "parking_off"] list_display_links = [ "location"] list_editable = [ "parking_on"] list_filter = ["location"] search_fields = ["location", "parking_on"] date_hierarchy = 'parking_on' save_as = True save_on_top = True change_list_template = 'admin/change_list_graph.html' class Meta: model = Parking def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not obj: user = request.user form.base_fields['user'].initial = user form.base_fields['email'].initial = user.email return form def save_model(self, request, obj, form, change): # add an additional message user = request.user messages.info(request, "Dear " + str(user)+ " "+ " please note that your parking plot has been reserved") super(ParkingModelAdmin, self).save_model(request, obj, form, change) admin.site.register(Parking, ParkingModelAdmin) This is my full error: ValueError at /admin/parcare/parking/ 'ParkingForm' has no field named 'parking_off'. Request Method: POST Request URL: http://127.0.0.1:8000/admin/parcare/parking/?location__exact=P3 Django Version: 2.1.1 Exception Type: ValueError Exception Value: 'ParkingForm' has no field named 'parking_off'. Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/forms/forms.py in add_error, line 353 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.0 Python Path: ['/Users/Desktop/Dev/parcare/src', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Wed, 3 Oct 2018 16:15:47 +0300 -
Profiling Django Startup Memory Footprint
I'm trying to optimize my Django 1.8 project's memory usage, and I have noticed that even from initialization, it's using 80+MB, which seems excessive. I observe this when I simply run ./manage shell --plain. By contrast, an empty Django project on startup uses only 30MB. I want to know what's consuming so much memory. I have tried various things to reduce memory consumption, including a fair amount of stripping down of the project by removing its apps and URLs. I tried poking around gc.get_objects but it's not comprehensible. I got excited about tracemalloc so I build a custom Python 2.7.8 with tracemalloc included, only to realize that it won't start tracking until I call start() from the prompt, at which point the memory has already been consumed. Questions: What kinds of things could be causing this high memory floor? What process can I use to determine the consumer? And yes, I realize I badly need to upgrade. Thanks! -
How to stop CharField from clearing its data after a new post request?
How do you stop a char field from clearing data after another post request? I have a django template with two forms (CharField text area widgets). I have made buttons that upload text files into the respective text boxes. If I press one of the two buttons, one text box is filled with data but the other is cleared. How do I make both text forms keep their text content even when different post requests are made? -
Django: using save(commit=false) when saving form extended from form.Forms
I have a many-to-many field and in order to save the retrieved data from the form, initially, I have to save an instance of that table, otherwise, I get an error like: "Order: None" needs to have a value for field "id" before this many-to-many relationship can be used. But the issue is when I have 2 save methods called, they also create 2 different logs(at the first save() it creates the instance and at the letter one it edits it) and this cause the chaos. Therefore, I want to be able to commit=False in the first one and finalize the save in the second save(). Commit is used for ModalForm, however, my form extends form.Forms. views.py if request.method == 'POST': form = OrderAddForm(request.POST) if form.is_valid(): order = Order() order.user = request.user order.save() order.ordered_materials.set(form.cleaned_data['ordered_materials']) order.location = form.cleaned_data['location'] order.note = form.cleaned_data['note'] form.save() else: form = OrderAddForm() forms.py class OrderAddForm(forms.Form): ordered_materials = forms.ModelMultipleChoiceField( queryset=Material.objects.all(), ) location = forms.CharField() note = forms.CharField() ordered_materials.widget.attrs.update({'id': 'materialsid', 'class': 'form-control', }) models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered_materials = models.ManyToManyField('Material') location = models.CharField(max_length=500) note = models.CharField(max_length=30, verbose_name="Note") STATUS = ( ('n', 'None'), ('a', 'Accepted'), ('r', 'Rejected'), ) status_name = models.CharField(max_length=1, choices=STATUS, default='n') def __str__(self): return str(self.id) -
Tango with Django Chapter 6 - URL won't work
I have been going through "Tango with Django" and have been unable to solve this problem myself or by looking online. Would anyone know how to approach it? The relevant page should be opened when I click on the link, but none are going through, which makes me assume something in my view.py file is wrong or even in my url.py or model.py file (index.html seems to be working correctly). Views.py # Create your views here. from django.http import HttpResponse from django.shortcuts import render from Spaces.models import Category, Page def index(request): # Query the databse for a list of ALL categories currently stored. # Order the categories by no likes in descending order . # Retrieve the top 5 only - or all if less than 5. # Place the list in context_dict dictionary # that will be passed to the template engine. category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories': category_list} # Render the response and send it back! return render(request, 'Spaces/index.html', context=context_dict) def about(request): context_dict = {'boldmessage':"Crunchy, creamy, cookie, candy, cupcake!"} return render(request, 'Spaces/about.html', context=context_dict) def show_category(request, category_name_slug): # Create a context dictionary which we can pass # to the template rendering engine. context_dict = {} try: # Can we β¦ -
2 Foreign key fields referencing the same django model leads to migration errors
I have a model named Profile(with various fields), and another model Trans. The model Trans is as follows(both the models in 'accounts' app): class Trans(models.Model): sender=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='sender' receiver=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='receiver') ... Created many instances(in views) using : t=Trans.objects.create(sender_id=profile.pk,receiver_id=prof.pk,..) t.save() Migrating the app leads to error: django.db.utils.IntegrityError: (1062, "Duplicate entry '2' for key 'accounts_trans_receiver_id_592a7105_uniq'") I checked the table structure of accounts_trans in MySql server, and i found that sender_id is taken as a 'MUL' key which means Multiple records can have the same sender(profile). While receiver is not assigned as a 'MUL' key and this I guess is why the migration is not working! I'm not able to alter the receiver_id field to 'MUL' in MySQL database. Can anyone help solve this issue? Thanks in advance. -
How can I set value of DurationField in Django from AdminPanel
I have been searching but unable to find that how can I set value of Duration Field from Admin Panel I want to set that value to 1 year So that latter I can get DurationField value and add it to datetime.datetime.now() to get required result -
How to scale database and Performance in Django?
We are facing issue with Django SQL Performance. Even setting up CONN_MAX_AGE setting, Connections are not closing. Following configurations we used, CONN_MAX_AGE: 5 Is there any place to do the configurations for performance? Can you suggest me any Solution for multiple application servers with Single Database server architecture? -
Django admin panel rejecting authorized superusers
I'm having an issue where I am unable to login to my Django admin panel. I've been through several Questions here on SO and haven't been able to solve my issue yet. Things to note: My sqlite3 back end that was installed by default has the user in question flagged True for is_superuser, is_staff, and is_active. I did create a new super user to try this out by running python manage.py createsuperuser <username> and I can see that user in the sqlite db with the same True values listed above. It still won't authenticate. settings.py import os import json # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CREDENTIALS_FILE = {} with open(os.path.join(BASE_DIR, "project_name/credentials.json")) as f: CREDENTIALS_FILE = json.loads(f.read()) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = CREDENTIALS_FILE["secretKey"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # this line will switch to debug mode whenever the prod web app id # is not in the path being executed. if '/specific_id/' not in os.path.abspath(__file__): DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'dev.dns.net', 'prod.dns.net' ] # β¦ -
Django-xadmin: Filter options based on previous question
xadmin to show a simple form. My question is that i would to know how to filter the options based on input that was given prior. Example. I have a company Foo that has 2 contact persons. What happens now is that when Foo is selected, all the contact persons are shown that are in the database.(including those that are not related to the selected company Foo) The documentation for xadmin is half in chinese and not extensive at all. This question is close but not wat i was looking for because the filtering is done before the form is loaded in. the filtering is not affected by the choice that was made. Filtering select field options in django-admin I hope someone can help me further. i think it is an option that xadmin should have built in but I have no idea where and how. -
Preventing concurrent duplicate database writes in Django/PostgreSQL?
I'm developing a Django-driven API that calls another, external API. It modifies and augments the results received from the external API, creating standard Django model instances for them in a PostgreSQL DB. On future calls to our API with the same parameters, the external API is no longer called, and our previously stored local results are returned instead. Let's say that the calls done to our API are to the endpoints /stuff/thingies and /stuff/thingamabobs. Each endpoint is a separate Django view, and each returns different aspects of stuff. Stuff is the data we retrieve and store from the external API, and thingies and thingamabobs are our two different augmented "views" into this external data. There are no guarantees about which endpoint is called first in any given case, so both endpoints inherit from a mixin class that checks if the results already exist, calls the external API, and stores the results if needed, before actually returning the augmented results. The external API call is expensive and time-consuming (which is why we store the results locally in the first place), and here's the problem: it's possible for both endpoints to be called in rapid enough succession that both of them determine β¦ -
I want to object instead of url in oscar api responce
I am working on oscar based Ecom platform and in the orderList API, I want the object Instead of URL. I am new in Django and oscar. How to do that ,please help me class OrderList(generics.ListAPIView): serializer_class = OrderSerializer permission_classes = (IsOwner,) def get_queryset(self): qs = Order.objects.all() data=[] for q in list(qs): print(q) return qs.filter(user=self.request.user) and it's serializer is : class OrderSerializer(OscarHyperlinkedModelSerializer): """ The order serializer tries to have the same kind of structure as the basket. That way the same kind of logic can be used to display the order as the basket in the checkout process. """ owner = serializers.HyperlinkedRelatedField( view_name='user-detail', read_only=True, source='user') lines = serializers.HyperlinkedIdentityField( view_name='order-lines-list') shipping_address = InlineShippingAddressSerializer( many=False, required=False) billing_address = InlineBillingAddressSerializer( many=False, required=False) payment_url = serializers.SerializerMethodField() offer_discounts = serializers.SerializerMethodField() voucher_discounts = serializers.SerializerMethodField() def get_offer_discounts(self, obj): qs = obj.basket_discounts.filter(offer_id__isnull=False) return OrderOfferDiscountSerializer(qs, many=True).data def get_voucher_discounts(self, obj): qs = obj.basket_discounts.filter(voucher_id__isnull=False) return OrderVoucherOfferSerializer(qs, many=True).data def get_payment_url(self, obj): try: return reverse('api-payment', args=(obj.pk,)) except NoReverseMatch: msg = "You need to implement a view named 'api-payment' " \ "which redirects to the payment provider and sets up the " \ "callbacks." warnings.warn(msg) return msg class Meta: model = Order fields = overridable('OSCARAPI_ORDER_FIELD', default=( 'number', 'basket', 'url', 'lines', 'owner', 'billing_address', 'currency', 'total_incl_tax', β¦ -
Minimising latency for users via aws
I am newbie to aws, i am using aws lambda for my project. How do i minimise the latency rate for my website users.I want to execute my backend logic from the nearest instance/server to the users. I have heard of Route 53, how do i configure that. -
How to sort Querylist in django ( rest api )
class AllStudioListConsoleViewset(FlatMultipleModelAPIView): def get_querylist(self): user = self.request.query_params['user'].replace('-', ' ') print(user) querylist = [ { 'queryset': audio_details.objects.filter(user=user).order_by('-created_on'), 'serializer_class': AudioStudioListConsoleSerializers, 'label': 'audio', }, { 'queryset': VideoStudioDetails.objects.filter(user=user).order_by('-created_on'), 'serializer_class': VideoStudioListConsoleSerializers, 'label': 'video' }, { 'queryset': ShootStudioDetails.objects.filter(user=user).order_by('-created_on'), 'serializer_class': ShootStudioListConsoleSerializers, 'label': 'video' }, ] return querylist How to sort all querylist created_on -
Using django models in functional tests (Selenium)
Since I'm new to TDD, I've got a problem. I have a database that has a specific amount of tickers. I pass those tickers to a django template and I'm trying to write a functional test that will check if the amount of tickers in my template equals to the amount of tickers in my database. functional_tests.py from selenium import webdriver from .models import Ticker browser = webdriver.Firefox() browser.get('http://127.0.0.1:8000/binance/') assert len(browser.find_elements_by_class_name('ticker')) == len(Ticker.objects.all()) browser.quit() But I cannot run this receiving the following error: ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package This is the tree (functional_tests.py is inside one of project's apps): βββ admin.py βββ apps.py βββ functional_tests.py βββ __init__.py βββ management βββ migrations βββ models.py βββ parsers.py βββ __pycache__ βββ templates βββ tests.py βββ urls.py βββ views.py -
Django: How to filter objects by daterange given by user?
I am building an accounting app, I want to filter objects present in my ledger details view via date range which will be given by the user... This is my view: @login_required def ledger1_detail_view(request, pk1, pk2): company_details = get_object_or_404(company, pk=pk1) ledger1_details = get_object_or_404(ledger1, pk=pk2) context = { 'company_details' : company_details, 'ledger1_details' : ledger1_details, 'Debitcount' : journal.debitsum(), 'Creditcount' : journal.creditsum(), 'journal_list' : journal.objects.all(), 'company_list' : company.objects.all(), } return render(request, 'accounting_double_entry/ledger1_details.html', context) ledger1 and journal are two model class... journal is related to ledger through foreign key This is the model: class ledger1(models.Model): Start_Date = models.DateField(default=datetime.now) End_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32) class journal(models.Model): By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) I want to filter the journal which is present in ledger details view by 'Start_Date' and 'End_Date' which the user will give according to their choise... Can anyone tell me how to do this in django? Thank you -
IF conditional statement in Django template does not work
{% if user.resume %} <div class="empty-state-box"> <img src="{% static 'resumes/images/resume-empty-icon.png' %}" class="centered"> <p class="empty-state-text"><b>You currently don't have any resumes.</b><br>Create one and start building your very first resume</p> </div> {% else %} <p>More information here</p> {% endif %} Hi, i'm trying to place an empty state IF a user does not have a resume. ELSE I want to show other information. I can't seem to get it to work. I think I am using the if conditional statement wrong in the template. Any help would be much appreciated! Thank you! -
Jquery code with .hide() function doesn't works in Django template
tying to use jquery in my django template. Here I import jquery from my static. <head> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> ... In tag also have js function <script> $(function () { $('#edit-website-btn').click(function () { $('#account-website').hide(); }); }); </script> and here are my elements <div id="account-website">{{ account.website }}</div> <button type="button" class="btn btn-outline-primary" id="edit-website-btn">Edit </button> But when I click my button ('#edit-website-btn') nothing happens and inside console there are any errors. What is wrong ? -
Tool for temporary data storage in Django
In my PostgreSQL powered Django application, I collect data that are intended to be sent to a third party application through an API that is rate-limited. The procedure is the following: Collect data through a web form Temporarily save the data in a "waiting room" for 24 -48 hours Use an internal mechanism to collect the data and send them to a third party Delete the data that were successfully sent The question is how can I build this "waiting room"? What tool is best suited for this use? -
Django makemessages. Is the any way to makemessages understand gettext in function arguments
I just noticed, that process of python manage.py makemessages on jinja2 templates ignores the construction like {{ abbr(_('N:Notes')) }} Is the any way to make makemessages understand text needed to translate in function arguments? -
How to make ForeignKey to two tables in two different location
I have 2 tables (users, user_shifts) in 2 different files but which are having a foreign key relationship to each other In users, table shift field is a foreign key to shifts table and in shifts table created by field is a foreign key to the user's table. But when I`m running the server it's raising an error that "cannot import users" class Users(models.Model): id = models.AutoIncrement() shift = models.ForeignKey(user_shifts) class Meta: managed = False db_table = 'users' class user_shifts(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) status = models.IntegerField(default=1) created_date = models.DateField(default=datetime.now().date()) created_by = models.ForeignKey(users) class Meta: managed = False db_table = 'user_shifts' -
Django model: Serialize objects filtered with related field
I have two models related with a many-to-many relationship like the following: class ModelA(models.Model): category = models.CharField(max_length=64) class ModelB(models.Model): a_models = models.ManyToManyField(ModelA, related_name="b_models") And a serializer for the ModelA-s: class ModelASerializer(ModelSerializer): class Meta: fields = ( "category" ) model = ModelA When I try to serialize a queryset that results in a filter on one of the ModelA-s fields, it works as expected: filtered_ok = ModelA.objects.filter(category="some category") serialized = ModelASerializer(filtered_ok, many=True).data but when I filter with the related field, the serializer throws the error Got AttributeError when attempting to get a value for field `category` on serializer `ModelASerializer`. The code: filtered_not_ok = ModelA.objects.filter(b_models__isnull = False) serialized = ModelASerializer(filtered_not_ok, many=True).data One more thing I noticed: if I print the filtered results, they look different: print(filterd_ok) # <QuerySet [<ModelA: mycontent1>, <ModelA: mycontent2>]> and print(filtered_not_ok) # (<QuerySet [<ModelA: mycontent3>]>,) The second looks like a list of querysets... but if I call .first() on it, it will return the first object in the queryset... Why do the filters return different types? How could I get the serializer to also work with the result of the related field filter? -
How recurcively get names of all parents in Django model?
I have this model: class Folder(TimeStampedModel): name = models.CharField(max_length=64, blank=False, null=False) parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children') @property def build_family_names(self): # this does not work names = f'{self.parent.build_family_names}' return names How can I get all parent and parent-parent... names from 1 Folder instance? May be some @property or @classmethod? What I have now does not work because I can't call property as model attribute directly. -
Django URL with {% URL %} from data string
I am trying to pass string information into a {% URL %} I am getting the data from data like: {% for p in proj %} <tr> <td> <a href="{% url {{ p.dir }} %}"> {{ p.name }} </a> </td> </tr> {% endfor %} The expected result would be something like: <a href="{% url "path" %}">Sample Info</a> Is this even possible? Thanks. -
Filtering list of elements based on a model @property in a ViewSet - Django Rest Framework
Below is a data structure that can be accessible trough an endpoint built with Django Rest Framework: "sites": [{ "id": 1, "configs": [ { "id": 1, "subconfigs": [ { "id": 1, "name": "subconfig_1", "macro_subconfigs": [1, 2] "flag": true }, { "id": 2, "name": "subconfig_2", "macro_subconfigs": [1] "flag": false }, { "id": 3, "name": "subconfig_3", "macro_subconfigs": [2] "flag": false }, ], "macro_sub_configs": [ { "id": 1, "flag": true, "subconfigs": [ { "id": 1, "name": "subconfig_1", "macro_subconfigs": [1, 2] "flag": true }, { "id": 2, "name": "subconfig_2", "macro_subconfigs": [1] "flag": false }, ], "name": "macro_subconfig_1" }, { "id": 2, "flag": false, "sub_configs": [ { "id": 1, "name": "subconfig_1", "macro_subconfigs": [1, 2] "flag": true }, { "id": 3, "name": "subconfig_3", "macro_subconfigs": [2] "flag": false }, ], "name": "macro_subconfig_2" }, ] } ] }] My models are the followings: Config class Config(TimeStampedModel): site = models.ForeignKey("site.Site", related_name="configs") @property def macro_sub_configs(self): try: return MacroSubConfig.objects.filter(subconfigs__config__pk=self.pk).distinct() except MacroSubConfig.DoesNotExist: return tuple() SubConfig class SubConfig(TimeStampedModel): name = models.CharField(max_length=200) config = models.ForeignKey( "Config", related_name="subconfigs", on_delete=models.CASCADE ) flag = models.BooleanField(default=True) MacroSubConfig class MacroSubConfig(TimeStampedModel): name = models.CharField(max_length=100) subconfigs = models.ManyToManyField(SubConfig, related_name="macro_subconfigs") flag = models.BooleanField(default=True) And my serializers: class SiteConfigSerializer(serializers.HyperlinkedModelSerializer): configs = ConfigSerializer(many=True) class Meta: model = Site fields = ("name", "configs") class SubConfigSerializer(serializers.ModelSerializer): β¦