Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invalid literal for int() with base 10: 'N/A' Django
I'm new to Django. I followed this tutorial to create a web interface with a MySQL database. The following is my model code: from django.db import models from django.contrib.auth.models import User # Create your models here. class Strain(models.Model): """; Model representing strains. """ strain_name = models.CharField(max_length=100, blank=False, null=True, default=None) data_of_generation = models.DateField(null=True, blank=True, default= None) submitter = models.ForeignKey(User,null=True, blank = False, on_delete= models.CASCADE, default= None) class Meta: ordering = ["strain_name"] def get_absolute_url(self): """ Returns the url to access a particular author instance. """ return reverse('strain-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '{0}'.format(self.strain_name) class Plasmid(models.Model): """; Model representing an Plasmid Database. """ plasmid_name = models.CharField(max_length=35, blank=False) data_of_generation = models.DateField(null=True, blank=True, default= None) restriction_sites = models.CharField(max_length=100, blank=False, null=True) host_strain = models.ForeignKey(Strain, null=True, blank = True, on_delete= models.CASCADE, default= None) class Meta: ordering = ["plasmid_name"] def get_absolute_url(self): """ Returns the url to access a particular author instance. """ return reverse('plasmid-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '{0}'.format(self.plasmid_name) When I first wrote the code, I accidentally wrote 'N/A' for the default option of variable host_strain. When I tried to migrate the changes, I got this error: "ValueError: invalid literal for int() with … -
Extend django permissions for specific group of users
I have two models: class Coach(User): name = models.CharField() email = models.EmailField() branding = models.CharField(choices=BRANDINGS) class Patient(User): name = models.CharField() email = models.EmailField() branding = models.CharField(choices=BRANDINGS) Is there any way to allow coaches see patients only of their branding? I think writing filter queryset on each view is a bad idea. Mayby it can be done by changing permissions? -
My Line Graph is only showing 7 points on the webpage by chart.js
So I am plotting a line graph on a django project through chart.js. The problem which I am facing is, I have more than 3000 points on Y axis, and 7 points on X Axis orignally. But the web page is only showing 7 points on Y axis. Due to this my Web page looks something like this: Webpage Image My HTML file responsible for plotting the graph is given below: <script> var speedCanvas = document.getElementById("speedChart"); Chart.defaults.global.defaultFontFamily = "Lato"; Chart.defaults.global.defaultFontSize = 18; data1 = {{Forecast}}; var dataFirst = { label: "Forecast", data: data1, lineTension: 0.3, fill: true, borderColor: 'red', backgroundColor: 'transparent', pointBorderColor: 'red', pointBackgroundColor: 'lightgreen', pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 30, pointBorderWidth: 2, pointStyle: 'rect' }; var dataSecond = { label: "Old Values", data: {{AdjClose}}, lineTension: 0.3, fill: true, borderColor: 'purple', backgroundColor: 'transparent', pointBorderColor: 'purple', pointBackgroundColor: 'lightgreen', pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 30, pointBorderWidth: 2 }; var speedData = { labels: ["2005","2007","2009","2011","2013","2015"], datasets: [dataFirst, dataSecond] }; var chartOptions = { legend: { display: true, position: 'top', labels: { boxWidth: 80, fontColor: 'black' } }, scales: { xAxes: [{ afterTickToLabelConversion: function(data){ var xLabels = data.ticks; xLabels.forEach(function (labels, i) { if (i % 2 == 1){ xLabels[i] = ''; } }); } … -
Have Gitlab CI/CD use different PostgreSQL server than local development?
I've just set up my Python and Django project on Gitlab. Now when I make a commit and push it to Gitlab, it automatically runs my unit tests which is a good thing. The problem is that to get it to work; I have to set my database host in Django to "postgres" which obviously won't work. I want my local development environment to use 127.0.0.1 and the Gitlab environment to use "postgres", but I'm not sure how to go about and do that. Here is my Gitlab configuration file: https://gitlab.com/glamorous-systems/seductive/blob/master/.gitlab-ci.yml Any help would be much appreciated. It took me quite awhile to get things working as I wanted them so if I can solve this problem I think everything will work out quite nicely. -
Django: Add foreign key in same model but different class
I'm new to Django. How to add foreign key in same Model of different class? from django.db import models class Student(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=200) class Player(models.Model): student = models.ForeignKey( self.Student, #? on_delete = models.CASCADE, ) sports_name = models.CharField(max_length=20) -
Using Gmail for Django email backend
I've just made a Gsuite account which I intended to use for my email backend for my Django site which is in production - however I read here that: Gmail is not recommended for a production project (live web application) because gmail is not a transactional email service Can someone tell me if this is true, and if so why? What alternatives are there? Edit: The use-case of the emails for my app is for verifying user signups - and yes this could be a very large number. -
Where is settings.py in django-cms?
django-cms is a django project itself. So there must be a file called settings.py But I couldn't find it, where it is? how is database connection taking place? -
What is the correct way to deploy more than one Django project on the same server?
I am using Django Cookiecutter and i would like to deploy three projects on production (via Docker). Let's assume that it should work like this: service-a.mydomain.com service-b.mydomain.com service-c.mydomain.com Could you please explain me how should i do it correctly? Thank you -
heroku deploy error with static root path django. static_root not set to file system path
my static files settings are improperly configured according to heroku when I attempt to deploy. I am without doubt this is false as I still lack understanding of the proper way to set up static files. I have ran collect static on my machine and it did work. I will provide the information my ask is to help me clear this up. I am going to continue to research and hope to come with a solution. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #angular distro root ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist') STATICFILES_DIRS = [ os.path.join(ANGULAR_APP_DIR), ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' -
Add primary key on upload of source file in django-import-export
I am using django-import-export to import data from csv/excel sheets into my models. This is my code: models.py class Client(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name admin.py class ClientResource(resources.ModelResource): class Meta: model = Client @admin.register(Client) class ClientAdmin(ImportExportModelAdmin): resource_class = ClientResource On upload however, I get an error that states: File "\venv\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' From what I understand, this is because my excel sheet doesn't carry the id field which is the primary key field. Is there a way that I can make the resource create an id on upload of each instance of Client? -
Cant get images to convert to pdf using xhtml2pdf (url of file returning errror)
Here is a supposed solution I have found. https://stackoverflow.com/a/2180417 I am trying to implement it but I am not able to do so. Here is my current code: utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def fetch_resources(uri, rel): path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path views.py from django.http import HttpResponse from django.views.generic import View from yourproject.utils import render_to_pdf #created in step 4 class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('pdf/invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') -
How to declare a Factory attribute that is an attribute of a RelatedFactory
class ValuationFactory(BEFactory): loan = factory.RelatedFactory(LoanApplicationFactory, 'valuation') security = factory.SelfAttribute('loan.security') This raises AttributeError: The parameter 'loan' is unknown. It works when loan is a SubFactory but loan has a foreign key relation back to the Valuation so I end with with infinite recursion if I try that. It seems like RelatedFactory is bound quite late and I can't even access it from @factory.post_generation methods safely because the factory tries to save to the database before the create phase and generates a database IntegrityError because security_id is null. I don't know if I can bind attributes in the build phase. Are there other techniques that would work? -
Django: Create a Custom 404 View for ONE Specific Generic View
Note: I don't mean changing the handler404 for the entire project. I only want to override the 404 response for one specific generic view. For instance, when users visits this specific view, if 404 occurs, they will be shown a special 404 page. For any other views, the 404 response remains default. -
get id from url parametrs (not from request)
How to get id from url parametrs in django function get_queryset. Not from get request i have url like so http://127.0.0.1:8000/17/ url(r'^(?P<pk>\d+)/$', views.NodesDetailView.as_view(), name='nodes_detail') view def get_queryset(self): node_id = self.request. -
Deploying Django with Puppet and Nginx
I'm trying to deploy a django application with puppet and nginx, but I'm having trouble figuring out how to configure nginx to serve static files while Gunicorn is running. Current I have nginx::resource::server { $site_name: listen_port => 80, proxy => 'http://localhost:8000', } nginx::resource::location{'/static/': server => $site_name, location_alias => "/home/git/${site_name}_django/static/", } So that anything that doesn't go to /static/ gets rerouted to the gunicorn process (which is running as daemon). But when I try to access the static files, it has django return a 404 error. How can I get the static files to properly be served? -
Unknown field `edges` on type `Query`
I am getting the error from the title when I attempt to run relay-compiler in my project. I am using graphql-python/graphene-django for the back end graphql server. Here's an abbreviated copy of my schema. grove.gql_schema.py: from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Tree class TreeNode(DjangoObjectType): class Meta: model = Tree filter_fields = ['owner'] interfaces = (relay.Node,) class Query(ObjectType): def resolve_my_trees(self, info): if not info.context.user.is_authenticated: return Tree.objects.none() else: return Tree.objects.filter(owner=info.context.user) my_trees = DjangoFilterConnectionField(TreeNode) tree = relay.Node.Field(TreeNode) project.gql_schema: class Query(grove.gql_schema.Query, graphene.ObjectType): pass schema = graphene.Schema(query=Query) With that setup, I can successfully run the following query in GraphiQL query { myTrees { edges { node { id } } } } So far so good, but now I'm trying to build a client-side component that can use this query. jsapp/components/index.jsx: import React from 'react'; import {graphql, QueryRenderer} from 'react-relay'; import environment from '../relay_env' const myTreesQuery = graphql` query componentsMyTreesQuery { edges { node { id } } } `; export default class App extends React.Component { render() { return ( <QueryRenderer environment={environment} query={myTreesQuery} variables={{}} render={({error, props}) => { if (error) { return <div>Error!</div>; } if (!props) { return <div>Loading...</div>; } return <div>User ID: {props.edges}</div>; }} /> ); } } … -
Passing value along with form in POST data in Django
When I render the form in HTML, I use this view. the patient_id is used to denote what patient the check in is for and for name display and such. def Checkin(request, patient_id): patient = get_object_or_404(PatientInfo, pk=patient_id) form = forms.PatientCheckinForm() return render(request, 'patientRecords/checkin.html', {'patient': patient, 'form':form}) When I submit the patient form filled out as a POST method, I still need access to the patient_id. Currently this is the view that accepts the filled form: def CheckinSubmit(request): if request.method == 'POST': form = forms.PatientCheckinForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.date_time_of_checkin = dt.now() instance.patient = patient.patient_id instance.save() return redirect('patientRecords/index.html') I want to set the instance.patient to the patient_id that was part of patient from the Checkin view. Is there a way to pass the patient data back along with the POST method or is there another way this can be done? For reference, here is my template and I am using ModelForm not form. {% block content %} <div class="container"> <h1>Patient Checkin</h1> <h2>{{patient.first_name}} {{patient.last_name}}</h2> </div> <div class="container"> <form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> </div> {% endblock %} Thanks in advance! -
using browser-sync with django on docker-composer
I'm doing a project for college and I've never used docker before, I usually use browser-sync when working on static files, but now when I'm using Django on docker-compose (i followed THIS tutorial ), I have no idea how to set it up to work, can anybody give me advice or direct me? -
generics vs viewset in django rest framework, how to prefer which one to use?
How to prefer which one of generics and viewset to use? in other words when should I use generics and when should i use viewset for building api. I know that it does the same thing, but viewset has routers, so in what situation generics is better then viewset? -
Django identify object through form
I am making a web page wich has a list of objects, and each object has a button to delete it. I am making this with Django forms, but once I make the post I cannot identify from which object it came from. How do I do that? This is my html code: <ul> {% for item in item_list %} <li> <form name="{{ item.nombre }}" method="POST" action="/inventario/"> {% csrf_token %} <input type="submit" name="del_item" value="x"> {{ item.nombre }}: {{ item.cantidad }} </form> </li> {% endfor %} </ul> -
Django vs Mithril url routing
I am using routing via Mithril. When I route to mysite.com/subpage/item3 via javascript, the static file '/static/app.bundle.js' remains loaded and the subpage html is shown, as expected. m.route(document.body, "/", { "/": Home, "/subpage": Subpage, "/subpage/:focus": Subpage, "/:focus": Home }); However, when I navigate to mysite.com/subpage/item3 from initial page load, Django kicks in and attempts to load the static file from '/subpage/static/app.bundle.js' instead. This results in a 404 error. I have set STATIC_URL and STATICFILES_DIRS, and I don't understand why Django is changing them. Here's my url pattern: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('<url>', views.index, name='index'), path('<url>/<suburl>', views.index, name='index') ] Here's my static file settings: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) Thank you! -
Django - adding user authentication to request.META
I' working on a Django project and to create some graphs using Graphs.js I'm using a class inheriting from the REST Framework's APIView, just like it was explained in https://www.youtube.com/watch?v=B4Vmm3yZPgc. The code for this: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): user = User.objects.get(user=request.user) gross_and_nets = GrossAndNet.objects.filter(user=user) years = [] gross_values = [] net_values = [] for gn in gross_and_nets: years.append(gn.get_year()) gross_values.append(gn.get_gross()) net_values.append(gn.get_net()) data = { "labels": years, "gross_values": gross_values, "net_values": net_values, } return Response(data) My issue is that I'm using a custom user model and the request.user in the get method of ChartData outputs AnonymousUser. Consequently, I followed the instructions in the 'Custom Authentication' section from http://www.django-rest-framework.org/api-guide/authentication/, and realised that I don't have any username header in request.META. Thus, in def authenticate(self, request): username = request.META.get('X_EMAIL') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) I don't have any header to retrieve the user's email, which is the primary identifier. To this I've tried adding a header in the main View's get method like: class KPIDemoView(LoginRequiredMixin, TemplateView): template_name = 'demo_view.html' def get_context_data(self, *args, **kwargs): context = super(KPIDemoView, self).get_context_data(*args, **kwargs) full_context = try_get_context(context, self.request.user) return full_context … -
django url patterns error , id not passed to view.
i try to create rest api, but got stuck on generating url. urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/shop/', include(('shop.api.urls', 'shop'), namespace='api-shop',)), ] also tried as path('api/shop/', include(('shop.api.urls', 'shop'), namespace='api-shop',)), in shop/api/urls.py i wrote urlpatterns = [ url(r'^(P<id>\d+)/$', ShopRudView.as_view(), name='shop-rud') ] and in shop/api/views.py i using drf library generics views to create class ShopRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'id' serializer_class = ShopSerializer def get_queryset(self): return Shop.objects.all() and when I enter http://127.0.0.1:8000/api/shop/1 i get ing the URLconf defined in untitled1.urls, Django tried these URL patterns, in this order: admin/ shop/ ^api/shop/ ^(P\d+)/$ [name='shop-rud'] The current path, api/shop/1, didn't match any of these. How to fix that? -
Model.ManyToManyField.all() gives AttributeError: 'ManyToManyDescriptor' object has no attribute 'all'
I'm using Django 2.0.2, Python 3.6.4 and PyCharm 2017.3.3 Models: (in models.py) class Position(models.Model): title = models.CharField(max_length=50) gang = models.ForeignKey(Gang, on_delete=models.CASCADE) description = models.TextField(max_length=20000) def __str__(self): return str(self.title) + ', ' + str(self.gang) class Application(models.Model): positions = models.ManyToManyField(Position) applicant = models.ForeignKey(User, on_delete=models.CASCADE) class Ranking(models.Model): position = models.ForeignKey(Position, on_delete=models.CASCADE) applicant = models.ForeignKey(User, on_delete=models.CASCADE) rank = models.IntegerField(default=3,validators=[ MaxValueValidator(3), MinValueValidator(1) ]) Form: (in forms.py) class RankingForm(forms.ModelForm): rank = forms.IntegerField(max_value=3, min_value=1) position = forms.ModelMultipleChoiceField(queryset=Application.positions.all()) class Meta: model = Ranking exclude = ['applicant'] fields = ('rank', 'position') def __init__(self, *args, **kwargs): super(RankingForm, self).__init__(*args, **kwargs) self.fields['rank'].widget.attrs.update({'class': 'form-control'}) I keep getting the AttributeError in RankingForm from "position = forms.ModelMultipleChoiceField(queryset=Application.positions.all())" When i write class Application(models.Model): ... def __str__(self): return str(self.positions.all()) it shows in django-admin as a QuerySet (which works for forms.ModelMultipleChoiceField()), but writing class Application(models.Model): ... def __str__(self): return str(Application.positions.all()) gives me the same error: 'ManyToManyDescriptor' object has no attribute 'all' Writing class RankingForm(forms.ModelForm): ... position = forms.ModelMultipleChoiceField(queryset=Position.objects.all()) works, but this is not what i want the field to display. I want to make a ModelMultipleChoiceField() with all the positions from a specific application, but this error keeps getting in the way. It seems that just referencing a model doesn't work, but referencing self does?? Any help is … -
Change field names in a Django query
I have several Django queries which I need to combine with .union(). But .union() works only if all the fields names are the same, what is not the case. So, how to modify field names in Django queries (like using AS keyword in SQL)?