Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail - made custom slug but page not serving from it
I made a custom slug because the default slug does not meet my needs and already set the url_path with the new slug. But the page is still serving with the default slug. I've already set the url_path with the following code: def set_url_path(self, parent): super().set_url_path(self) if parent: self.url_path = parent.url_path + self.custom_slug + '/' return self.url_path But when I publish the page, it still returns the page with the default slug value. I thought Wagtail serves the page on url_path. What other methods or variables do I have to override for the page to be served on my custom slug? -
How to get webpack file in output folder?
I've made a webpack file(as MainPage.js) in output folder which I set up on webpack.config.js However, when I access to my main page it says there is no MainPage.js. What's wrong with it?? (I'm using Django on backend and React on frontend) Hierarchy of my folder Cebula4 - back - settings.py - manage.py - front - webpack-stats.json - webpack.config.js - static - bundles - MainPage.js (I checked that it was existed) Settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') ... WEBPACK_LOADER = { 'DEFAULT' : { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'front/webpack-stats.json'), } } ... -
Adding placeholder to form in Django when using django-filter
I am developing a web application which displays an html table using django-tables2 and which allows filtering this table using django-filter. In my html template I can simply put {% filter.form %} and I am getting a full form for filtering my table which I think is really great and easy. However, I would like to add placeholders to this form which would be in plane html (using Bootstrap4) something like this: <div class="container"> <form> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" placeholder="ENTER PLACEHOLDER HERE" name="email"> </div> </form> </div> (example taken form here:https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_form_basic&stacked=h and edited) How can I add a placeholder when working with django-filters and all I am doing is adding % filter.form %} to my template? -
Celery and .env file with django-decouple
I am starting my celery in a separate terminal with command -A app worker -E --concurrency=5 -l debug -P eventlet but it can't find .env file. I have this this question which appears similar to mine but still gives me errors. The error I am getting is decouple.UndefinedValueError() -
Django: How to save mxGraph, so when user refreshes the graph stays? (asynchronous)
I convert the current mxGraph the user creates into XML which is stored in the database (ajax.js). I return this in my views as a JSONResponse to my ajax request (views.py). The data stored in the database saves, as I have checked in the Django administration page and the xml gets updated per save button. This is all working fine, however the issue is that when I refresh the page the graph created does not stay on the page. ajax.js var button = mxUtils.button('Save', function() { //var url = "{%url'login'%}" //var url = "{% url 'myapp:productdetail' %}"; //location.href = '/saveData/' var encoder = new mxCodec(); var node = encoder.encode(graph.getModel()); var xml = mxUtils.getPrettyXml(node); var csrftoken = getCookie('csrftoken'); $.ajax({ type: "POST", url: "/saveData/", data: { "xml": xml}, headers:{ "X-CSRFToken": csrftoken }, success: function(data){ //console.log("data" + data[0]) //console.log(graph) //var xmlDoc = data[0] var xmlDoc = mxUtils.parseXml(data[0]); //var xmlDoc = mxUtils.load("/saveData/").getXml(); //console.log("xmlDoc " + xmlDoc) var node = xmlDoc.documentElement; //console.log("node " + node) var dec = new mxCodec(node.ownerDocument); //console.log("dec " + dec) //console.log("graph model " + graph.getModel()) dec.decode(node, graph.getModel()); } }); views.py def saveData(request, user): if request.method == "POST": #Get user profile member = Member.objects.get(username=user) #Get XML data once user presses save #xmlData … -
How to convert image(ndarray object) to image object so that it can be JSON serialized?
I am new to python and programming world. I have a code which converts image into numpy array. I want to learn how to reverse it i.e. convert the numpy array into image. I have an rest api code, which takes an image from post method, convert it to numpy array, do some processing and return some results. However, I am trying to modify the code, so that, I can take two image as input from post method, convert it to numpy array, combine those images as one and send that final image as json response. I have successfully modified the code, so that, it accepts two images as input. I will add later the Code for combining two image into one. Currently, I am trying to send image as json response. For that, I am just trying to send the image I got from post method, as it is. But I am receiving an error of "Object of type 'ndarray' is not JSON serializable". So, I thought, I should convert the ndarray object(Previously created) must be convert back into image so that it can be json serialized. How to do that? # import the necessary packages from django.views.decorators.csrf import … -
Displaying a total count of instances of a model in Django?
I would like to display the total number of a model instance (boxes) on my dashboard page but for some reason its not displaying! Could someone help me making the query string for this? e.g. If there are a total of 100 boxes, I would like to display "100" My HTML: {{ box_data.count }} My Views: def dashboard(request): box_data = Box.objects.all() My Model: class Box(models.Model): box_store_date = models.DateTimeField(blank=True, null=True) box_review_date = models.DateTimeField(blank=True, null=True) box_contents = models.CharField(max_length=300, blank=True, null=True) box_on_loan = models.BooleanField(default=False) box_return_date = models.DateTimeField(blank=True, null=True) project_assigned_to = models.ForeignKey('Project', null=True) Location = models.OneToOneField('Location', null=True) -
Is it possible to predict just one row from my data set?
I have a dataset that looks like the table below. I would like, on clicking on the link button to predict according to the Label field. So, my question is, as I want to just predict one row of my dataset, How can I split my data into training and testing set according to this code from sci-kit-learn? X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size) Below is my view to give you an idea of what I would like to do. def prediction_view(request): template='index.html' . . . train=Pull_Requests.objects.all() features_col = ['Comments', 'LC_added', 'LC_deleted', 'Commits', 'Changed_files', 'Evaluation_time','First_status','Reputation'] # This also test class_label=['Label'] X = train[features_col].dropna() # This also test # y = train.Label # This also test y=train[class_label] random_state = 0 test_size=request.POST.get('test_size') X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size) clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train, y_train) y_pred = clf.predict(X_test) classification_report={'accuracy':Accuracy, 'pricision':Precision, 'recall':Recall, 'f1_score':F1_meseaure} importance_features={'importances_feautre':importances_feautres} data={ 'new_data':new_data, 'classification_report':classification_report, 'importance_feature':importance_features, 'features':features_col, } return render(request,template,data) Dataset sample -
Jquery tablesorter plugin does not work in Django template
Trying to use the table sorting JQuery plugin in the Django template. Tried different sources for jquery and tablesorter files. Didn't seem to work with any of them. Just nothing changes on the template page. The real table that I'm trying to sort is tab2. Created a simple tab1 just for testing. Didn't work with this table also. Tried to follow these instructions https://mottie.github.io/tablesorter/docs/. Downloaded .js files from this page. Didn't have any experience with JS and JQuery before. {% extends 'base.html' %} {% load static %} {% block content %} <h4>Players</h4> <head> <script type="text/javascript" src="{% static 'players/jquery-latest.min.js' %}"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/css/dragtable.mod.min.css"></script> <script type="text/javascript"> $(function() { $("#myTable").tablesorter(); }); </script> </head> <body> <table id="tab1" class="table table-hover table-bordered tablesorter"> <thead> <tr> <th>Month</th> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td>$80</td> </tr> </tbody> <tr> <td>Sum</td> <td>$180</td> </tr> </table> <div class="container"> <table id="tab2" class="table table-hover table-bordered tablesorter"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Height</th> <th>Weight</th> <th>Birth Date</th> <th>Draft Pick No</th> <th>Games</th> <th>Goals</th> <th>Assists</th> <th>Shots</th> <th>Hits</th> <th>Faceoffs Won</th> <th>Blocks</th> </tr> </thead> {% for player in players %} <tbody> <tr> <td><a href="{% url 'player-detail' player.playerName|slugify player.playerId %}">{{ player.playerName }}</td> <td>{{ player.playerPositionCode }}</td> <td>{{ player.playerHeight }}</td> <td>{{ player.playerWeight }}</td> <td>{{ player.playerBirthDate }}</td> <td>{{ player.playerDraftOverallPickNo }}</td> <td>{{ … -
How to include foreign key field when serialising search query result from django haystack
After googling a lot, I cant seem to find a solution to this: I have created a new endpoint for searching items from my Product Index Using Django oscar with django oscar api, here are the models: class Product(AbstractProduct): title = models.TextField(blank = True) class ProductImage(AbstractProductImage): product = models.ForeignKey('catalogue.Product', on_delete=models.CASCADE) display_order = models.PositiveIntegerField() remote_image = models.URLField(blank=True) The views.py class ItemSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = ItemSearchSerializer def get_queryset(self): request = self.request queryset = EmptySearchQuerySet() if request.GET.get('q', ''): query = request.GET.get('q', '') queryset = SearchQuerySet().filter(content=query) return queryset Serializers.py from oscarapi.serializers import product class ItemSearchSerializer(serializers.ModelSerializer): text = serializers.CharField() title = serializers.CharField() price = serializers.HyperlinkedIdentityField(view_name='product-price') image = product.ProductImageSerializer(many=True, required=False) class Meta(): model = Product fields = ('image', 'price', 'text', 'title') When I hit the endpoint with localhost:8000/api/search/?q=bmw, it seems works for all other fields but does not return images, here is sample: [ { "image": null, "price": "http://localhost:8000/api/products/2339/price/", "text": "2339\nBMW 316 SE Automatic", "title": "BMW 316 SE Automatic" }, { "image": null, "price": "http://localhost:8000/api/products/0029/price/", "text": "0029\nBmw 330d\nLoverly car in excellent condition", "title": "Bmw 330d" }] Another thing, as there maybe several images for a given product, I would also like to just return the first image, which will have a display_order value of 1 Thanks … -
I want to add two extremely large numbers in python which even bignum can't handle
I am new in python,I want to add two extremely large numbers in python which even bignum can't handle. I can take these two numbers as a string and then can calculate from the end and as like we used to do in old school addition process. we can take the carriage and add it to the next numbers and so on. Please assist. -
Reduce large number to intword in Django without editing template
I am developing a web application that displays an html table using django, django-tables2 and Bootstrap4. I have a column AUM which contains very large numbers (up to billions). In my models.py the corresponding model uses a models.Interfield() for AUM. class MyModel(models.Model): ... AUM = models.IntegerField(null= True, blank= True) ... Using django-tables2 and Bootstrap4 this model gets transformed into a table and rendered into a template using {% render_table table %} The numbers displayed in the corresponding column a displayed in there raw format which looks like e.g. this 1000000000. I want to make it more human readable. I have found two solutions for seperating thousands Using intcomma from django.contrib.humanize which is not a viable solution for me as it requires me to add a filter in the template which I cannot do as I am just adding {% render_table table %}(https://docs.djangoproject.com/en/2.1/ref/contrib/humanize/) Using the global setting USE_THOUSAND_SEPARATOR = Truein my settings.pywhich is a solution that works great for me (https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#use-thousand-separator) I have also seen that there is something similar to intcomma which is intword and it transforms e.g. 1000000 into 1 Million which is in my opinion even more human readable. As with the intcomma this is not a viable … -
Pytest-django: cannot delete db after tests
I have a Django application, and I'm trying to test it using pytest and pytest-django. However, quite often, when the tests finish running, I get the error that the database failed to be deleted: DETAIL: There is 1 other session using the database. Basically, the minimum test code that I could narrow it down to is: @pytest.fixture def make_bundle(): a = MyUser.objects.create(key_id=uuid.uuid4()) return a class TestThings: def test_it(self, make_bundle): all_users = list(MyUser.objects.all()) assert_that(all_users, has_length(1)) Every now and again the tests will fail with the above error. Is there something I am doing wrong? Or how can I fix this? The database that I am using is PostgreSQL 9.6. -
How to save form data to my model in django
I am creating a newsletter application that requires the user's name and email. However each time I input form data . no change is reflected in the database here is my models.py class NewUsers(models.Model): name = models.CharField(max_length=50) email = models.EmailField() date_added = models.DateField(auto_now_add= True) class Meta: verbose_name = "NewUser" verbose_name_plural = "NewUsers" def __str__(seld): return self.email and here is my views.py def newsletter_subscribe(request): if request.method == 'POST' : form = NewUserForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] #variable to store cleaned data email = form.cleaned_data['email'] instance = NewUsers(name= name, email = email) instance.save() if NewUsers.objects.filter(email = instance.email).exists(): print("Your email is already added to our database") else: instance.save() print("Thank you for subscribing") else: form = NewUserForm()#display empty form context = {'form':form} template = "index.html" return render(request ,template ,context ) -
What data structure to use for ranking system which divides itself in groups?
I have a quiz app where students can take tests. There is ranking based on every test. It's implemented with simple lists (Every new score is inserted into the list and then sorted (index+1 is the rank)). But I want to add another abstraction. ie. Suppose 1000 students took the test and my ranking was 890. But those 1000 students should automatically be divided into 10 groups ie. group 1 of ranking 1 to 99, group2 of ranking 100 to 199 and so on. So if my overall ranking is 890. I should be subscribed to group 9 with 90th rank in that group. How should this be implemented? -
django model's field choices of another model's field
I have a graph data with which I display a single point in the graph. monthly_yield is the Y coordinate and date is the X coordinate. all the X's and Y's in one graph have the same graph_id, different graph_id means another graph with its own X's and Y's. I have built a form in which the user can select multiple graphs to display them one with the other, so the user basically has the option to select multiple graph_ids. GRAPHS_CHOICES = (GraphData.objects.all().values_list("graph_id", flat=True).distinct()) DATA_YEARS = ('2017', '2018') DATA_MONTHS = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12') class GraphForm(forms.Form): graphs = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=GRAPHS_CHOICES) from_year = forms.DateField(widget=forms.SelectDateWidget(years=DATA_YEARS)) from_month = forms.DateField(widget=forms.SelectDateWidget(months=DATA_MONTHS)) to_year = forms.DateField(widget=forms.SelectDateWidget(years=DATA_YEARS)) to_month = forms.DateField(widget=forms.SelectDateWidget(months=DATA_MONTHS)) class GraphData(models.Model): graph_id = models.CharField(max_length=128) date = models.DateField(max_length=128) monthly_yield = models.CharField(max_length=128) The problem is that I'm not sure how to implement it accordingly, and I guess this is not the data "choices=" expects in the graphs field, and also "months=" or "years=" in the other fields -
How to send Email using smtplib in django app deployed on Aws lambda?
I want to send email using python package smtplib from Django application which is running on AWS. I had deployed the Django application using zappa. I had written the smtplib sendmail() function to send mail. When I tried executing the project in my local. It is sending mail. But when I had deployed onto AWS. It is throwing "End Point Request Timeout". Please help me in solving my issue. -
Django Rest Framework: serialize list of ids
Is there a way to serialize request's payload like {'ids': [1,2,3]} as a ListField of primary keys (i.e. check by serializer whether Task objects with such ids exist)? Or what approach should I use to write an API view for another microservice to confirm that tasks were enqueued? serializer = ConfirmationSerializer( data=request.data, many=True ) queryset = Task.objects.filter( ids_in=serializer.data.ids, status=Task.STATUS_CREATED, ) queryset.update( status=Task.STATUS_SENT, confirmed_at=dt.datetime.now() ) return Response({'status': 'ok'}) -
Accessing previous steps in Wizard Form, Django
I cannot get to jump to previous steps of WizardForm in django in any different way than the one showed in documentation From the documentation we have that we can jump to previous steps through: {% if wizard.steps.prev %} <button class="btn btn-outline-info" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">Previous Step</button> {% endif %} However if I use the same button above the form, or try to emulate anything similar with HTML tag a and href, nothing seem to work. I need something like that because I have implemented a breadcrumb above and I need every previous step completed, to be a link to that form Thanks! -
Displaying an image in a Django template
I have these three models -- A "Thing" has an associated "Album", which contains typically three or four "Photo"s of the "Thing". For the latest nine "Thing"s, I want to display the first photo of the thing from the "Album", along with other details of the thing (e.g., name, country of manufacture) using a template called "headquarters.html". The following are my models: class Thing(models.Model): name = models.CharField(verbose_name = "Item", max_length = 60) price = models.DecimalField(max_digits = 5, decimal_places = 2) country_of_manufacture = models.CharField(verbose_name = "Country of Manufacture", max_length = 40) created_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False) album = models.OneToOneField(Album, on_delete = models.CASCADE, null = True) def __str__(self): return self.name class Album(models.Model): name = models.CharField(verbose_name = "Photo Album", max_length = 60) created_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False) def __str__(self): return self.name class Photo(models.Model): photo_identity = models.ImageField(blank = True, null = True, upload_to="media/%Y/%m/%d/") photo_in = models.ForeignKey(Album, on_delete = models.PROTECT) uploaded_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False) def __str__(self): return '%s -- (%s)' % (self.photo_in.name + " Album", self.photo_identity) This is my view.py: def headquarters(request, *args, **kwargs): last_nine = Thing.objects.all().order_by('-id')[:9] mylist = [] for thing in … -
UnicodeDecodeError while trying to run a server for a Django 2.1 Project
I'm new using Django and I'm just running my first project here. I'm working with the pipenv virtual environment and what I've done is: I created a new directory, I installed Django 2.1 there, opened the pipenv shell and executed the following line: $ django-admin startproject test_project . Next thing I did is try to run the server, with the following command, but it throws an exception. $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. December 25, 2018 - 12:43:58 Django version 2.1, using settings 'test_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001C80D5FB378> Traceback (most recent call last): File "C:\Users\Pol\.virtualenvs\Django-93jgfkzB\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Pol\.virtualenvs\Django-93jgfkzB\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Pol\.virtualenvs\Django-93jgfkzB\lib\site-packages\django\core\servers\basehttp.py", line 163, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Pol\.virtualenvs\Django-93jgfkzB\lib\site-packages\django\core\servers\basehttp.py", line 66, in __init__ super().__init__(*args, **kwargs) File "c:\users\pol\appdata\local\programs\python\python37\Lib\socketserver.py", line 449, in __init__ self.server_bind() File "c:\users\pol\appdata\local\programs\python\python37\Lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "c:\users\pol\appdata\local\programs\python\python37\Lib\http\server.py", line 139, … -
Is there any other way except forms to post and redirect simultaneously in django?
It can be done with Django forms. But I'm just asking if there are other ways. Something like: data = {'name':'John Doe', 'age':30} post_data_to_url('www.example.com',post_data = data) and then it redirects to www.example.com with POSTed data. -
How to weave ( join alternating elements ) several Django QuerySets
How can several QuerySets be weaved in just one? I mean joining them in another QuerySet alternating their elements, without evaluating each individual QuerySet so performance is kept. For example: #QuerySets to be weaved q1 = Model.objects.filter(...) q2 = Model.objects.filter(...) q3 = Model.objects.filter(...) #The QuerySet in which the previous ones are weaved WeaveQuery = ???? So the first element from WeaveQuery belongs to q1, the second to q2, the third to q3, the fourth to q1... and so on. The weaved QuerySets may not have the same length, so the elements shouldn't be repeated in the WeaveQuery if one of the weaved querysets run out of elements. -
How to load a form to django base template using inclusion tag avoiding RecursionError?
I have already tried to use inclusion tag in many ways like seperating the html file and including it in base template(layout.html) or even directly on the base template(layout.html), I keep getting RecursionError at / maximum recursion depth exceeded In app/forms.py class UserSettingsForm(forms.ModelForm): class Meta: model = UserSettings fields = ['theme_color','text_color'] widgets = { 'theme_color':forms.Select(attrs={'class':'form-control'}), 'text_color':forms.Select(attrs={'class':'form-control'}) } error_messages = { NON_FIELD_ERRORS : { 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", } } In app/templatetags/theme.py @register.inclusion_tag('layout.html') def settings_form(): set_form = UserSettingsForm() return {'set_form':set_form} In layout.html {% load theme %} ... <form action="{% url 'set_settings' %}" method="post"> {% csrf_token %}} {% settings_form %} {{set_form}} </form> I want the form to be displayed on all of the pages that this layout.html is extended to so sending it from a view is out of the question. I keep hearing about RequestContext but I don't know how to render it using that. If you know please describe where should I create this new file for this function to be implemented and how should I do it. -
Represent this Image django Model
I am trying to build a multichoice question app with Department -> subject -> questions relations but I am confused on how to get questions in relation to the given subjects just like the image i have posted.