Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Range Slider POST to view
Wondering if someone can help me out, As I am new to JQuery and DJango and currently finding it tricky to figure this issue out. I have the following model with various books models.py class Books(models.Model): articleid = models.CharField(primary_key=True,max_length=20) author = models.CharField(max_length=300) title = models.CharField(max_length=500) rating = models.FloatField(blank=False, null=False) publisheddate = models.DateTimeField(default=datetime.now, blank=True, null=True) In the views.py file, the default view is to list all books ordered by publisheddate def index(request): all_books = Books.objects.all().order_by('-publisheddate') context = { 'all_books': all_books, } return render(request, 'library/index.html', context) Now I would like to add a JQuery Range Slider (https://jqueryui.com/slider/#range) that users can then use to filter out to only display books that are within a min and maximum rating (as an example all books that are between 6 and 10) will only be displayed. html code I have so far <script> $( function() { $( "#slider-range" ).slider({ range: true, min: 1, max: 10, values: [ 1, 10], slide: function( event, ui ) { $( "#rating" ).val( "Low" + ui.values[ 1 ] + "High" + ui.values[ 10 ] ); } }); $( "#rating" ).val( "Low" + $( "#slider-range" ).slider( "values", 1 ) + "High" + $( "#slider-range" ).slider( "values", 10 ) ); } ); </script> … -
Why I have AttributeError in django-realtime
I use this framework https://github.com/anishmenon/django-realtime I read solution and write this: def index(request): post = Post.objects.get(id=1) print(post.title) ishout_client.emit( Post.title, 'notifications', data={ 'test' : 'test' } ) return render(request, 'index.html', { }) But i got this: AttributeError: 'NoneType' object has no attribute 'read' I just want write webapclication where I click button and another browser get console log 'clicked' for example. -
Page Not Found - how to find current path is valid in Django URL's?
Please Note I gone through all answer i didnt found solution, I am getting this error, i know current URL asdf is not presented in urls.py my question i want to check whether my current path is in urls or not? i tried path == reverse('some_view') but i need existing specific view to test. but i dont have anything except current path. here is the not found error, Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8002/asdf/ here i want to redirect if URL is not present in urls.py how to do this? -
Dajngo and approximative category
I work in a company which develops a price comparator with Django (1.11). We have uploaded catalogs from merchants and my job is to find the related category for each products. Then, in our website we have about 22 categories (home, dress, glasses, barbecues, speakers, ...) Each catalog uploaded by a merchant has thousand products with properties such as: - name - description - category - price - ... This category can be each a word or a full category path (i.e: dress > shoes > baby > ...) My question is: how can I find the best category from submitted informations ? I've tried to use trigram search on title but I have too many errors. categories_by_title = Category.objects\ .annotate(distance=TrigramDistance('name', product_title))\ .filter(distance__lte=0.9)\ .order_by('distance') Do you know how can I find the most appropriate category function of submitted products ? There are many price comparator but I do not know how they do. Thanks -
Django multiple databases (sanity check)
Afternoon. I've read a good number of places about the topic, taking info from each as they don't all appear consistent, and believe I have this working. As this is a test setup, I don't want to get months down the line to find something's not working --- and it turns out to be down to this. Appreciate those more experienced than myself looking this over, and please make any suggestions. 'settings.py' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'abc123', 'HOST': 'localhost', 'PORT': '', }, 'ta1_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testapp1db', 'USER': 'ta1', 'PASSWORD': 'ta1', 'HOST': 'localhost', 'PORT': '', }, 'ta2_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testapp2db', 'USER': 'ta2', 'PASSWORD': 'ta2', 'HOST': 'localhost', 'PORT': '', }, } DATABASE_ROUTERS = ['spiderproject.routers.DBRouter',] 'routers.py' (in main 'spiderproject' folder) class DBRouter(object): def db_for_read(self, model, **hints): """Send all read operations on 'app_label' app models to associated db""" if model._meta.app_label == 'testapp1': return 'ta1_db' if model._meta.app_label == 'testapp2': return 'ta2_db' return None def db_for_write(self, model, **hints): """Send all write operations on 'app_label' app models to associated db""" if model._meta.app_label == 'testapp1': return 'ta1_db' if model._meta.app_label == 'testapp2': return 'ta2_db' return None def allow_relation(self, obj1, obj2, **hints): """Determine if relationship is allowed between … -
How to retrieve Django JSON variables in javascript?
I'm using JSONField() to save my json data on my models. What I would like to do is to get these json datas onto my javascript as JSON. Here's the error I get : SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data My JSON datas are valid, there's nothing missing in it since there's no error from JSONLint and I checked it already. What could be the problem ? models : ... json = JSONField() #('Layout' as model) views : ... layouts = Layout.objects.all() #('layouts' as context) Javascript : <script> {% for layout in layouts %} var data = '{{ layout.json|escapejs }}'; alert(data); var json = JSON.parse(data); alert(data); {% endfor %} </script> -
How to run one of failed tests in new tab in PyCharm?
Given situation: There is an app with 2000+ tests, all tests execution takes about 15-20 min. After major changes, a lot of tests are failing (let's say, 100+ tests). Re-execution of failed tests is possible by pressing corresponding button in Run window and takes about 2 min. Within the failed tests, only 2-3 tests re-execution is needed to identify and fix the issues in few iterations 'change code - run tests - check results'. ... but, currently the only option I have is to rerun all 100+ of failed tests, which is a big waste of time. Is there possibility to re-run specific failed test in new Run window, keeping the list of the 100+ failed tests for later re-run? I'm using current version of PyCharm, 2017.1.4. -
Showing certain fields of related models in Django Admin
I have following scenario: There are Containers. Each Container has Contents. There are Consumers. Each Consumer measures temperature of Contents I have Django admin page that shows: Consumer Container Content Container Content Temperature Date when Temperature was measured I need this page to show also 'Parent Container' for 'Container Content' How can I do it? Here is content of my models.py and admin.py in models.py: class Container_Model(models.Model): container_name = models.CharField(max_length=200) def __str__(self): return unicode(self.container_name) class Container_Content_Model(models.Model): container_content_name = models.CharField(max_length=200, ) parent_container = models.ForeignKey(Container_Model, related_name="parent_container", on_delete=models.CASCADE) container_content_consumers = models.ManyToManyField(Container_Consumer_Model) def __str__(self): return unicode(self.container_content_name,) class Container_Consumer_Model(models.Model): container_consumer_name = models.CharField(max_length=200) def __str__(self): return unicode(self.container_consumer_name) class Container_Content_Temperature_Model(models.Model): container_content = models.ForeignKey(Container_Content_Model) container_consumer = models.ForeignKey(Container_Consumer_Model) container_content_temperature = models.CharField(max_length=64, blank=True, null=True) container_content_temperature_measured_at = models.DateField() def __str__(self): return unicode(self.container_content_temperature) in admin.py: @admin.register(models.Container_Content_Temperature_Model) class container_content_temperature_model_admin(admin.ModelAdmin): list_display = ( 'container_consumer', 'container_content', 'container_content_temperature', 'container_content_temperature_measured_at', ) -
Passing Reason for Deletion to all Destroy End Points
In a Django Rest Framework app using Django Simple History to track model changes, how would one force a user to pass a Reason for Deletion for all Destroy End Points and then pass that reason to Django Simple History's Change Reason? Also, for related models with a Delete Cascade, would that reason be passed on to the related deleted entries? -
Gunicorn 502 gateway linked to sock file's permission denied error
I'm setting up a django, gunicorn and nginx and when I visit the homepage I get a 502 gateway error. The logs shows it's related to the permissions of the sock file 2017/07/01 09:59:18 [crit] 12237#12237: *23 connect() to unix:/home/sammy/revamp/revamp/revamp.sock failed (13: Permission denied) while connecting to upstream, client: 105.49.30.134, server: $ And the permissions are srwxrwxrwx 1 sammy www-data 0 Jul 1 05:29 revamp.sock gunicorn service is setup like so [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/revamp ExecStart=/home/sammy/revamp/revampenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/revamp/revamp.sock revamp.wsgi:application [Install] WantedBy=multi-user.target the permissions look okay and systemctl status gunicorn is active. -
reload page automatically without needing to RE-enter URL again Django
My webpage consists of 2 parts, upper part is a section that let user to enter data while bottom part displays all the data in database in a table form. When user selects "Add" button in the upper part, the data will be saved into database and being outputted in a table in bottom part of the webpage. Is there anyway to show the table once i select the "Add" button ? Right now what the code is doing is when "Add" button is being selected, it will load a new form but then the whole table will disappear. I have to manually type this address again "http://127.0.0.1:8000/hrfinance/lscholarship/" then only the table will appear. Even with refreshing the page will not work. Below is my code in views.py: def scholarship(request, id=None): query_results = [] if request.method == "POST": form = ScholarshipForm(request.POST) if form.is_valid(): scholarship = form.save(commit=False) scholarship.save() else: form = ScholarshipForm() id = request.GET.get('scholarship') query_results = Scholarship.objects.all() data = { 'query_results':query_results, 'form': form } return render(request, 'hrfinance/add_remove_scholarship.html', data) -
Django - TemplateView and POST
I have a page generated by a TemplateView and containing a POST form. How can I use this form with a TemplateView. There is an example similar of my code : class ProjetMixin(object) : ... def get_context_data(self, **kwargs) : ... return context class AView(ProjetMixin, TemplateView): template_name = 'path-to-the-page.html' offre = None def get_context_data(self, **kwargs) : context = super(AView, self).get_context_data(**kwargs) try : self.offre = self.projet.offredeprojet except OffreDeProjet.DoesNotExist : self.offre = None if self.request.user.is_authenticated() : print(" method = ",self.request.method) //display "GET" if self.request.method == "POST" : print("post") context['offre'] = self.offre return context So it's normal that the only method is GET but how can I use POST ? I have this error when I submit the form : Method Not Allowed (POST): /projets/pseudoaz/recrutement [2017/07/01 11:50:57] HTTP POST /projets/pseudoaz/recrutement 405 [0.06, 127.0.0.1:57560] Thank you -
How to update serialized data on valid?
I have two models, BookTicket and Ticket. class BookTicket(models.Model): user = models.ForeignKey(User) booking_ref = models.CharField(max_length=25, blank=True) class Ticket(models.Model): seat = models.ForeignKey(Seat) user = models.ForeignKey(User) show = models.ForeignKey(Show) booking_ref = models.ForeignKey(BookTicket) And this is the data from the client side [ {u'seat': 49, u'user': 3, u'show': 2}, {u'seat': 50, u'user': 3, u'show': 2} ] What I would like to do is, if the serialized is_valid, then create a new booking object, and update that object as the booking_ref for the all tickets data. def buy_ticket(request): serialized = TicketSerializer(data=request.data, many=True) if serialized.is_valid(): ... b = BookTicket.objects.create(user=request.user) ... ... update all of the data's booking_ref with newly created booking instance i.e., b ... serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) How can I do that? -
Performing a right join in django (take 2)
With reference to Performing a right join in django , when I try a similar approach (field slightly different): class Student: user = ForeignKey(User) department = IntegerField() semester = IntegerField() class Attendance: student_attending = ForeignKey(Student, related_name='attendee') subject = ForeignKey(Subject) When I run this query: queryset = Student.objects.all().select_related('attendance_set') I get this response: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'attendance_set'. What could trigger that warning and how do I get the 'join' to work properly? -
Collectstatic populates thousands of files Django
So im trying to get my site to production and I have huge problems with the staticfiles(Im using white noise). Beside of my other Problems, each time when I run ./manage.py collectstatic all files get compressed again and saved in the static folder. currently I have around 5500 static files. Here is an example of the admin/css folder. I have two questions: How can I stop to populate so many files? Is there a known way to clean the static folder so its not so heavy? -
Efficient backend for finding nearby properties
I am thinking of building an app based on location for finding nearby properties around 15 km from the location of user. I am a beginner in Django and for such use case I could code the following for finding nearby properties. Is the following code efficient or how can it be improved for more precise result? Right now this is my code to find nearby property around 15 km. @api_view(['GET', ]) def nearby_property_finder(request, current_latitude, current_longitude): user_location = Point(float(current_longitude), float(current_latitude)) distance_from_point = {'km': 15} properties = Property.gis.filter(location__distance_lte=(user_location,D(**distance_from_point))) properties = properties.distance(user_location).order_by('distance') if properties.exists(): paginator = ResultInPagination() paginated_properties = paginator.paginate_queryset(properties, request) serializer=PropertySerializer(paginated_properties, many=True) return paginator.get_paginated_response(serializer.data) else: return Response({}, status=status.HTTP_200_OK) -
Django: translate parametric messages
I'm using Django 1.11 and I am currently translating my app into other languages. Django is, of course, well-equipped for translations, but I have ran into following problem: At one point my app generates parametric messages, such as John has created Foo Bar has been changed to Foo Foo occurred at 12.00 and so on. The words in italic are dynamically generated when the message is generated. Now the problem is this: After the message is generated, I need to store it into the database. However, at this time I do not know in which language it should be displayed. That means I cannot translate it at the time of storing. If the message was non-parametric, I would store it in English and then use gettext when displaying the message. I believe this is not possible with the parameters. Also, there are many types of messages and also new ones are constantly being added, therefore I cannot just extend the message model to |message|param1|param2| where message would be in the form of e.g. {param1} has created {param2}. If I did this, the model would be very large and constantly getting larger. I hope I made the issue clear. Is there … -
upload multiple image and associate to property
I am using django rest framework for rest api. I am trying to work on mutiple image upload and associate those multiple images to property. However my browsable api does not show form to upload the images so i can test if my code works or not. How can i upload multiple image and associate them to property? class Property(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) address = models.CharField(_('Address'), max_length=140) rooms = models.PositiveSmallIntegerField(_('Rooms')) class Gallery(models.Model): property = models.ForeignKey(Property, related_name="gallery") caption = models.CharField(null=True, blank=True, max_length=80) image = models.ImageField(upload_to="properties/rooms/") class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields=('id', 'caption', 'image', ) class PropertySerializer(serializers.ModelSerializer, EagerLoadingMixin): _SELECT_RELATED_FIELDS = ['owner', ] _PREFETCH_RELATED_FIELDS = ['property_type',] gallery = GallerySerializer(many=True) class PropertyGallery(APIView): serializer_class = GallerySerializer parser_classes = (FileUploadParser,) def put(self, request, property_id=None, format=None): serializer = self.serializer_class(data=request.data, partial=True) if not serializer.is_valid(): return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) else: serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) url(r'^upload/images/(?P<property_id>[0-9]*)/$', views.PropertyGallery.as_view(), name='property-gallery'), -
Updating table with Ajax
I have a data table that I am trying to append rows to when there is new data to display. I'm relatively inexperienced so I took the easy way out on this and wanted to write a script that checked the database for updates every second instead of listening for server-sent events. I tried to write an Ajax query that would get all the objects in the data table, and if their 6th value is false (which means they have not been loaded), then it would add a row to my data table with that information. My tables are in a Django webapp, and here's the code I have tried to implement: <script type="text/javascript"> $(document).ready(function(){ var table = $('#example').DataTable(); setInterval(function(){ newrequests = $.ajax({ type: "GET", url: "/main/newrequests/", // I tried this and it didn't work // success: function(data) { // for(i = 0; i < data.length; i++){ // // check if the request has been loaded // if(data[i][5] == 0) // // if not, load and set to loaded // table.row.add(data[i]).draw; // data[i][5] == 1; // } // } }); for(i=0; i<newrequests.length; i++){ if (newrequests[i][5] == 0){ table.row.add(newrequests[i]).draw(); newrequests[i][5] = 1; } } }, 1000) }); </script> I have a … -
Friend matching query does not exist
def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id, friend = Friend.objects.get(current_user=request.user), friends = friend.users.all()) args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends} return render(request, self.template_name, args) -
Redirecting to the previous page upon a 500 error
I am using Django for my web app and it uses a payment gateway for taking in transactions. I have used validations for checking the required fields for the gateway and it works just perfectly fine. Now I just crashed into a case when someone was trying to donate but the "key" itself was missing from the dict I was passing to the gateway. I tried making a payment myself and it again worked perfectly fine. I want to have my app redirect back to a particular page if in case it gets an unhandled exception such as this, that is, a 500 error. I want this 500 error redirect for just this particular view and not for all 500 errors. -
How to use for with a function in a django template?
I am using this function to tokenize sentences in my blog posts: def sentence_tokenize(string): sents2 = sent_tokenize(string) return sents2 In my html template when i am using this line of code: {% sentence_tokenize post.text %} It successfully sent the post text to the function and return a list of all sentence. I need to use for loop to get each sentence in seperate line, but it gives an error, here is my code: {% for sentence in sentence_tokenize post.text %} {{ sentence }} {% endfor %} And here is the error: TemplateSyntaxError at /post/1/ 'for' statements should use the format 'for x in y': for sentence in sentence_tokenize post.text any suggestions? -
Django, what is the maximum number of queries per view, which does not cause serious speed issues
I'm new to django, I have this application where each of my views have an average of 6 queries. Is that ok, or should I optimise my database for better. -
Django formset hidden foreign key
This question and answer got me 90% of the way there. So thank you community. I have a modelformset, which validates and goes into the 'if valid' loop models.py class session_log(models.Model): anaesthetist_id = models.ForeignKey('auth.User') session_start_datetime = models.DateTimeField(blank=False) session_end_datetime = models.DateTimeField(blank=False) session_type= models.ForeignKey(session_types, null=True, blank=True) session_comments=models.TextField(null=True, blank=True) def __unicode__(self): return str(self.anaesthetist_id)+" "+str(self.session_start_datetime.date())+" "+str(self.session_type) forms.py class SessionList(forms.ModelForm): session_comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':1})) session_start_datetime = forms.DateTimeField(input_formats=['%d/%m/%y %H:%M',], widget=forms.DateTimeInput(format="%d/%m/%y %H:%M")) session_end_datetime = forms.DateTimeField(input_formats=['%d/%m/%y %H:%M',], widget=forms.DateTimeInput(format="%d/%m/%y %H:%M")) class Meta: model = session_log exclude = ('anaesthetist_id',) fields = ['session_start_datetime', 'session_end_datetime', 'session_comments','session_type'] views.py def session_overview(request): SessionListFormSet = modelformset_factory(session_log, form=SessionList, extra = 10, exclude =('anaesthetist_id',), can_delete=True) x = session_log.objects.filter(anaesthetist_id=request.user.id).count() y = x-10 initialformset = SessionListFormSet(queryset=session_log.objects.filter(anaesthetist_id=request.user.id).order_by("session_start_datetime")[y:]) if request.method == 'POST': submitted_data = SessionListFormSet(data=request.POST) if submitted_data.is_valid(): for session in submitted_data: new_session = session.save(commit=False) new_session.anaesthetist_id = request.user new_session.save() The x and y are in there to reverse the queryset and give me the last 10 results in descending order, so that you add a new session, usually a later one, to the bottom of the formset. It's a stylistic bodge The problem is that when I try and save or edit a form I get: IntegrityError at /trainee/dataentry/ NOT NULL constraint failed: trainee_session_log.session_end_datetime But I can bodge it by adding an 'if … -
In Django button and Hyperlink click event
In Django button click event then i want to display signup.html page http://127.0.0.1:8000/home/signup.html like this give me a sample code please i want like this if user click signup it directly goes to signup page