Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in Django 2.2 with Debug=True on Ubuntu
I am trying to run a project in Django 2.2 with Debug=True on Ubuntu but I get this error in python manager.py runserver: TypeError: 'module' object is not iterable does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import error. This is /myparentapp/urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'', include('moeaforhdlweb.urls')), url(r'^admin/', admin.site.urls), url(r'^tinymce/', include('tinymce.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is /mychildapp/urls.py: from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^help/$', views.help, name='help') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I test this project on Windows 10 and it works perfectly, but not on Ubuntu. Besides, if I comment this line: url(r'', include('moeaforhdlweb.urls')) it works. Any help will be grateful, thanks a lot. -
Define blueprints grouping objects in Django
Django modelling question: I'm writing a manufacturing e-commerce site. We have an inventory of all components and we want to define blueprints for products that we could build using those components. How could I model that? Say for example I have a class AtomicComponent class AtomicComponent(models.Model): component = models.CharField(max_length=255) length = models.IntegerField(blank=True, null=True) thickness = models.IntegerField(blank=True, null=True) colour = component = models.CharField(max_length=255) quantity = models.IntegerField(blank=True, null=True) +----+------------+--------+-----------+--------+----------+ | id | Component | length | thickness | colour | quantity | +----+------------+--------+-----------+--------+----------+ | 45 | table-legs | 80 | 3 | white | 90 | | 46 | table-tops | 100 | 3 | white | 25 | | 47 | bolts | 1 | null | null | 3000 | +----+------------+--------+-----------+--------+----------+ How could I specify blueprints like: ikea-table: 4x(id=45) + 1x(id=46) + 4x(id=47) Trying to find a way so that the product could have a relationship with specific objects so that when a customer tries to order a table, it would check if all the components are available. -
Transfer all related models to different user in Django
In my django 1.8 app I can get all linked objects from other models of a user with user._meta.get_fields(). I now want to update/transfer all linked objects to point to an admin user. This is what I've tried: In [6]: from danube.people.models import Profile In [7]: admin = Profile.objects.get(id=1000) In [8]: user = Profile.objects.get(id=1002) In [9]: userData = user._meta.get_fields() In [10]: for item in userData: ...: extModel = item(related_model=admin) ...: # extModel = item(related_model_id=1000) ...: extModel.save() ...: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-aa9ee22a4e75> in <module>() 1 for item in userData: ----> 2 extModel = item(related_model=admin) 3 extModel.save() 4 TypeError: 'ManyToOneRel' object is not callable How can I overcome the TypeError: 'ManyToOneRel' object is not callable Error? -
authenticating client in multiple APIs
How to authenticate client when there is more than one API (obviously in all of them) and these APIs are using different authentication methods (token, session, ...) I need a general idea any help would be awesome. -
Authenticating user in websocket connections
I am trying to build a basic chat app with Django as backend. I am using WebSockets after the user logs in. However, I am not able to figure out a good way to authenticate the user. I was thinking about using Tokens but there doesn't seem to be a good way to send it from a javascript client to the server. Also, I also saw the implementation to authenticate on the first received message given here, however, it doesn't seem to be a great solution due to the following reasons: We have to accept the WebSocket connection with I'm pretty sure has some overhead. It doesn't seem to be much secure as for example if the client never sends the 1st message which is supposed to authenticate, the connection remains open for a long time and that behavior can be exploited to bring down the server by opening thousands of connections together. So is there any better way to implement authentication with WebSockets? For reference, I have tried the 2nd and 3rd method given here although couldn't figure out what to do at client end in the 2nd one. Also, it's not a full-stack app that I am building. … -
Django forms is not valid
my page html : resrver salle ! <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="reserver"> </form> views .py : def reserversalle(request , id): form= ReserverSalle(request.POST or None) print(form) if form.is_valid(): print("gooddd") context= { 'form' : form , } return render(request,'registration/reserversalle.html', context) forms.py : class ReserverSalle(forms.Form): nomsalle = forms.CharField(required=True , widget=forms.TextInput) motifresa = forms.CharField(required=True , widget=forms.TextInput) datedebut = forms.DateField( initial="2019-06-21", widget=forms.SelectDateWidget(years=YEARS)) heuredebut = forms.TimeField( initial='00:00:00') heurefin = forms.TimeField( initial='00:00:00') hello i try to submit my form but my form is not valid please i need some help -
Django Trigram search with rankings across multiple models
I'm trying to create an aggregated search result across multiple fields in multiple models and return a result ordered by rank. I can figure out each of these things on one model, but not merging the results from multiple models. One method I envision working is to take the weighted Trigram score for each record, append it to the record, and then sort by that score once the records from each search are combined in a list. How would I go about retrieving the weighted score for each record? Here's the code I'm working with: q = "search query" # ie "honey" A = 1.0 B = 0.4 C = 0.2 D = 0.1 total_weight = A + B + C + D trigram = A/total_weight * TrigramSimilarity('name', q) + \ B/total_weight * TrigramSimilarity('brand__name', q) + \ B/total_weight * TrigramSimilarity('description', q) + \ D/total_weight * TrigramSimilarity('category__name', q) results = Product.objects.annotate( similarity=trigram ).filter(similarity__gt=0.1).order_by('-similarity') This code works fine, in that it returns a ranked result within the model Product, and I can produce similar results in other models. So my main question is: How can I show ranked Trigram similarity results from multiple models, ordered by their rank regardless of what model … -
how to upload image at google cloud storage using app engine in django rest framework?
install pip install django-google-cloud-storage Configuration On your django settings.py file you need to add the following settings GOOGLE_CLOUD_STORAGE_BUCKET = '/your_bucket_name' # the name of the bucket you have created from the google cloud storage console GOOGLE_CLOUD_STORAGE_URL = 'http://storage.googleapis.com/bucket' #whatever the ulr for accessing your cloud storgage bucket GOOGLE_CLOUD_STORAGE_DEFAULT_CACHE_CONTROL = 'public, max-age: 7200' # default cache control headers for your files And finally declare the file storage backend you will use on your settings.py file DEFAULT_FILE_STORAGE = 'django_google_cloud_storage.GoogleCloudStorage' but not working -
Update only specific fields
//views def newEnroll(request): GradeYear = request.POST.get['customers'] payment = request.POST.get['paymentID'] pending = "Enrolled" update = StudentUser.objects.filter(PaymentTypes=payment,pending=pending,Grade_Year=GradeYear) update.Grade_Year = ([GradeYear]) update.PaymentTypes = ([payment]) update.Request = ([pending]) return render(request, 'accounts/pending.html') //model class StudentUser(models.Model): Grade_Year = models.CharField(max_length=500, null=True, blank=True) Subjects = models.CharField(max_length=500, null=True, blank=True) SectionID = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) CourseID = models.CharField(max_length=500, null=True, blank=True) PaymentTypes = models.CharField(max_length=500, null=True, blank=True) RoomID = models.ForeignKey(Room, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Request = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) I'm getting this error 'method' object is not subscriptable -
How to create an image from binary data returned by a request to store and use in Django app?
I am using the "Dropbox API Explorer - get_thumbnail" to get a thumbnail of images stored in Dropbox folders. The response returns a blob in binary. I am attempting to create a image file to store as an imagefield on my django app's database. I followed this to create the image https://2.python-requests.org//en/latest/user/quickstart/#binary-response-content. # get_thumbnail request url = "https://content.dropboxapi.com/2/files/get_thumbnail" # product_path is a variable storing path from list_folder new_product_path = "{\"path\":\"/%s\"}" %(product_path) headers = { "Authorization": "Bearer <api_token_ommitted>", "Dropbox-API-Arg": new_product_path } r = requests.post(url, headers=headers) thumbnail = Image.open(BytesIO(r.content)) # album is foreign key for Album model product = Product.objects.create(album=album, name=converted_name, image=converted_url, thumbnail=thumbnail) print('Product has been created!') print(r.content) b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n\x10\n\n\t\t\n\x14\x0e\x0f\x0c\x10\x17\x14\x18\x18\x17\x14\x16\x16\x1a\x1d%\x1f\x1a\x1b#\x1c\x16\x16 , #&\')*)\x19\x1f-0-(0%()(\xff\xdb\x00C\x01\x07\x07\x07\n\x08\n\x13\n\n\x13(\x1a\x16\x1a((((((((((((((((((((((((((((((((((((((((((((((((((\xff\xc0\x00\x11\x08\x00$\x00@\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xc4\x00\x1f\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x11\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02w\x00\x01\x02\x03\x11\x04\x05!1\x06\x12AQ\x07aq\x13"2\x81\x08\x14B\x91\xa1\xb1\xc1\t#3R\xf0\x15br\xd1\n\x16$4\xe1%\xf1\x17\x18\x19\x1a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xfa\x16\x8a\xc3_\x15h\xcd\x1c\x8c\xb7\xa8v\x9cm\xc1\x05\xbe\x80\xf5\xa7\xc3\xe2m\x1eB\xa0\xea6\xf1\x92\xa5\xb1+l \x0e\xb9\'\x8f\xd6\xbc\xa5R\r\xd93\xdcxj\xd1Wp\x7fs6h\xacx|K\xa2L3\x0e\xabg \xeb\xf2\xc9\x9a\xcd\xd6|w\xa3i\x9at\xd7m$\xb3\xac\\\x95\x8a2I\xa6\xe7\x14\xec\xd8G\rZ[A\xfd\xc7UEs\xd6\x9e0\xd1n,\x92\xe5\xaf\x16\x10\xc8\x1fd\xa0\x86\xc7\xb0\xefV-\xfcO\xa2\xcd\x07\x9a\xba\x9d\xa0PpCH\x14\x83\xee\x0f\xf3\xe9B\x9c_Pxj\xd1\xde\x0f\xeef\xcd\x15\x917\x894h@2j\x96x<\xe5d\r\xc7\xe1\x9ab\xf8\xa7B.\xe85{-\xeb\xc1\x1eg"\x9d\xd1>\xc2\xae\xfc\xaf\xeeg\xc2\xd3^\xddN\x00\x9a\xe2g\x00`\x06rq@\xbc\xb8\xe33\xc8p0>c\xd3\xd2\xa0\xa2\xbd\xbeT\xba\x18\xacMT\xef\xcc\xfe\xf3F\xcbX\xbb\xb4\x04C)Q\x90\xdcz\xd5\xa4\xf1>\xa6\xa1\xc7\xda\\\xab\x8c2\x93\xc1\xe75\x89EC\xa5\x07\xbaGB\xcc\xb1)[\x98\xd9\xb9\xf1\r\xf5\xc3\xc7#\xce\xfb\xd3\xa6\x0e1U\xe7\xd6/\'bd\x99\xc9 \x83\xcfPz\xd6u\x14\xd5(-\x90\xdeg\x89\x7fh\xb35\xed\xc4\xbc4\xcf\x8fL\xd4+,\x8ar\xae\xc0\xe7<\x1ae\x15VH\xe6\x9e&\xac\xdf4\xa4\xc2\x8a(\xa6b\x14QE\x00\x14QE\x00\x14QE\x00\x7f\xff\xd9' -
Lists are not currently supported in HTML input. When attempting to upload multiple photos through the django rest framework in one click
I am trying to use the django rest framework to carry out multiple POST events once I point it to a directory. The idea is that I will specify the country and a directory containing multiple images. Then the API must go to the directory, and post each image in that directory to the database along with more details available from the filename of each image. Following some pointers from the internet, I managed to build out a little model and framework that looks like it could work except for one thing. The default rest API page doesn't support the HTML input of lists. I would like to know if my time will be better spent trying to fit the API page to my requirements or if I should go about building my own HTML interface. Or to be more direct What is the fastest (and simplest) way for me to upload multiple images (each image is a separate instance in the db) into a database using Django and the Django REST Framework? models.py: from django.db import models # Create your models here. class Tiles(models.Model): image = models.ImageField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) country = models.CharField(blank=True, … -
Show user GitHub's repositories on a webpage
What the best way, what the simple way if I want to show all https://api.github.com/users/serhii73/repos user GitHub's repositories on a webpage? -
pre_save signal using tastypie api not allowing me to access "instance" field
I'm working on this small Django project in which I'm using pre_save signals to update a table in which I save the cumulative value of a certain quantity, whenever a new Transaction is created or modified, the corresponding value in the table is updated. If i add a transaction manually from the admin page everything works fine but today i tried to create a new Transaction through a POST request using tastypie generated api, the problem is that when my update_total_if_changed function is called by the signal, the instance parameter is /api/v1/transaction/ instead of the actual python object, therefore i get "Transaction has no FieldName." since the instance actually points to the tastypie entrypoint instead of the newly created object. Below you can see the code of my signal @receiver(pre_save, sender=Transaction) def update_total_if_changed(sender, instance, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: #new transaction tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste) tw.total += instance.quantity tw.save() else: if not obj.quantity == instance.quantity: # Field has changed tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste) tw.total = tw.total + instance.quantity - obj.quantity tw.save() -
Django rest framework upload multiple images
I have 2 model The Problem is , I am trying implement Multiple file uploaded and from front end I am sending like postimage: [object File] Problem is I am not getting the postimage in my serializer. Please help me Python with Django Rest Framework My Model class Post(models.Model): """ Model for the Post""" title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, editable=False)`enter code here` description = models.TextField(blank=True, null=True) photo = models.ImageField(blank=True, null=True, upload_to='media/') user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posted_user' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class PostImages(models.Model): """ Model for handling multiple images for Postings""" post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post' ) image = models.ImageField(blank=True, null=True, upload_to='media/post_images/') My View class PostPublishView(generics.ListCreateAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Post.objects.all() serializer_class = serializers.PostManageSerializer def get_queryset(self): """ return objects for the current auth user""" return self.queryset.filter(user=self.request.user).order_by('-title') def perform_create(self, serializer): """ Create newpost""" post = serializer.save(user=self.request.user) My Serializer : class PostImageSerializers(serializers.ModelSerializer): id = serializers.IntegerField(required=False) post = serializers.ImageField(required=False, use_url=True, max_length=None, allow_empty_file=True) class Meta: model = PostImages fields = ('id','post') class PostManageSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() postimage = PostImageSerializers(many=True) class Meta: model = Post fields = ( 'title', 'user', 'slug', 'postimage', 'description', 'photo', 'active') def create(self, validated_data): # task = Post.objects.create(**validated_data) images_data … -
How does django authentication work internally?
I was looking under the hood, on how the different authentication systems work in django. I have a basic idea that in case of session authentication, sessions are stored some where in the session models. It is easier to understand token authentication, as in token authentication, tokens are created which are in turn stored in the frontend. But, how is the login saved when the user goes for basic authentication or session authentication? When using basic authentication, assuming the User that is imported in from django.contrib.auth.models import User, we can use the decorator login_required, but how exactly does it work? -
perform_destroy: change the value before deleting instance
How to change value the save it in db in perform_destroy. I want to set cancel value to True when user is try to delete the instance def perform_destroy(self,instance): instance.cancel = True instance.save() i try this but nothings change in db. -
How to dynamically access to a given pandas dataframe column in django template?
I have some indicator objects and each indicator has an attribute content which contains a pandas dataframe. One can have access to such a content by using the accessor getContent of an indicator object. I do not know in advance the name of the columns of those pandas dataframes but I would like to have access to those columns in a Django template. Basically, one can iterate on a pandas dataframe by using the attribute '.columns'. But it seems it doesn't work. Please find below what I tried, I would add that my goal is to do some plotting using Plotly : <script> Some code with the container definition ... Plotly.plot( container, [ {% for column in indicator.getContent.columns %} { x: [{% for x in indicator.getContent.index.values|slice:":-1" %}"{{ x }}",{% endfor %}], y: [{% for y in indicator.getContent[column].values|slice:":-1" %}{{ y }}, {% endfor %}], name: '{{ column }}', mode: 'lines+markers', type: 'scatter' } {% endfor %} ], { xaxis: {title: {text: "Calendar months"}}, yaxis: {title: {text: "Indicator values"}}, } ); </script> The exception : django.template.exceptions.TemplateSyntaxError: Could not parse some characters: indicator.getContent|[column].values||slice:":-1" Hope it's clear, do not hesitate to let me know if you want more details. Thanks :) -
Passing HTML code as string variable to template for PDF generation
I'm working on a Django app which parses xlsx input, processes series of REST API queries and returns the result of the queries as a table in one of my django templates. The HTML code containing the results table is generated with Pandas.to_html() functionality. The HTML code is stored in a variable ("table") and passed to the html template, where it is displayed as {{ table | safe }}. This mechanism works just fine. However, I'm now struggling to add a button which would generate a pdf file to be downloaded by the user. NOTE: I'm aware it would probably make more sense to use JS to render the PDF on the client side, but at the moment the point is to avoid doing so. Upon some research, I decided to go with the django-easy-pdf library. I based my solution on the example included in the documentation, but so far to no avail. In urls.py: urlpatterns = [ [...] path('result.pdf', views.PDFView.as_view(), name='PDFview'), ] In views.py: class PDFView(PDFTemplateView): template_name = 'whitelist/listresult.html' table = None def get_context_data(self, **kwargs): return super(PDFView, self).get_context_data(pagesize='A4', title='Hi there!', table=self.table, date=date.today) Please note that the template "listresult.html" is the one expecting the {{ table }} variable. Last but … -
How to add combined querysets into one template table
I have 3 models that are CarDetailsAdd, ShippingDetails, MaintenanceDetails. ShippingDetails and MaintenanceDetails models are connected to CarDetailsAdd foreign-key and each of them have a price field. here is the problem how do I solve this and put data in one row #View def get(self, request, *args, **kwargs): profit = CarDetailsAdd.objects.filter(status='sold') total_profit = profit.aggregate(Sum('profit_amount'))['profit_amount__sum'] shipping = ShippingDetails.objects.filter(car__status='sold').values( 'car').annotate( total_shipping_price=Sum('price')) maintenance = MaintenanceDetails.objects.filter(car__status='sold').values( 'car').annotate( total_maintenance_price=Sum('price')) query = chain(shipping, total_profit, maintenance) context = { 'profit_data': query, 'total_amount_profit': total_profit, } return render(request, 'pdf/profit.html', context) #template <tbody> {% for profit_data in profit_data %} <tr style="text-align: center"> <td>{{ profit_data.name }}</td> <td>{{ profit_data.purchased_amount }}</td> <td>{{ profit_data.total_shipping_price }}</td> <td>{{ profit_data.total_maintenance_price }}</td> <td>{{ profit_data.sold_details.sold_amount }}</td> <td>{{ profit_data.profit_amount }}</td> </tr> {% endfor %} </table> -
How to apply ajax on Django class based views
I'm working on a social app i have created a class based view 'CreatePost' without ajax but now i need ajax to fill the form and without refreshing show the post. I have tried with function based views but i need it on class based views Views ============== class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) Urls ============== urlpatterns = [ path('', views.PostList.as_view(), name="all"), path('new/', views.CreatePost.as_view(), name="create"), path('by/<username>/', views.UserPosts.as_view(), name="for_user"), path('by/<username>/<pk>/', views.PostDetail.as_view(), name="single"), path('delete/<pk>/', views.DeletePost.as_view(), name="delete"), ] Form ============== class PostForm(forms.ModelForm): class Meta: fields = ("message", "group") model = models.Post def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) if user is not None: self.fields["group"].queryset = ( models.Group.objects.filter( pk__in=user.groups.values_list("group__pk") ) ) Template ============== {% extends "posts/post_base.html" %} {% load bootstrap4 %} {% block post_content %} <h1>Create New Post</h1> <div class="container mt-3"> <form method="POST" action="{% url 'posts:create' %}" id="postForm"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Post" class="btn btn-primary btn-large"> </form> </div> {% endblock %} -
How do i use materialize autocomplete with google books api
I have a search function to pull up books through google books api, I am trying to add autocomplete through some materialize code. I tried putting the books API in the data section but I'm inexperienced with java script. html <div class="row"> <div class="col s12"> <div class="row"> <div class="input-field col s6 offset-s3"> <input type="text" id="search" class="autocomplete"> <label for="search">Enter you favorite book</label> <button id="button" type="button">Search</button> </div> </div> </div> </div> <!-- The Output for the search function--> <div class="row"> <div class="col s12"> <div class="row"> <div class="input-field col s9 offset-s2"> <div id="results"></div> </div> </div> </div> </div> Java Script document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.autocomplete'); var instances = M.Autocomplete.init(elems, {}); }); $(document).ready(function(){ $('input.autocomplete').autocomplete({ data: { "www.googleapis.com/books/v1/volumes?q=": null, "Gallop": null, "Great": null, "Google": 'https://placehold.it/250x250', "Greaters": null, "Goolig": null, "Gorlog": null, "Garti": null, }, limit:(5), }); }); When I put the books API in the data it didn't change anything. -
Django cron is not running using crontab
I have made a file named updatefield.py content is from FrontEnd.views import UpdateField def my_scheduler(): # add logic UpdateField() I have put it inside my project root with manage.py file And my settings.py file is like CRONJOBS = [ ('* * * * *', 'Ravi.updatefield.my_scheduler') ] Installed apps 'django_cron', 'django_crontab', After executing command python manage.py crontab add I got adding cronjob: (33083f0c14f7cccdc5851431976adcbb) -> ('* * * * *', 'Ravi.updatefield.my_scheduler') But its not running Right now . And noting is appearing on my terminal my function is this def UpdateField(request): print('hi') return HttpResponse('hello world') -
Nginx configuration file is not working due to server_names_hash_bucket_size
I am trying to make nginx, gunicorn and supervisord work on Ubuntu and django project for AWS EC2. Currently using this tutorial: https://www.youtube.com/watch?v=u0oEIqQV_-E Nginx in terminal is not working and I receive the message below: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64 nginx: configuration file /etc/nginx/nginx.conf test failed My question is: Is the right way to insert and solve the problem below? Am I using the server_names_hash_bucket_size: 64 used at the right line? if not please help me identify what line to use it. server { listen 80; server_name XXX; ***** server_names_hash_bucket_size: 64; **** I TRIED HERE location / { include proxy_params: proxy_pass http://unix:/home/ubuntu/PROJECT_NAME/app,sock; } } -
Conditioning the records to be related in a recursive relation
I have a model as the below that have a recursive relation with it self: class Unit(models.Model): unit_name = models.CharField(max_length=200, blank=False, unique=True) is_main_unit = models.BooleanField(blank=False, default=False) main_unit = models.ForeignKey('self', on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.unit_name This one is working as I want except by that I need that ONLY objects (records in the table) that are "main" (is_main_unit=True) have related others units. In other words -and functionality talking- in the admin screen- when I am adding an non main unit, I need that only main units will displayed in the list box to be selected and related to the no main unit that is doing created. I am trying to use the 'related_name' and 'related_query_name' attributes but I can't found the way to reach the expected behavior. I tried and play with the bellow code, but I don't know how to define the condition "is_main_unit=True" in the relation definition: class Unit(models.Model): ... main_unit = models.ForeignKey('self', on_delete=models.CASCADE,blank=True,null=True,related_name='unidades_asociadas',related_query_name='unidades_principales') ... Regards and thanks in advance ... Homero Matus. -
Trying to drop table using cursor in django
I am trying to drop a table using the cursor but, it always says syntax error although I used it before and worked but not to drop table def check_TempTableNames(tableName): print(tableName) with connections['DataAdmin'].cursor() as cursor: print("Check Done") cursor.execute("DROP TABLE %s",[tableName]) def preStepBtn2(request): #empty=Rfde2003Syd0827.objects.using('DataAdmin').all() sourcePE = request.GET.get('sourcePE') targetPE =request.GET.get('targetPE') dropdownConnType =request.GET.get('dropdownConnType') sourceInterFace =request.GET.get('sourceInterFace') targetInterFace =request.GET.get('targetInterFace') temp_looback = "sop_ce_loopback_interface_" + sourcePE + "_" + targetPE TEMP_ROUTER_STATUS = "sop_ce_router_status_" + sourcePE + "_" + targetPE Temp_virtual_int = "sop_ce_virtual_interface_" + sourcePE + "_" + targetPE print(temp_looback) check_TempTableNames(temp_looback) check_TempTableNames(TEMP_ROUTER_STATUS) check_TempTableNames(Temp_virtual_int) My databases: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Fileade', 'HOST': '10.238.76.53', 'USER': 'SDS_dataflow', 'PASSWORD': 'SDS_dataflow', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } , 'DataAdmin': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Data_Admin', 'HOST': '10.238.76.53', 'USER': 'SDS_dataflow', 'PASSWORD': 'SDS_dataflow', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } } Traceback (most recent call last): File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\College\Orange Training\MassiveMigrationPortalTool\posts\views.py", line 170, in preStepBtn2 check_TempTableNames(temp_looback) File "D:\College\Orange Training\MassiveMigrationPortalTool\posts\views.py", line 147, in check_TempTableNames cursor.execute("DROP TABLE %s;",[tableName]) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) …