Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setup Django with Pycharm
I am currently following the tutorial in the link below to set up a Django file. https://www.jetbrains.com/help/pycharm/step-4-creating-and-running-your-first-django-project.html I can install Django for a certain project via adding a package in the project interpreter. In the picture in the link it seems that it is installed for every project. Also, I do not have a "more settings"-option in the new project options. What am I doing wrong? I am using Pycharm 2017.3.3. -
Two Django apps, and Two different servers
I' have two Django applications on two different servers. Server A = Regular Django App Server B = Django Based Rest API My question is how can I fetch the data from the Server A, using the RestAPI. This way I can keep the API and the other Django apps separate. Cheers, S -
jquery .load() causing elements to disappear
I'm using jquery "load()" to update some data whenever the user clicks on a like button. Here's my javascript code: $(document).on('click','.post-like',function(event){ event.preventDefault(); var data = $(this).attr("data"); var refresh = "#"+data; var urll = $(this).attr("formaction"); $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); $.ajax({ url :urll , type : 'POST', data: {}, success : function(json) { $( refresh ).load("{{request.path}} "+refresh); }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); Everything function just fine when I refresh a div that contains the whole page. But when I try to target a specific element or a div inside the page, the element disappears or shifts position. -
django migrating existing database and not using all tables
I recently integrated an existing legacy database-MySQL into models.py in django. There are many tables in this database that I do not need imported in models.py. Is it a good practice to delete the tables one does not need-which corresponds to deleting the classes associated with those tables? -
Can the choices defined in a model class be accessed elsewhere outside the model class?
I have the following model class class Movies(models.Model): MOVIE_CHOICES = ( ('SHAW', 'Shashank Redemption'), ('NIGHT', 'In the Heat of the Night'), ('GOD', 'The God Father'), ('INVIC', 'Invictus'), ) and I am writing the values to a database table. When I query the database table, I will get the key back, e.g. I get 'INVIC" back. In my code I will need to get the value for the key, in this case 'Invictus'. To be able to do this, I need access to the data structure that holds the key-value pair. How to access MOVIE_CHOICES by key outside of the model class? Alternatively, can I use a dictionary to set values for choices? -
How do I replicate behaviour in my Django template?
I have this page which renders my courses from my Courses model. It also allows me to paginate or search through them. But I also want to sort the courses by faculty or by study programme (other models) and be able to paginate or search through them as well. Basically I want that by clicking, for example, on faculty name on the left column, the content on right column will be replaced with the courses of that faculty, and they will also have pagination and be searchable. I think is easy, but I don't have any idea yet. def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Sort courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li><a href=""> {{ faculty.name }}</a></li> {% for department in faculty.department_set.all %} {% for study in studies %} <ul> {% if study.department == department %} <li>{{ study.name }}</li> {% endif %} </ul> … -
Add console to Django error page
Does anyone know of a package that would let you add a console to the django error page? When my template produces an error I want to be able to check out my query sets without having to go back to my view pages/ pdb -
How to convert an existing Django app to run in a virtualenv?
There are so many questions about this, and so many tries I've made and probably bungled... But let me stick to the real problem: I have a fledgling Django app that I want to insulate from future changes to support software. I think putting in under a virtual environment is the answer. I'd like guidance, even just a pointer to the right Howto (one about migrating, not a fresh install). My environment is Ubuntu 16.04.3 LTS, apache2, python3.5 and django 2.0. I'll be upgrading to the next LTS, which is why I want to insulate this app from changes. Complicating matters is the fact that python2 and python 3 are both here, and pyhton2 is the default (what you get when you just call for "python". That makes things weird, for instance, because pip3 is uses the default python, so the output of 'pip3 freeze' is very different from what I get when I run it under python3, and I don't know the details of why. What has failed in the past is my attempts to do it following guidance aimed at a freshly installed OS. What's more, probably because I did something wrong, pip3 lives in my $HOME/.local/bin/pip3. I … -
Add CSRF token to hard coded Django form
I am building a static page with Jekyll that has a hard coded form, I am sending the form data to a Django server, I am having trouble generating a CSRF token. The only way I could get the data to save to the database was if I used a static csrf token which is hacky and pointless. Is there a better way this can be done? This is what I want: <form method="POST" action="http://djangoserver" > {% csrf_token %} <!-- Doesn't work in Jekyll --> <input type="text" name="name" required id="id_name" maxlength="100> </form> But obviously Jekyll doesn't know what that token is, and the POST doesn't send it to the Django Server. This works, but it is vulnerable and hacky, I need the same effect that actually generates a unique token every time. <form method="POST" action="http://djangoserver" > <input type="hidden" name="csrfmiddlewaretoken" value=" some long stuff" > <input type="text" name="name" required id="id_name" maxlength="100> </form> -
How to get PDF output to look exactly like HTML output
I am trying to create a PDF for my client to start invoicing their clients. I've dealt with creating PDFs in the past and remember it was a huge pain to create them. In my Django application, I have two view functions, one that just renders a template that I am using to design the invoice, and another that converts it into a pdf and renders the PDF as well. I have two tabs open side by side one that points to each version template HTML vs. PDF and they look completely different. Is there a special Markup language I have to use to create PDFs, or is their a python package out their that converts HTML to an exact replica of that HTML in PDF ? View Functions from django.shortcuts import render, HttpResponse from django.template.loader import get_template from io import BytesIO from xhtml2pdf import pisa def generate_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render({}) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def ronin(request): template = get_template('ronin.html') context = {} html = template.render(context) pdf = generate_pdf('ronin.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") content = "inline; filename='%s'" … -
what is the equivalent for assertDatabaseHas in Django
Coming from Laravel background learning Django. Forgive me if my question is naive. response = self.client.delete(reverse('details'), kwargs={'pk':pk}, format="json") self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) The above test passes, and I would like to go a little further and try to check if the database actually has this item, of course I can query the db and try to match the count. But in Laravel I have used these methods to check for the existence/nonexistence of records. assertDatabaseHas('users', ['id' => 10]); //asserts true if record is present in users table. assertDatabaseMissing('users', ['id' => 10]); // asserts true if record is not present in users table Is there something similar present in Django? -
Retrieving access token from database
I'm attempting to create a client server which will make calls to a resource server (i.e. Google, Facebook) to retrieve an access token for a user. I'm assuming that this token shouldn't be given to the user, but I'm confused as to how I'm supposed to save this token so that when the user needs to make an API call, the token can be retrieved. I'm trying to construct a Django server to do this. As of right now, I'm up to the point where I'm able to retrieve an access token from the resource server. However, I don't know what to do with it -- I don't know how to save it so that the user can access it again. I've tried reading up on this but it's been confusing for me to understand. I'm new to Django/OAuth2, any help would be greatly appreciated! -
When I put in pip --version into the terminal I get this error: "The 'pip==9.0.1' distribution was not found and is required by the application"
Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3095, in @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3081, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3108, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 658, in _build_master ws.require(requires) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 959, in require needed = self.resolve(parse_requirements(requirements)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 846, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application -
How do I make a Django filter with dropdown?
I have the following chained models: class Faculty(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Faculties' def __str__(self): return self.name class Department(models.Model): faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Meta: verbose_name = "Study Programme" verbose_name_plural = 'Study Programmes' def __str__(self): return self.name class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) I want to make to have a dropdown for faculty, and then when a faculty is selected a department can be selected from that faculty, and after that a study programme can be selected from that department and all courses specific to that study programme to be displayed. How can I achieve this ? -
Get common instance from two ManyToMany field in Django
class Category(models.Model): name = models.CharField(max_length=100) class UserProfile(models.Model): name = models.CharField(max_length=100) tags_liked = models.ManyToManyField(Category, related_name='liked_by') class Product(models.Model): name = models.CharField(max_length=100) product_tag = models.ManyToManyField(Category, related_name="products") How to find all the 'Category' instance that shares atleast one common field between 'UserProfile' and 'Product'? I will use it to recommended products to user. -
Online store on python. How to adjust the price of goods depending on the currency?
Just started writing on the python. I'm writing an online store. I have a "Category of goods" class. The child class "products", which indicates the price and all other attributes. I want that in the admin set the exchange rate and prices changed automatically. How can this be realized? Thanks for any help. -
django - combine the output of json views
I write a simple json api, I use one base class, and I mostly write one api view per one model class. What I want is to combine the output of few views into one url endpoint, with as least as possible additional code. code: # base class class JsonView(View): def get(self, request): return JsonResponse(self.get_json()) def get_json(self): return {} class DerivedView(JsonView): param = None def get_json(self): # .. use param.. return {'data': []} urls.py: url('/endpoint1', DerivedView.as_view(param=1)) url('/endpoint2', DerivedView2.as_view()) # What I want: url('/combined', combine_json_views({ 'output1': DerivedView.as_view(param=1), 'output2': DerivedView2.as_view() })) So /combined would give me the following json response: {'output1': {'data': []}, 'output2': output of DerivedView2} This is how combine_json_views could be implemented: def combine_json_views(views_dict): d = {} for key, view in views_dict.items(): d[key] = view() # The problem is here return json.dumps(d) The problem is that calling view() give me the encoded json, so calling json.dumps again gives invalid json. I could call json.loads(view()), but that looks bad to decode the json that I just encoded. How can I modify the code (maybe a better base class) here, while keeping it elegant and short? without adding too much code. Is there any way to access the data (dict) which is … -
How to order readonly M2M fields in django admin
I can't seem to work out how to hook into the queryset of a readonly field in Django admin. In particular I want to do this for an inline admin. # models.py class Value(models.Model): name = models.TextField() class AnotherModel(models.Model): values = models.ManyToMany(Value) class Model(models.Model): another_model = models.ForeignKey(AnotherModel) # admin.py class AnotherModelInline(admin.TabularInline): # How do I order values by 'name'? readonly_fields = ('values',) class ModelAdmin(admin.ModelAdmin): inlines = (AnotherModelInline,) Note that this could probably be done by overriding the form and then setting the widget to disabled, but that's a bit of a hack and doesn't look nice (I don't want greyed out multi-select, but a comma-separated list of words. -
How to randomise the order of a queryset
Consider the following query: candidates = Candidate.objects.filter(ElectionID=ElectionIDx) Objects in this query are ordered by their id field. How do I randomise the order of the objects in the query? Can it be done using .order_by()? -
Django datetime comparison not working as expected in save
I have a custom save routine in one of my models that compares datetime fields and then is supposed to modify a field on another model and save it based on the results. However, the comparison is not working as I would expect it to. Namely, my <= comparison is returning True regardless of the actual comparison. models.py class Session(models.Model): date = models.DateField() # etc... class Case(models.Model): summary = models.TextField(blank=True) session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='cases') case_type = models.ForeignKey(CaseType) # etc... class Person(models.Model): earliest_case = models.ForeignKey('Case', null=True, blank=True, related_name='person_to_earliest_case+') latest_case = models.ForeignKey('Case', null=True, blank=True, related_name='person_to_latest_case+') # etc... class Litigant(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='person_to_case') case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='case_to_person') # etc... def save(self, *args, **kwargs): try: person = Person.objects.get(id=self.person_id) earliest_case = person.earliest_case latest_case = person.latest_case if self.case.session.date <= earliest_case.session.date: person.earliest_case = self.case person.save() elif self.case.session.date >= latest_case.session.date: person.earliest_case = self.case person.save() except: pass super(Litigant, self).save(*args, **kwargs) As you can see, when I save a new Litigant, what I want it to do is call up the existing Person instance, compare that instance's entries for earliest_case and latest_case with the new Case instance tied to Litigant and then reassign the fields if necessary. What is happen instead is that the new case … -
How do I filter/search my items from a model dependent on other models, by using dropdown choice fields ?
I have 4 models dependent on each other, related by foreign keys: Faculty > Department > StudyProgramme > Course. I have a page where all my courses are displayed and paginated, and on it's left I want to implement a filter with dropdowns, that will let you choose a faculty, then choose a department of the faculty, then choose a study programme of the department and display the specific courses. Also, I want to able to search for a course by just it's name. The results then would replace all courses and of course have pagination as well. I don't want to use any high-level tools that I would not understand or Ajax, I just want to use plain Django if possible. Can someone advice or point me to something similar to what I want to achieve ? I learn by example. Here is the code so far: def index(request): course_list = Course.objects.all() paginator = Paginator(course_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> … -
How to set limit on models in Django
I have a little problem. I want to set the limit for users in my app. For example: The new user after register and login to his account can add only one record. After added if this same user want to add next record, the app will return the alert "You are permited to add only one record". How to solve it? -
Django LiveServerTestCase with SQLite3
I am using LiveServerTestCase for functional tests with selenium in a Django app. I am using sqlite3 as a backend for local development, and I'm running the tests with a local development server on port 8081. I wrote a test for user registration, and when I run this test more than once, I see that the test fails because my form throws an error saying the user already exists. When I delete the sqlite3 database file, I can run the test again and it works fine (but running again will fail). I thought that this class would use a new database each time a test within the class was run, but I am getting errors. My question is: Is there another way to run the tests with LiveServerTestCase so that I don't have to delete the sqlite3 database each time I want to run the test? -
Form not Displaying in Django 1.8
I am making a form using Django 1.8 and Python 3.5 But the form is not showing up,IDK why ? This are my files respectivel urlpatterns = [ url(r'^login', 'login.views.login', name='login'), url(r'^admin/', include(admin.site.urls)), ] + static(settings.STATIC_URL , document_root=settings.STATIC_ROOT) login/view.py== from django.shortcuts import render from .forms import allusers1 # Create your views here. def login(request): form1=allusers1() context = { "form1": form1 } return render(request, "login.html",context) login/forms.py== from django import forms from .models import allusers1 class signupform(forms.ModelForm): class Meta: model = allusers1 fields = ['name','phoneno'] login/models.py from django.db import models # Create your models here. class allusers1(models.Model): name=models.CharField(max_length=400) phoneno=models.CharField(max_length=10) otp=models.IntegerField() # def __str__(self): # return self.name login.html {{form1}} output allusers1 object But output should have been Name and ,Email fields for input WHAT IS THE ERROR ? -
How do I get django static files actually styling in Kubernetes?
This is my deployment for the django app with rest framework: #Deployment apiVersion: extensions/v1beta1 kind: Deployment metadata: labels: service: my-api-service e name: my-api-deployment spec: replicas: 1 template: metadata: labels: name: my-api-selector spec: containers: - name: nginx image: nginx command: [nginx, -g,'daemon off;'] imagePullPolicy: IfNotPresent volumeMounts: - name: shared-disk mountPath: /static readOnly: true - name: nginx-config mountPath: /etc/nginx/nginx.conf subPath: nginx.conf ports: - name: nginx containerPort: 80 - env: - name: STATIC_ROOT value: /src/static/ - name: MEDIA_ROOT value: /src/media/ - name: CLIENT_ORIGIN value: https://marketforce.platinumcredit.co.ke - name: DJANGO_SETTINGS_MODULE value: config.production - name: DEBUG value: "true" image: localhost:5000/workforce-api:0.2.0 command: [ "./entrypoint.sh" ] name: my-api-container imagePullPolicy: IfNotPresent ports: - name: my-api-port containerPort: 9000 protocol: TCP volumeMounts: - name: shared-disk mountPath: /src/static initContainers: - name: assets image: localhost:5000/workforce-api:0.2.0 command: [bash, -c] args: ["python manage.py collectstatic --noinput"] command: [bash, -c] args: ["sleep 10"] command: [bash, -c] args: ["cp -r static/* /data"] imagePullPolicy: IfNotPresent volumeMounts: - mountPath: /data name: shared-disk volumes: - name: shared-disk emptyDir: {} - name: nginx-config configMap: name: nginx-config My service: # Service apiVersion: v1 kind: Service metadata: name: my-api-service labels: label: my-api-service spec: type: NodePort ports: - port: 80 targetPort: 80 protocol: TCP name: http selector: name: my-api-selector And here's my nginx configuration: apiVersion: …