Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web programming in PyCharm. Making a ecommerce website
My question is about a website programming syntax error. How to correct this error? def product_pre_save_receiver(sender, instance, *args, **kwargs) if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=Product, weak=False ) While making migrations in shell, I am getting a syntax error in the first line. -
"StopIteration" exception while using factory_boy in django setUp() tests
I have the following factory: class ContactFactory(DjangoModelFactory): name = Faker('company') industry = Iterator(Industry.objects.all()) class Meta: model = 'sales.contact' @post_generation def requested_devices(self, create, extracted, **kwargs): if create: self.requested_devices.add( MSize.objects.first() ) And I'm trying to write a test such as: class TestUserCanAskQuestion(TestCase): @classmethod def setUpTestData(cls): call_command('insert_initial_data') def setUp(self): self.contact = ContactFactory() But everytime I run the test, it results in "StopIteration" error. If I move the ContactFactory() outside of class, the error disappears. I'm I missing something? or it's a bug in factory boy or django? (I'm using factory_boy==2.11.1 and django==2.1.2) -
Dynamic Field Serialization using Serpy
I was using DRF serializers.ModelSerializerbut with hundred of data to serialize, it's slow and has a huge CPU time. I've switched to Serpy [GITHUB LINK], it's a great library and REALLY FAST, works like a charm, dropping the serialization time to 50/70% less than the standard DRF ModelSerializers. Using the DynamicModelSerializer, in DRF, my life was quite easy, in fact, basically, i was able to use the fields=('all') in my old DRF Serializer classed and then, adding the extra exclude parameter, i was able to exclude some unuseful parameters from my serializer, here is the DynamicModelSerializer class: class DynamicModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): fields = kwargs.pop('fields', None) add_fields = kwargs.pop('add_fields', None) exclude = kwargs.pop('exclude', None) nest = kwargs.pop('nest', None) if nest is not None: self.Meta.depth = nest super(DynamicModelSerializer, self).__init__(*args, **kwargs) if fields is not None: allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) if add_fields is not None: for field_name, field_class in add_fields.items(): ### first pop the old field class from the fields if it's there if field_name in self.fields: self.fields.pop(field_name) ### now add the field to the fields self.fields[field_name] = field_class if exclude is not None: for field_name in exclude: self.fields.pop(field_name) Now, how i β¦ -
Django admin missing add edit buttons when using get_form()
When overriding the get_form() method in a ModelAdmin class, the "Add" and "Edit" (plus sign and pencil) icons do not appear next to any field on the admin page, even though permissions are correct. As soon as I remove the overridden get_form() method, the icons appear. I am using a form factory to render the ModelForm class to do some queryset filtering based on the current user, so I can't use form = <ModelForm> in the admin (the form needs to capture the HttpRequest object). (Using Django 2.1 and Python 3.6) admin.py @admin.register(Reservation) class ReservationAdmin(admin.ModelAdmin): list_display = ('room', 'check_in_date', 'check_out_date', 'guest', 'reserved_by', 'reserved_on') inlines = (RoomChangeInline,) fieldsets = ( (None, { 'fields': ( ('room', 'guest'), ('check_in_date', 'check_out_date'), ('adults', 'children'), ('subtotal', 'taxes', 'deposit'), ('reserved_by', 'reserved_on') ) }),) def get_form(self, request, obj=None, **kwargs): return reservation_admin_form_factory(request) forms.py def reservation_admin_form_factory(request): class ReservationAdminForm(forms.ModelForm): class Meta: model = Reservation exclude = [] widgets = { 'check_in_date': forms.DateInput(attrs={'type': 'date'}), 'check_out_date': forms.DateInput(attrs={'type': 'date'}) } """ I have an __init__() method, but even if I remove it the problem remains, so I am not showing it here. """ return ReservationAdminForm -
Filter by file size in Django (FileField)
I have an a model: class MyModel(models.Model): file = models.FileField(verbose_name='File', upload_to="files/") I can get file size in bytes: size = my_model_instance.file.size How to filter by file size in Django? Something like that: MyModel.object.filter(file.size__lt=128) -
Howto combine DjangoRestFramework routers for different apps
I use Django 2.1 and DRF and a planning a quite larger application with many plugged-in apps. I'd like to have ONE /api URL for the DRF as endpoint, but allow each app to have a special model exposed over the REST endpoint, e.g.: In the main urls.py: router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ # ... path('api/', include(router.urls)), # ... ] and in foo_app/urls.py: router = routers.DefaultRouter() router.register(r'foomodel', FooModelViewSet) Now, /api/foomodel produces a 404 Error. The foo_model/urls.py gets imported (a print statement there is printed at Django start), and all the other foo_model.urlpattern[path...] are recognized and work fine. How can I define custom api model endpoints for a central api REST endpoint? I didn't find anything in the documentation. Thanks in advance. -
Using User built in model in Django
I am trying to save the username of the current logged in user from the django built in User model. model.py class Notes(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) note = models.CharField(max_length = 100000000) def __str__(self): return self.note views.py @login_required def saveNote(request): if request.method == 'POST': note = request.POST['note'] print(request.user.username) note = Notes(username=request.user.username ,note = request.POST["note"]) note.save() return redirect('/') But this shows an error. I want to save the current user in the Notes table along with the note. How am I supposed to do this? -
import django ModuleNotFoundError: No module named 'django' after install python 2
I have 3 django projects (version 1.11.15), and all errors after I accidentally install Python 2 (I installed the react native), before I used python 3.6.5 via Anaconda. some of my project files appear error symbols, when I try to run "manage.py runserver", it can't run, and an error appears. I uninstalled Python 2, and reinstalled my Anaconda (Python 3.6.5), but it didn't work. in my opinion there is a problem in the path, but I don't know what that is. I've been looking for a solution, but nothing works. Anyone has a solution? ... thanks my python version this is my python path, I don't know what to add here, I just followed a few tutorials that I found -
Django Attribute Error - Form object has no attribute 'is_valid'
I am receiving an error, object has no attribute 'is_valid', when trying to insert form data into a form. Below is the structure of my code: Views.py: def add_user(request): form = Car(request.POST) if request.method == 'POST' and form.is_valid(): last_store = form.cleaned_data.get['value'] make = request.POST.get('make', '') model = request.POST.get('model', '') .. car_obj = Car(last_store = last_store, make = make, model = model, series = series, series_year = series_year, price_new = price_new, engine_size = engine_size, fuel_system = fuel_system, tank_capacity = tank_capacity, power = power, seating_capacity = seating_capacity, standard_transmission = standard_transmission, body_type = body_type, drive = drive, wheelbase = wheelbase, available = available) car_obj.save() return HttpResponseRedirect('/inventory/add/') else: form = Car() return render(request, 'cars/inventory-add.html', {}) Class: class Car(models.Model): make = models.CharField(max_length=200, null=False) model = models.CharField(max_length=200, null=False) series = models.CharField(max_length=200, null=False) series_year = models.IntegerField(null=False) price_new = models.IntegerField(null=False) .. last_store = models.ForeignKey(Store, on_delete=models.DO_NOTHING, related_name="last_store") available = models.BooleanField(null=False, default=True) def __str__(self): return(self.make + " " + self.model) The error lies within the last_store as without form.is_valid(), apparently I cannot use form.cleaned_data, but form.is_valid() seems to not even exist? As seen in the class, last_store is of type a foreign key, therefore I am struggling to set the default value for it when the user enters input into β¦ -
Iterating fields selected by name in template
I need to do a lot of popup select windows in Djago application, basically for each model and show only some selected fields (each time different). I would like make universal view, which would get model name, list of field names and make such popup-select. Something like that (simplyfied): def MyView(request,model_name,field_names): a_model=get_model(model_name) paginator = Paginator(a_model.objects.order_by('id'),30) values = paginator.page(1) contex={'values':values, 'field_names':field_names} return render(request, 'popup.html',context) popup.html: <tr> {% for fn in field_names %}<th>{{fn}}</th>{% endfor %} </tr> {% for val in values %}<tr> {% for fn in field_names %}<td>{{val.'fn'}}</td>{% endfor %} // val.'fn' does not work </tr>{% endfor %} val.'fn' does not work, but I would like something to this effect, to get result of MyView(request,'Friends',('name','nick','detail123')) name | nick | detail123 -----+------+---------- James| Joe | horses Peter| Pet | cars ........ Thanks for help -
DJANGO PYTHON AND PHP Recommendations for a pre built plugin for reverse auction platform
Can I have recommendations for an app for a django python reverse auction plugin please . I am developing a django project and I am looking to integrate the ability for providers to bid on client listings. Any recommendations and tips please. -
How can I highlight words from my search result based on my query?
I would like the words i used to search for results to be highlighted in the results. How would i go on about doing this? I have looked at examples using JS but they don't seem to work with my code. html: (Search) <input type="text" name="q" placeholder="Search..." required value="{{ query|escape }}" size="100" autofocus> <input class="buttonCopy button1" type="Submit" value="Search"> (Results) {% for resp in results %} <tr> <td style="border: 1px solid">{{ resp.Question.Statement }}</td> <td style="width: 70%; border: 1px solid"><div id="resp{{forloop.counter}}" style="height: 200px;overflow-y:auto;overflow-x:hidden">{{ resp|escape|linebreaks }}</div></td> <td><button class="buttonCopybutton3",onclick="copyFunction('text{{forloop.counter}}')">Copy</button></td> <td><textarea id="text{{forloop.counter}}" style="display:block; width:0; height:0; opacity:0">{{ resp }}</textarea></td> <td> <label class="container"> <input type="checkbox" id="chck" name="responseCheck" onClick="checkbox();" value="{{ resp }}"><br></br> <span class="checkmark"></span></label> </td> <td><textarea id="show" name="responseCheck" style="display:block; width:0px; height:0px; opacity:0"></textarea><br></br></td> </tr> {% endfor %} views.py: if query: newquery = stopwords.strip_stopwords(query) terms = newquery.split() for term in terms: qset &= ( Q(Question__Statement__icontains=term) | Q(Response__icontains=term) ) results = Response.objects.filter(qset).distinct() else: results = [] posts = '' return render_to_response("app/search.html", { "results": results, "query": query, "noOfResults": len(results), "username": username, "queryR": queryR, "topicList": topicList, "clientList": clientList, }) -
Google maps production (Django Wagtail and Wagtail Geo Widgets)
I am running Django Wagtail and using a plugin called wagtailgeowidget and when I run it on my laptop it works just fine. However when I use it on my production apache2 server I keep getting the error in the console. js?key=my_key&language=en:51 Geocoding Service: This API project is not authorized to use this API. For more information on authentication and Google Maps JavaScript API services please see: https://developers.google.com/maps/documentation/javascript/get-api-key _.Gc @ js?key=my_key&language=en:51 My production server doesn't have a domain name it is a straight IP. I have tried three different configurations for google maps API. None HTTP referrers (http://ip/, http://*ip/, *ip*) IP Addresses (IP) None of the configurations has worked. I would imagine at the very least the configuration "None" would be insecure but at the very least it would work. However it still doesn't work. -
Django no reverse match error while using url dispatcher
I have an app that runs some long running tasks and I am showing the log of runs (a table) that a user has made on a particular page. There is a result location in the table on the page, where I would like for it to be a hyperlink and when clicked, gets redirected to a page where the user can see the result. I am getting a : NoReverseMatch: Reverse for 'past_run_results' with arguments '(u'1649103c-67d0-47f9-a085-401c02acff6a',)' not found. 1 pattern(s) tried: ['discovery-engine/past-runs/(P<task_id>[-\\w]+)$'] and I can't figure out what is wrong /urls.py [ url(r'^past-runs/$', views.past_run_log, name="previous_runs"), url(r'^past-runs/(P<task_id>[-\w]+)$', views.past_run_results, name="past_run_results"), ] /views.py def past_run_log(request): past_fifty_runs = JobLog.objects.all().filter(user=request.user)[:50] context_dict = {"past_runs": past_fifty_runs} return render(request, 'website/previous_runs.html', context=context_dict) def past_run_results(request, task_id): get_result = JobLog.objects.get(task_id=task_id) read_location = os.path.join(os.getcwd(), "results", get_result.result_location) with open(read_location) as f: result_data = json.load(f) if result_data: return render(request, 'website/previous_runs_results.html', context={"result": result_data}) else: return render(request, 'website/previous_runs_results.html', context={"result": "No result found."}) /previous_runs.html <div class="container-fluid"> <div class="row"> <div class="col-xs-12"> <h1>History</h1> <table data-toggle="table" data-search="true" data-pagination="true" class="table-responsive"> <thead> <tr> <th>Task Name</th> <th>Username</th> <th>Algortihm Name</th> <th>Start Time</th> <th>Duration (secs)</th> <th>Status</th> <th>Result</th> </tr> </thead> <tbody> {% for run in past_runs %} <tr> <td>{{run.task_name}}</td> <td>{{run.user}}</td> <td>{{run.algorithm}}</td> <td>{{run.time_started}}</td> <td>{{run.time_taken | floatformat:2}}</td> <td>{{run.status}}</td> <td><a href="{% url 'past_run_results' run.task_id %}">{{run.result_location}}</a></td> </tr> {% endfor β¦ -
Django ManyToMany relationship details of details
I have read well the Django documentation on the ManyToMany filed. Especially the one here . I am quite clear of the things that can be done with it. For instance if I have a Category model and a Startup model where a category can have many startups and a startup can belong to many categories, then ManyToMany relationship is useful here. I am able to list all categories on my template, each category is clickable and leads to a list of all startups on another template belonging to this category. Now, having had this, I want to go a bit further. Having gone to the detail page of a specific category, which is a list of startups belonging to it, I want each item in this details page to also lead to another details page where I can display more information about a specific startup. My main problem is now how I can implement it. I have gone through the many questions asked relating to ManyToMany field and its queries, especially here but they seem to all be taking about how to access the related objects to a category for example in a details page and it ends there. β¦ -
Django version for Python 3.7.1
What is the required version to install for Django, i am using Python 3.7.1, and everything i do keeps crashing, as it doesn't install on My PC. I am using a windows 8 operating system -
Django and HTML template : Group by panels with common object attributes
One more time, I come back to you in order to get advices or your help. I'm displaying in my django template a list of objects and I would like to sort them through a common attributes : category. Each object displayed (a publication) gets some attributes : category, format, language ... For example : The white text with blue background indicates the category. I have 2 publications with category = BIOLOGICAL STANDARDISATION PROGRAMME and 1 publication with category = TEST I would like to group both BIOLOGICAL STANDARDISATION PROGRAMME in one panel but I don't find a way to do that. This is my HTML template file : {% for element in test_research|dictsort:"publication.category.name" %} <div class="col-sm-12"> <div class="panel panel-default request-panel"> <div class="panel-heading" role="tab"> <h4 class="panel-title"> {{ element.publication.category }} </h4> </div> <div class="panel-body"> <div class="row"> <div class="col-sm-9"> <p class="request-publication">{{ element.publication }} </p> </div> <div class="col-sm-3 request-cover"> {% if element.publication.cover %} <a href="{{ element.publication.cover.url }}" target="_blank"> {% thumbnail element.publication.cover "40x40" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %}</a> {% endif %} </div> </div> </div> <div class="panel-footer"> <div class="row"> <table> <tbody> <tr> <td class="col-md-1"> <div class="material-switch pull-right"> <input id="someSwitchOptionSuccess_{{ element.id }}" name="DocumentChoice" type="checkbox" β¦ -
Add a field to raw data to prevent serialization error
Assume I have two models and their serializers like this: class Billing(models.Model): ... class Transaction(models.Model): billing = models.ForeignKey(Billing, null=False, blank=False) ... class TransactionSerializer(serializers.ModelSerializer): billing = serializers.PrimaryKeyRelatedField(queryset=Billing.objects.all()) class Meta: model = Transaction fields = '__all__' Now I want to have an endpoint to post new transaction to a billing, something like this: post http://address/billings/{id}/transactions [{other fields except billing because the billing exists in the address}] For this purpose I have written a viewset like this: class BillingTransactionList(generics.ListCreateAPIView): serializer_class = TransactionSerializer def get_queryset(self): billing = get_object_or_404(Billing.objects.all(), pk=self.kwargs['pk']) return Transation.objects.filter(billing=billing) def perform_create(self, serializer): billing = get_object_or_404(Billing.objects.all(), pk=self.kwargs['pk']) return serializer.save(billing=billing) But if billing does not exist in data that I get from request, serializer would be failed becuase it needs the billing in raw data of request. I have the billing from endpoint and I just want that serializer accepts the data and further I will add the billing as I have done in perform_create. There is an option to add required=False to TransactionSerializer but I need this serializer in another places with required=True, Also there is an another solution to write another serializer, but in my real example the serializer is a big class and I do not want to write it again. β¦ -
Ideal why to track active websocket connections?
I'm using Django 2+ and Channels 2+ with redis. I'm trying to reduce my ws connections on the client side and I wanted to be able track active connections but I'm finding it difficult to find an answer. Eventually this is something I want to track using netdata or something like it. Is there an integrated way or simple method to see how many websocket connections are open on a server? I will have http traffic going to the same port so I would like to be able to tell the difference between http and ws. Ideas? -
Running Neural Network model on Django web app
I'd like to include a NN classifier in a web app I am developing but I am relatively new to Django and not sure how to structure it in the best way. Basically I would like to load the model when the server starts and as necessary pass a string to the "predict" method of the classifier and return the result. Should I include the classifier class in the views and pass forward the "predict" method as context to the page the classifier will be used on? Really I am just looking for advice and guidance and this is my first web application -
Getting request.path in django template tags
I want to create a custom filter for django templates. I've got some currency pairs (which are links) that I pass to my html page so I need to check if current url is equal to a currency pair from my list, then I gotta skip it. For example, my url is: https://website.com/usd/eur/ So if there's a pair USD/EUR, it won't be shown on my page. To do this, I need to loop over all pairs and compare them to request.path value. So, how can I get it within my template tags ? -
Force reload on client's webpage Django
I am new to Django development and would like to know is it possible to trigger a webpage refresh on client side. My scenario: Webpage 1 is being surfed by clients. I updated some data to the database and wish to refresh the view.py to get new data from database and refresh clients webpage to display new informations. How can I achieve this? Thanks. Best Regards. -
DJANGO script error TypeError: url() takes from 2 to 4 positional arguments but 16 were given
Very new to Django and have hit another stumbling block . I am intergrating a separate third party auction app into my own project and before integrating into my own I get errors in the app. I seem to be getting url errors for each of the urls. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0340E810> Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked β¦ -
How to connect the mysql in django
i am trying but not connect , and installing in pip install mysqlclient getting error_mysql.c(29): fatal error C1083: Cannot open include file: 'my_config.h': No such file or directory -
django-user-accounts : no such table: account_passwordhistory
There are a lot of django-related posts with "no such table" error but none are coming from django-user-accounts module. I am getting this error sqlite3.OperationalError: no such table: account_passwordhistory , and here are the steps: Installed django-user-accounts: $ pip install django-user-accounts Collecting django-user-accounts Downloading https://files.pythonhosted.org/packages/0c/4f/40f76395324d98b7f8717aad7e08ad6f86ba2714eb956be6070e0402988c/django_user_accounts-2.0.3-py2.py3-none-any.whl (106kB) 100% |ββββββββββββββββββββββββββββββββ| 112kB 2.8MB/s . . . Installing collected packages: django-appconf, django-user-accounts Successfully installed django-appconf-1.0.2 django-user-accounts-2.0.3 in settings.py added INSTALLED_APPS = [ . . . 'django.contrib.sites', 'account' ] SITE_ID = 1 MIDDLEWARE = [ . . . 'account.middleware.ExpiredPasswordMiddleware', ] ACCOUNT_PASSWORD_USE_HISTORY = True ACCOUNT_PASSWORD_EXPIRY = 60 # number of seconds restarted server and ran : $ python manage.py user_password_history I got: Traceback (most recent call last): File "/Users/ipozdnya/miniconda3/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/Users/someuser/miniconda3/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: account_passwordhistory I realize that account_passwordhistory did not get created at the time of install or some other step, but nothing in this doc tells me what to do about it: http://blog.pinaxproject.com/2016/11/22/how-configure-password-expiration-for-your-site/ Thanks