Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Javascript, class and sequence diagram
I don't know how to visualise whole django project. What should it look like? For example I have an actor that is sending request.GET in order to see the page. So actor is sending that request to View class (right?). I don't exactly know how to mark this class. Should it be like: "Name_of_view_class(View): View", or maybe different? (I know, that convention is name:type" Then some Ajax, or jQuery action happens. Those functions are placed in HTML file. Again something like: "jQuery: Template", or by some kind of notes/stereotypes? -
django channels redis multiple consumers receive message a different times ensured?
Does this need to be implemented or is it in Channels already? If I have a channel group with multiple consumers subscribed to it and one consumer is sent the message is the message lost to the rest of the consumers or does the message persist until all consumers see the message? Or does the message persist for time until time is expired regardless of consumers seeing it or not? -
Cannot install psycopg2 Ubuntu
Trying to get a server ready for a django project and I'm running into some issues with setup for postgres. I'm following this guide: https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html And I'm at step 5: Now, we need to configure postgreSQL so that it can communicate with our Django application. For this, install psycopg2 database adapter. But this adapter have some package dependencies, so first install them. run: (django_env) $ sudo apt-get install libpq-dev python3-dev then... (django_env) $ pip install psycopg2 I do that, and this point in the instructions, I get a "compilation failed" error. I tried the solutions suggested in this stack exchange question: Trouble with psycopg2 in virtualenv python3 for use with Django and this one: Cannot install psycopg2 on virtualenv I am very much a linux and django noob, so if this is a duplicate issue, please have mercy on me and leave a comment explaining why you are marking it as a duplicate as you do so. Thanks for your time! Here's the output and install command that caused it: (django_env1) user:/home/projects/sample_project$ sudo pip install psycopg2 Downloading/unpacking psycopg2 Downloading psycopg2-2.7.3.2.tar.gz (425kB): 425kB downloaded Running setup.py (path:/tmp/pip_build_root/psycopg2/setup.py) egg_info for package psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 building … -
Access Methods form django apps within the same project = Django
I am have a django project that I am creating. Within the django project I have two apps which as user and common. I want to use a method that validates if a user is logged in from the common apps views.py file within the user views.py file. How can I can the LoggedIn method from the common view.py in a method from he user views.py Home method.... User -> views.py file: # checks if someone is logged in def Home(request): # check if there is a user logged in currentUser = LoggedIn(request) # no user logged in if currentUser == None: # send user to the main sign in and log in form return redirect('Signup') # a user logged in else: # users home page content will be down below parameters = 'parameters' Common -> views.py file: def LoggedIn(request): if 'username' not in request.session: return None else: user = request.session['username'] currentUser = User.objects.get(username=username) return curentUser I cant seem to get how to call one method from a different app. I don't want to have to redirect the user but rather just call the method and return a value to the Home method in the user app views.py file. Couldn't … -
Django Isolated Subdomains
Let's say we have a model called Event with a slug name. I'm looking to configure my Django app to basically isolate all my other models into separate apps depending on the event. For example: "http://annualmeetup.domain.com" # in the form of "http://{}.domain.com".format(e.name) How would I create completed isolated apps such that my models for users, meetings, and others only work in the context of the given subdomain? I was thinking about writing multiple apps for each event and copying the same models via a command script, but I still don't know how to point an app to a subdomain. -
proper way to validate django unique_together
I've searched lots of answers about unique_together, but haven't found anything appropriate. I've got model like this: class Skill(models.Model): user = models.ForeignKey(User, blank = True) title = models.CharField() ... class Meta: unique_together = ("user", "title") And form like this: class SkillForm(forms.ModelForm): class Meta: model = Skill fields = ( 'title', ... ) But now when I try to create new Skill with same user and title I got: IntegrityError at /skill/new/ UNIQUE constraint failed: personal_page_platform_skill.user_id, personal_page_platform_skill.title I need a proper way to catch this situation without user field in form. Problem is not in blank=True of user, because in my view I got user from request. Also get_or_create method is not for me, I guess. Here my view, if needed: @login_required def skill_new(request): if request.method != "POST": form = SkillForm() return render(request, '...', {'form': form}) form = SkillForm(request.POST) if not form.is_valid(): return render(request, '...', {'form': form}) skill = form.save(commit=False) skill.user = request.user skill.save() return redirect('...', username=request.user.username) -
Django How to make conditional forms, query, and character replacement
I am working on a language app that will generate form to take user input > search db > if it exists in db, return the input word and the translated word if input does not exist, prompt user if they want to add new word to dictionary > new form will have 2 text areas one for the word in english and the other for the word in other language > return (display) user inputs to confirm if entered correctly > if correct save to db the text area used in the input for the word in other language must be able to handle unicode characters. i can do this part in html javascript as seen below.... I have basic understanding of django but how can I combine everything (particularly the char replacement) it into a seamless django app? function replaceStuff(aObj){ aObj.innerHTML = aObj.innerHTML.replace('.O','Ọ') aObj.innerHTML = aObj.innerHTML.replace('.o','ọ'); aObj.innerHTML = aObj.innerHTML.replace('.E','Ẹ'); aObj.innerHTML = aObj.innerHTML.replace('.e','ẹ'); } function printStuff(aObj){ document.getElementById("strDiv").innerHTML = document.getElementById("tArea").innerHTML; } Print Stuff -
Ajax Call not being passed, POST.request shows as None
I am having issues getting my POST request to capture the selected check boxes. It's been suggested to me to use Ajax so I did with the following: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(document).ready(function () { var SelectedItems = []; $('.checkbox').click(function () { var SelectedItems = $(this).val(); var index = SelectedItems.indexOf(SelectedItems); var url = window.location.href.split('?')[0]; if (index == -1) { SelectedItems.push(SelectedItems); } else { SelectedItems.splice(index, 1); } }); $('#submit-button').click(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'requestaccess' %}", data: JSON.stringify({ report_id: SelectedItems }), dataType: 'json', type: 'POST', success: function (data) { }, }); }); }); </script> When I push the button my chrome developer Network tab only shows the jquery.min being the initiator. However, when I print my request.POST call as a get or getlist on the request access view it displays either an emptylist or NONE, my web application isn't switching from /account/profile to /account/requestaccess on the button press: [15/Nov/2017 15:04:02] "POST /account/requestaccess/ HTTP/1.1" 200 1031 None [] [15/Nov/2017 15:04:43] "POST /account/requestaccess/ HTTP/1.1" 200 1031 My view for requestaccess is the following: @csrf_exempt def requestaccess(request): import simplejson as json owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0) … -
Advantage of django over HTML, CSS and JS
I know that there are questions like this but please bear with me, I still don't understand something, so let's say I have a very simple web page which has a text input and a button. when the user inputs text and presses the button a js script is called to display whats in the text input. simple, right? if I were to use Django to return an HTML file can I make it so that button is instead tied to python script? if not where does python come in? and what advantages does django have over html, css and js websites and am I supposed to use HTML with Django? also can you create a standalone django app (eg: .exe)? I'm still a little confused about this. -
Autocomplete Select will redirect to new url
I am using the .autocomplete from jquery-ui. What do I want? I would like to search through my ajax URL and return whatever is in my DB. When I click on the autocomplete suggestions, I want it to redirect to another URL. I have seen some questions that ask for what I want, but I can't seem to get the redirect going. My python view only GET's the 'q' after I click on the item and it fills the input with the name then I press 'Enter' and then it'll redirect. I am using Django, and inserting all the js/query code inside of my templates for now. views.py def search_boards(request): boards = Board.objects.all() query = request.GET.get('q') if query: print(query) boards = boards.filter(name__icontains=query).distinct() if boards: print(len(boards)) return HttpResponseRedirect(reverse('home')) return render(request, 'search_boards.html', {'boards': boards}) def ajax_search_boards(request): if request.is_ajax(): search_text = request.GET.get('term', '') boards = Board.objects.filter(name__icontains=search_text) return JsonResponse([{'id': i, 'value': v.name} for i, v in enumerate(boards)], safe=False) search_boards.html <body> <form method="GET" class="post-form">{% csrf_token %} <label for="autocomplete">Select a programming language: </label> <input name="q" id="autocomplete"> </form> <script> $("input[name='q']").autocomplete({ source: '/ajax_search_boards/', select: function(e, ui) { if ($("input[name='q']").val(ui.item.value)) { $("#autocomplete").val(ui.item.value); $("#autocomplete").submit() } } }); </script> </body> -
Django: Read uploaded CSV file using FileField instance
I'm trying to read the data of a .csv file uploaded by a user in a field of type FileField. I have no problem acessing the object, but I can't seem to make it work with the csv module. Here is what I'm trying: reader = csv.reader(object.uploaded_file.read()) for rows in reader: ... Where object is an instance of my model and uploaded_file the corresponding field. I'm getting this error: iterator should return strings, not int (did you open the file in text mode?) Also, I tried to use the open() method but whitout success. The documentation on this subject seems so vague. Even worst, the only thing I could find on the read() method used above is this: In addition to the listed methods, File exposes the following attributes and methods of its file object: encoding, fileno, flush, isatty, newlines, read, readinto, readline, readlines, seek, softspace, tell, truncate, write, writelines, xreadlines, readable(), writable(), and seekable(). EDIT I know it probably has to do with the reading mode has this thread suggest, but how can I change the mode in this case ? -
Getting the height of a Cloudinary Image Object in Django
in my models, I have the following code: class Product(models.Model): display_picture = CloudinaryField('Display Picture') It allows me to upload images directly to Cloudinary using a simple Django form. However, I need to get the height of these images. How exactly do I do this? Is there a built-in method that I can call that returns the height? Thanks. -
Reading in field from parent in foreign key relationship in DRF
Really struggling with this and it seems like it should be really straight forward. Basically, I am just trying to the products associated with a user, and then the short_name for each of those products to be rendered on the FE. I have a table that has the user_id and prod_id. The table can look like this: user_id | prod_id ----------------- 2 | 42 2 | 2 2 | 21 13 | 7 13 | 17 13 | 2 The user_id is a models.ForeignKey to the User table and the prod_id is a models.ForeignKey to Products table. Better yet, here is the model: # ./home/models.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Product(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=16) name = models.CharField(max_length=255, blank=True, null=True) short_name = models.CharField(max_length=128) updated = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(blank=True, null=True) def __str__(self): return self.short_name class Meta: db_table = 'Product' class UserToProduct(models.Model): user = models.ForeignKey(User, related_name='user_name', db_column='user_id', null=True) prod = models.ForeignKey(Product, related_name='prod_name', db_column='prod_id', null=True) class Meta: db_table = 'User_to_Product' unique_together = ('user', 'prod') What should be happening is the React front-end sends the user_id based on who is logged in to the Django/DRF back-end. This is happening just fine. Here … -
How to make a vocabulary quiz webapp just like in Memrise.com and what programming language is best for it?
I have a task for making a vocabulary quiz just like in Memrise.com. We already have a fully functional website on Wordpress. I have to integrate that quiz into it. Please help and elaborate from where I can start and I complete it. -
Is it a good idea to change behavior of back button in browser?
I have a web form with multiple steps/pages (I'm using django-formwizard) that is dependent on POST requests like the typical web form. If the user presses the back button, things break. I in this Stackoverflow post that you can stop the default behavior of the back button while it's on your own domain before it unloads the page. I am thinking about, if the form step is greater than 1, I assume the user is trying to go back to step 1. Therefor, I ask the user to confirm, telling them of the great sin they're about to commit. If they say yes, call a GET request to the form with step 1 (which would undo all of their input as a side effect. I would tell them about this in the confirmation). If they say no, I would block the event they were just trying to do (go back) and stay on the current page (my form at the current step). Is this a good idea? -
Insurance quote website based on Django
I am a newbie in Django. I want to build a car insurance quote website based on Django. Basically, users input their information such as car type,age, gender,etc. and then my website take users' information as inputs into my model( I have already created my model based on Python) and then shows the result of model which also need to put on the website. Can all above steps be done by Django? The first step is to take inputs from users and then input to my model. Which feature in Django should I use? Should I use Django form to do that ? Is there any similar project on Github that I can look? Thanks for helping!! -
Django poll tutorial AttributeError
I've ran into problem with Django Poll tutorial. For some reason, I keep getting AttributeError: 'Question' object has no attribute 'question_text' I've been following tutorial step by step, not sure what went wrong. Mmodels.py: from django.db import models import datetime from django.utils import timezone class Question(models.Model): # ... def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): # ... def __str__(self): return self.choice_text -
Upgrading Python from 3.5 to 3.6 causes Oracle error ORA-28040
I have a Django application that connects to an Oracle database. It's a very standard application, does everything conventionally. Everything works great, and database communication succeeds with: Python 3.5.4 Django 1.11.7 cx-Oracle 6.0.3 The Oracle database version is 12.1.0.2, and the Oracle client is properly installed as far as I can tell. sqlnet commands work to test the connection. However, when I upgrade to Python 3.6.3, I receive the Django error: DatabaseError at /... ORA-28040: No matching authentication protocol I kept the Django and cx-Oracle versions the same. The only thing that changed is the Python version. Is there something I need to configure or change in Python 3.6 to correct this? -
Settings up django project in nginx and php project in apache2 in one VPS server
I am trying to run 4 domain in one VPS server. 2 of them i will run in apache2(php/wordpress). And rest 2 (My django project) i will run on nginx+gunicorn. But here some of the problem i am getting. 1. Whenever i am installing apache2 it's taking all the associated domain of this server and show it's default page on them. Even if i try to show nginx hosted site to any domain apache2 doesn't let me do that. Also having trouble to run 2 domain in 2 sepearte sites-available/abc.conf file. So in one word my question is:- What are the procedure that i should follow to run in my one VPS server many domain/sub-domain and also in different different server.(nginx + apache2). Also as i said before the time i set one domain all other domain associated with my this server start getting the value and shows the same web page. How to stop it and as long as i am not settings up any domain with any host(apache2 or nginx) it show nothing found page. Thanks -
Django get children/father of many2many self referenced
I have this class: class Group(models.Model): dependency = models.ManyToManyField('self') name = models.TextField() I need to get in different queries: From one id I need to get all children. From one id I need to get all fathers. Thanks! -
Bootstrap-table: Server Side pagination + nextPage method
I'm using Django and the app Bootstrap-table to correctly format my tables. I've got a lot of data so I'm using a server-side pagination. It's working great. Now I'd like to implement some method like a nextPage method. By combining the example jsfiddle of server-side pagination + method nextPage, it doesn't work: http://jsfiddle.net/ThePhi/msj2apLb/1/ <button id="button2" class="btn btn-default">nextPage</button> <table data-toggle="table" data-url="http://issues.wenzhixin.net.cn/examples/bootstrap_table/data" data-pagination="true" data-side-pagination="server" data-page-list="[5, 10, 20, 50, 100, 200]" data-search="true" data-height="300"> <thead> <tr> <th data-field="state" data-checkbox="true"></th> <th data-field="id" data-align="right" data-sortable="true">Item ID</th> <th data-field="name" data-align="center" data-sortable="true">Item Name</th> <th data-field="price" data-sortable="true">Item Price</th> </tr> </thead> </table> <script> var $table = $('#table'), $button2 = $('#button2'); $(function () { $button2.click(function () { $table.bootstrapTable('nextPage'); }); }); </script> -
Django blog - calling latest 3 posts per category via many to many
So far my blog project has : Models.py class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Meta: verbose_name_plural = "categories" class Post(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=500, default = True) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) categories = models.ForeignKey('Category', default=True) def __str__(self): return self.title Views from django.shortcuts import render from .models import Post, Category def getAllCategories(request): categories = Category.objects.all() context = { 'categories':categories, } return render(request, 'categories/getAllCategories.html', context) Template {% extends "../posts/base.html" %} {% block content %} <div> {% for category in categories %} <div> <h3>{{ category.title }}</h3> <ul> {% for post in category.post_set.all %} <li><a href=#>{{post.title}}</a></li> - {{post.summary}} {% endfor %} </ul> </div> {% endfor %} </div> {% endblock %} This pulls through all of my posts per category fine - however I'm stuck as I would like to only pull through the latest three posts per category. I understand that in a simple view you can use order_by()[:3], but then you can't use post_set with that. So I need a way of filtering by top three posts within a category, so using the many-to-many relationship. Hope this is clear. Many thanks -
Add logic in admin panel in Django
I have two models, the second model is FK from my first model like this: class Model0(models.Model): work = models.FloatField(blank=True, null = True) class Model1(models.Model): class Meta: unique_together = (('lat', 'lng'),) lng = models.FloatField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) class Model2(models.Model): idWork = models.ForeignKey('Model0', on_delete=models.CASCADE) idSTFolio = models.OneToOneField('Model1', on_delete=models.CASCADE) I use admin panel to add my data, I need that when I add a second (Model0, Model1) with others values to Model1, in my Model2 this association was created automatically like this: for example: Model2 : (Model0, Model1) Id 1 : (1.5, (2.5, 3.0)), 1.5 is 'Work' from Model0 and (2.5, 3.0) lat and lng in Model1 I need something like this...in this moment I create other Model1 with these values (2.5, 4.0), so like lat: 2.5 has already been added in Model2 I need that in my Model2 add other row like this automatically : Id 1 : (1.5, (2.5, 3.0)) Id 2 : (1.5, (2.5, 4.0)) Any idea if it is possible to modify the admin panel for what I need? In this moment I must add this association in my Model2 page in admin panel, but It not is my idea. -
Button no longer changing URLafter Ajax and data not coming through POST
I have the following JS/Ajax. Which appears not to capture the value on report_id for a POST, if I change the type to GET I can see the values for report_id, so I know the ajax call is working correctly. <script> $(document).ready(function () { var SelectedItems = []; $('.checkbox').click(function () { var SelectedItems = $(this).val(); var index = SelectedItems.indexOf(SelectedItems); if (index == -1) { SelectedItems.push(SelectedItems); } else { SelectedItems.splice(index, 1); } }); $('#submit-button').click(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'requestaccess' %}", data: JSON.stringify({ report_id: SelectedItems }), dataType: 'json', type: 'POST', success: function (data) { }, }); }); }); </script> When I attempt to print the results in my requestaccess view the console displays the following after pushing the submit-button: Quit the server with CTRL-BREAK. None [] [15/Nov/2017 11:56:50] "POST /account/requestaccess/ HTTP/1.1" 200 2 My for requestaccess is the following: @csrf_exempt def requestaccess(request): import simplejson as json owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0) if request.method == 'POST': checkedlist = request.POST.getlist('report_id') checked = request.POST.get('report_id') print (checked) print (checkedlist) args = {'retreivecheckbox': checkedlist} return HttpResponse(json.dumps(checkedlist), content_type="application/json") What's not happening is after I push the button my … -
Running django in a virtual machine vs dual boot
I normally work in C++ and embedded systems, but I would like to get into some web development. The problem is that the share number of technologies and choices I have to make before I can even get started is extremely daunting! I am already familiar with Python, so I though I would choose a technology that is based on that. From what I can gather, LAMP and django is the way to go. My first goal is to make a web server, maybe on a raspberry PI, maybe on a laptop or desktop computer, that will read some sensors around the house and that I can access from outside. The main goal is to get acquainted with web development in general. Should I add anything else on my list of things I need to learn (other than HTML, CSS and JavaScript)? Should I start with a virtual machine on my Windows laptop, install Ubuntu as a dual boot or just install Django under Windows? Any guidance on how to get started is appreciated!