Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
input json in elasticsearch and django
the situation : I'm making a website in django, and I want to make research on json file, for this I need to use elasticSearch but here is my problem : -I have a lot of json generated by a software with various fields so I'm looking for how to input all json in elastic search and then making research on some fields, i've seen many tutorial but they use it like an ORM (for example here https://medium.freecodecamp.org/elasticsearch-with-django-the-easy-way-909375bc16cb) so have you any tutorial or idea of how to send a json to elastic search without making any change ? With kind regards, Brice -
Use permissions without a model
I have a django setup with no models, but I want to use the authentication / permission system to limit access to certain views. For that, I have created an empty model: from django.db import models # Create your models here. class Report(models.Model): class Meta: permissions = ( ('view', "May view the reports") ) and added that permission to my view: @login_required @permission_required('reports.view') def index(request): ... When logged in a staff user, it works, when logged in as a normal user, I get the login screen. But, in my admin panel, I do not see the permission, so I cannot give the normal user permission to view the reports. I tried to run makemigrations, but it says no changes detected. How can I use an empty model just for permissions? -
Django: Signal for "post initial migration"
For setting up new development systems I would like to have a "post initial migration" signal. It seems that something like this does not exist yet. Is there a way to work around it? -
How to get the count of most viewed product?
Hi actually i new to django Restframe work. Here i have mentioned my model My question is that ? I don't know how to store the count of each product. and most viewed product should display in frontend. MODEL.PY class Products(models.Model): name = models.CharField(max_length=100) image = models.CharField(max_length=10, null=True) categories = models.ArrayModelField( model_container=Category, model_form_class=CategoryForm ) specifications = models.ArrayModelField( model_container=Specifications, model_form_class=SpecificationsForm ) description = models.CharField(max_length=500) reviews = models.ArrayModelField( model_container=Reviews, model_form_class=ReviewsForm ) drizzly = models.BooleanField(default=False) complete = models.BooleanField(default=False) comment = models.CharField(max_length=500) count = models.IntegerField() -
Generate short temporary link to a form
So, I have a form that logged in user can fill, and when that form is submitted, I'd like it to generate a temporary link to another form that non-logged in users could access and fill, that would last 24 hours. That form would then send data to the database. I would like that URL to be as short as possible and easy to write down manually on a browser, but I don't know the best way to do so, or even how to do so. Please keep in mind that I am fairly new to Django. -
django serializer is_valid() return false
using django 2.0.2 Python 3.4 MySerializers.py class MySerializer(BaseSerializer): UserUID = serializers.CharField() DeviceUID = serializers.CharField() SessionId = serializers.CharField() MyView.py class MyVeiw(BaseViewSet): serializer_class = MySerializer def create(self, request, *args, **kwargs): serializer_class = MySerializer(data=request.data.dict()) if serializer_class.is_valid(): print(serializer_class.errors) return Response(0) else: return Response(1) input data {'SessionId': '222a282f-c3f8-46d2-8476-8d4ec627a477', 'UserUID': '62', 'DeviceUI D': '25'} serializer_class return MySerializer(data={'SessionId': '7c5d0530-8e54-42aa-91a0-ce8776c82490', 'Us erUID': '64', 'DeviceUID': '27'}): UserUID = CharField() DeviceUID = CharField() SessionId = CharField() serializer_class.initial_data return {'UserUID': '65', 'DeviceUID': '28', 'SessionId': 'aecef14f-7f9d-4f01-bc1d-89514 8ab0c05'} serializer_class.errors return {} but is_valid() is always false why errors return empty list i tried SessionId change UUIDField() but not work and UserUID , DeviceUID Change IntegerField() but not work i think this serializer is valid why return false -
Django CMS migrate from SQLite to PostgreSQL
I'm developing a project with Django CMS 3.5. I used SQLite for development and have data in there. Now I'm trying to migrate to PostgreSQL. My steps so far: python manage.py dumpdata --natural-primary --natural-foreign > dump.json Switching to production settings python manage.py migrate TRUNCATE django_content_type CASCADE; python manage.py loaddata dump.json But I encounter the next error: Traceback (most recent call last): File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__ rel_obj = getattr(instance, self.cache_name) AttributeError: 'Page' object has no attribute '_node_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/db/models/base.py", line 833, in save_base update_fields=update_fields, File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 193, in <listcomp> for receiver in self._live_receivers(sender) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/cms/signals/page.py", line 8, in pre_save_page instance.clear_cache(menu=True) File "/home/webmaster/tc56/env/lib/python3.6/site-packages/cms/models/pagemodel.py", line 963, … -
delete record from another model on action select in Django admin
I'm using Django 2.0 I have created few actions to use in admin interface def clear_arbitrase(modeladmin, request, queryset): queryset.update(arbitrase_generated=False) @admin.register(WallmartRecord) class WallmartRecordAdmin(admin.ModelAdmin): actions = [ clear_arbitrase ] This updates, the arbitrase_generated flag to False for WallmartRecord model. I have another table to save record of arbitrase in ArbitraseRecord I want to delete record from ArbitraseRecord as well when flagging arbitrase_generated to False. I tried implementing post_save signal in models.py @receiver(post_save, sender=WallmartRecord) def post_save_wallmart_record_receiver(sender, instance, *args, **kwargs): if not instance.arbitrase_generated: # delete records from ArbitraseRecord arbitrase_record = ArbitraseRecord.objects.filter(wallmart_record=instance) if arbitrase_record is not None: for record in arbitrase_record: record.delete() But this seems be to not calling receiver. How can I delete record from another model on admin action select? -
ValueError .. The 'image' attribute has no file associated with it
I'm using Django 1.11.11 / Python 2.7.5 I have a Photo model in form to upload multiple images. There is an error with this model : https://ibb.co/m3XLDn Photo model : class Photo(models.Model): produit = models.CharField(_("Produit (code utile pour le tri des choix):"), max_length=2000, blank=True, null=False) legende = models.CharField(_("Légende:"), max_length=200, blank=True, null=False) image = models.ImageField(upload_to='fiche_image', blank=True, null=False) def __str__(self): return self.produit or "undefined" # return str(self.produit) class Meta: ordering = ['produit', 'legende', 'image'] I'm not sure what causing the problem. -
Django: Object Filtering from ManyToManyField
I have a Question & Answer model, where anyone can answer a question & also follow a question. # question model class Question(models.Model): text = models.TextField() followers = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) # answer model class Answer(models.Model): text_answer = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) How can I filter through Answer if request.user is followers list? I tried Answer.objects.filter(question.followers=request.user) but it didn't work. -
Django-Dose Heroku allow for using requests module?
I deploy a Django app. And I need to use the requests module. It works on local server. param ={'things'} // Don't care about this. try: dic_request = requests.get(url="https://www.google.com/", params=param,timeout=5) except dic_request.exceptions.Timeout: return render(request,'no-def-100.html') except dic_request.exceptions.TooManyRedirects: return render(request,'no-def-100.html') except dic_request.exceptions.RequestException: return render(request,'no-def-100.html') else: print("this") return render(request,'no-def-100.html') When running on Heroku ,it always print 'this'. -
how to detect mouse click on a link and show the clicked details in another page?
how can i detect mouse click on a question,and also how can i display the clicked question to answer page ? views.py class SuccessView(FormView): template_name = 'success.html' form_class = QuestForm success_url='home' def get_context_data(self, **kwargs): context = super(SuccessView, self).get_context_data(**kwargs) st9=[] namee='' obj1=Logs.objects.all() obj4=Quest.objects.filter(status='1') for k in obj4: st9.append(k.question) context['st9']=st9 return context answer.html: <form action="" method="post">{% csrf_token %} <div class="form-group"> <label>Enter Your Answer :</label> <input class="form-control" type="text" name="anw"> </div> <button type="submit" class="btn btn-success">Add Answer</button> </form> <center> -
assert post worked Django
I just wrote some tests case about my forms, here is one : def test_department_admin_creation(self): nb = Department.objects.count() response = self.client.post(self.url, {"name" : 'department', "organization" : self.organization}) self.assertEqual(response.status_code, 200) self.assertEqual(nb+1,Department.objects.count()) And I'm wondering why the last assertion doesn't work while the status_code's one did. AssertionError: 2 != 1 Thank you ! -
Identify nouns and verbs from JSON
Imagine I have a JSON data like following: tasks=[ { "id":17, "title":"Browse through the list of books", "how_often":"DO", "how_important_task":"EI", "role":"reader", ... }, { "id":18, "title":"Search for a book", "how_often":"DS", "how_important_task":"EI", "role":"reader", ... }, { "id":19, "title":"Request a book", "how_often":"WO", "how_important_task":"RI", "role":"reader", ... }, { "id":26, "title":"See latest arrivals of the books", "how_often":"MO", "how_important_task":"LI", "role":"reader", ... } ] I am interested in extracting nouns and verbs from this data, possibly for each task object individually. Is it easier/better to handle on my angular frontend or django backend? Are there any libraries for angular which does something like this? Any libraries for django? -
Implementing Typeahead on django
I'm implementing typeahead for the first time and I'm doing something wrong in passing the URL here. This is my typeahead: $(document).ready(function(){ var getIsbn = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: "/update/?q=%QUERY", wildcard: '%QUERY' } }); $('#remote .typeahead').typeahead(null, { name: 'isbn', display: 'value', source: getIsbn }); }); This is my URL in urls.py: url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'), When I open network panel Page not found is being displayed. Any suggestion how to make this work? -
How to get template variable from within a custom template tag
In Django, is there a way for a custom template tag to have access to the current template's variables passed on by the view? My first thought is to make a parameter where the user can place the template variable manually but if my custom template tag can access the variable itself then it would be much better! To illustrate, I want to get rid of the parameter templatevar @register.simple_tag def sampletag(templatevar): return templatevar -
After post the bootstrap modal form and it will go to the action url using django
I am new to django, I tried to creating a data and edit the data using ajax modal and after post the bootstrap modal form and it will go to the modal form action url using django Here i attached the image Link Modal Form After the create the Modal and Update the Modal form ! Thanks Save the Modal def save_table_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() print("valid") data['form_is_valid'] = True tables = Rparequest.objects.all() data['update_form'] = render_to_string('uts/rpa_table.html', {'tables': tables}) else: print("Invalid") data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) Create a Modal def rpamodaltable(request): if request.method == 'POST': form = RparequestForm(request.POST) else: form = RparequestForm() return save_table_form(request, form, 'uts/send-request.html') Edit the Modal def table_update(request, pk): table = get_object_or_404(Rparequest, pk=pk) if request.method == 'POST': form = RparequestForm(request.POST, instance= table) else: form = RparequestForm(instance= table) return save_table_form(request, form, 'uts/update_table.html') -
What is the best way to create a cluster for Django REST Application
I was wondering, what is the best way to create a cluster from my own hardware for Django REST Application? My main goal is to train Deep Neural Network later on that cluster. While searching for the solution i came across : http://django-q.readthedocs.io/en/latest/cluster.html , but documentation seems confusing and I cannot figure out how to go through it. Any help would be appreciative ! Thanks in advance! -
Q objects OR query on a list
I am looking to apply an OR query on a list of elements in expertiseParams My code is : queryset_list = Profile.objects.all() for expertise in expertiseParams: queryset_list = queryset_list.filter(Q(expertisematch__expertise=expertise)) My question is : how can I implement the OR logic on all the Q object contained in expertiseParams? Thank you! -
Not Null Constraint Failed - null=True already set
I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations. Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register. My model now looks like: class Register(AbstractBaseUser, models.Model): username = models.CharField(max_length=20,default='',blank=True) password = models.CharField(max_length=80,default='',blank=True) email = models.CharField(max_length=255,default='',blank=True) #Added 2nd May #locations = models.ManyToManyField(Location) #3rd May change to foreign key locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='') USERNAME_FIELD = 'username' The model referenced is: class Location(models.Model): locationname = models.CharField(max_length=80,default='',blank=True) address = models.ForeignKey(Address, on_delete=models.CASCADE) geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='') When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes. "NOT NULL constraint failed: register_register.locations_id" I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error. -
Update a related model field based on another field
I have 2 model choice field Category and Sub Category. Sub Category is based on Category. I have to fill the sub categories with different set of results when Category is selected/changed . How to do this without using JavaScript in Django forms /templates I couldn’t find a reference to this -
Lookups that span relationships User
I have model Post class Post(models.Model): user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE,default=None) created_at = models.DateTimeField(auto_now=True) ...... First I have tried to get all post for the current user using the following code and things worked alright def get_queryset(self): return models.Post.objects.filter(user__username__iexact=self.kwargs.get("username")) Everything worked as expected for the code above. BUT when I tried to retrieve all users with posts that was created before certain date. I followed django documentation which is very clear and had this function. def get_queryset(self): return User.objects.filter(post__created_at__lte='2019-01-01') But django seems to expect only User fields not another model name and fields because the error I got is expecting User fields the error is: Cannot resolve keyword 'post' into field. Choices are: date_joined, email, first_name, group, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, posts, user, user_groups, user_permissions, username. Any ideas? Many thanks. -
Bootstrap javascript not working in Django
I downloaded bootstrap and configure in my Django application and every was good after sometime the Javascript stop working but the CSS is working i don't know what is wrong with it.The javascript stop after sometime of development after first of all working well {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width ,initial-scale=1, shrink-to-fit=no"> <meta name="author" content="Fon Desmond Ade"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% static 'tzuzz/css/bootstrap.min.css' %}"> <nav class="navbar navbar-expand-lg navbar-light bg-secondary"> <a class="navbar-brand" href="#" style="color: white">Tzuzz</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link nav-item" style="color: white" href="{% url 'tzuzz:login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" style="color: white" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" style="color: white" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" style="color: white" href="#">Link</a> </li> </ul> </div> </nav> <br> {% block body %} {% endblock %} </body> <footer style="padding-top: 70px" class="fixed-bottom"> <div class="card w-90"> <div class="card-body"> {% block footer %} {% endblock %} </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="{% static 'todo/js/bootstrap.js' %}"></script> </footer> </html> -
Django-CMS - Django Model Form not rendering
I'm building a new site in Django with Django-CMS that needs a form to filter JSON results and return the filtered set. My issue is that, initially, I can't even get the Django Model Form to render yet I can get the CSRF token to work so the form is technically rendering, but the inputs/fields aren't showing up at all. models.py: from django.db import models from .jobs.jobs import * roles = get_filters() loc = roles[0] j_type = roles[1] industry = roles[2] class Filter(models.Model): country = models.CharField(max_length=255) job_type = models.CharField(max_length=255) industry = models.CharField(max_length=255) search = models.CharField(max_length=255) jobs/jobs.py try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup import urllib3 import json http = urllib3.PoolManager() def get_filters(): response = http.request('GET', 'http://206.189.27.188/eo/api/v1.0/jobs') jobs = json.loads(response.data.decode('UTF-8')) job_list = [] for job, values in jobs.items(): job_list.append(values) roles_data = [] for job in job_list[0]: roles_data.append(job) roles_data = sorted(roles_data, key=lambda role : role["id"], reverse=True) loc = [] j_type = [] industry = [] for role in roles_data: loc.append(role['location']) j_type.append(role['type']) industry.append(role['industry']) return loc, j_type, industry views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import FilterForm def index(request): form = FilterForm() context = { 'form': form, } return render(request, 'blog.html', context) forms.py from django.forms import … -
Compressing and decompressing images when sending payload in django rest framework using lz4
I have the following model below. I would like to compress the document uploaded and then provide a link to the decompressed file it when a POST request is done. How do I use lz4 in a class based view to compress or decompress a payload that contains images? models.py class EmployeeDocument(models.Model): """ Model, Which holds Employee documents uploaded. """ employee = models.ForeignKey( Employee, related_name="employee_docs", null=True, blank=True) document = models.FileField( upload_to='Images/', default='Images/None/No-img.jpg') details = models.TextField() def __str__(self): return 'DOC - %s' % (self.employee.user.username)