Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a good data model diagram for Saleor E-Commerce?
I've begun working with Saleor Django E-Commerce. Is there a data model diagram available? -
Can i use django-hitcount with puput?
I am using Django-puput as a blog app, and I have been looking around all day trying to figure out how to use django-hitcount with it. Puput uses Wagtail as a CMS and it has 1 view which is responsible with the page serve, but adding the hitcount mixin there doesn't seem to work. I don't need to use django-hitcount, but any solution that can show hit counts is ok. Any help would be appreciated. -
Equivalent of git checkout -b new_branch in GitPython
I'm building a Django application which makes heavy use of Git and therefore using GitPython. My question is relatively simple, but often, I've been unable to find good and clear instructions in the documentation, and I couldn't find any other answer here which answers my question. I apologize in advance if this is a duplicate. Question: What is the most appropriate way of creating a new branch and pushing it back to a remote? What I'm doing currently trying to do in a function is: def create_new_branch(self, branch_name): self._repo.remotes.origin.fetch() self._repo.active_branch.checkout(b=branch_name) self._repo.remotes.origin.push() With this approach, when I try to create a new branch called '1234test' I get the error message: cmdline: git push --porcelain origin stderr: 'fatal: The current branch 1234test has no upstream branch. To push the current branch and set the remote as upstream, use git push --set-upstream origin 1234test So, I guess my question is "how do I set the upstream for the new branch?". I know how to set it to master, but since this branch is newly created, I'm not sure how to do it in this case. I know that I could just change the Git configuration not to require setting an upstream anymore, but … -
DigitalOcean add domain to django instance with nginx and gunicorn
I've setup the one click install django on digitalocean and added a domain to it. I'm also trying to add a sub domain before the site goes live. I've edited the nginx conf file as below server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name beta.kazi-connect.com; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } and restarted both nginx and gunicorn however when I visit the sub domain I get a 502 bad gateway error. Nginx log states there's an issue with gunicorn. 2017/01/24 16:24:19 [error] 6258#6258: *2 upstream prematurely closed connection while reading response header from upstream, client: 105.230.203.101, server: beta.kazi-connect.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "beta.kazi-connect.com" 2017/01/24 16:24:20 [error] 6258#6258: *2 upstream prematurely closed connection while reading response header from upstream, client: 105.230.203.101, … -
Django postgres order_by distinct on field
We have a limitation for order_by/distinct fields. From the docs: "fields in order_by() must start with the fields in distinct(), in the same order" Now here is the use case: class Course(models.Model): is_vip = models.BooleanField() ... class CourseEvent(models.Model): date = models.DateTimeField() course = models.ForeignKey(Course) The goal is to fetch the courses, ordered by nearest date but vip goes first. The solution could look like this: CourseEvent.objects.order_by('-course__is_vip', '-date',).distinct('course_id',) But it causes an error since the limitation. Yeah I understand why ordering is necessary when using distinct - we get the first row for each value of course_id so if we don't specify an order we would get some arbitrary row. But what's the purpose of limiting order to the same field that we have distinct on? If I change order_by to something like ('course_id', '-course__is_vip', '-date',) it would give me one row for course but the order of courses will have nothing in common with the goal. Is there any way to bypass this limitation besides walking through the entire queryset and filtering it in a loop? -
Django MPTTModel load all children
I am working on employee hierarchy. Employee model is of type MPTTModel. I want to get Employees with id 10 and 11, and all their direct children employees in one SQL query. Is that possible? Model: class Employee(MPTTModel): supervisor = TreeForeignKey( 'self', null=True, blank=True, related_name='employees', db_index=True, verbose_name='Supervisor' ) MPTTModel has nice getChildren() function, however is is usable only for single employee model (which is not my case). I would like to have something like this: Employee.objects.filter(id=10).filter(id=11).prefetch_related('children').get_children() #code above is not not working -
django Is there a way to get a reversed url without passing parameters?
I am using ajax data to pass info to my page, but I need to create some links that use data from the javascript to call a view, so the parameters usually passed when one does a {% url 'jobs:close' foo %}, for example, are not available at the time the template is rendered, but imported later through an ajax call. Obviously, this causes errors when the template is rendered. Is there a way to keep the benefit of having reverse url lookups in such a situation, and dynamically get the URL in the template without passing foo, or do I need to hard code the URL in the template and paste the parameter on the end later? -
Is there a way to mass upload products to Saleor E-Commerce
I'm starting out with django Saleor. Is there a way to mass upload a list of products from a csv file? If not can someone suggest which classes to call to build one? Thanks. -
Accessing HTML form element inside a Django template {% url %}
I have a Django HTML template with <form method="get" action="{% url 'handler_name' parameter %}">. I wanted to replace the parameter with a form field's value. Does Django has any provisions for that? urls.py ... url(r'^sample-endpoint/$', view_function_1, name='endpoint1'), url(r'^sample-endpoint/(\d+)/$', view_function_1, name='endpoint2'), ... The first one sample-endpoint/ is hit when the page loads for the first time. The page has an input (a number). On selecting a number, and clicking a button, the second one, say sample-endpoint/1/ gets called and the same page gets rendered with some additional data. catalog.html <form id='get-list' name='get_list_form' method='get' action='{% url "endpoint2" placeholder %}'> {% csrf_token %} <select id='select-catalog-id' name='catalog_id'> <option value='1'>Foo</option> <option value='2'>Bar</option> </select> </form> I don't want to fetch the value on the server side in views.py using request.GET['catalog_id']. I feel having two URLs looks clean. And moreover, both URLs are for GET request. My objective is to use the value of selected item in the dropdown (1 or 2, in this case) instead of placeholder in the form action. Is it provided out of the box in Django? Or some custom JavaScript? -
Django: Cross Site Request Forgery protection doesn't work when using with S3, Cloudfront
I manage static files, including js files, using AWS S3 and AWS CloudFront. I have a code sending ajax POST request (to one of my django view) and this a.js file is located in S3. I realized that I'm faced with sort of cross domain issues, so I copied and pasted some codes in https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax. Here is my js code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: "POST", url: '/orders/pay-check/', data: { imp_uid : rsp.imp_uid, merchant_uid : rsp.merchant_uid }, // form date가 아니기 때문에, 맨위에 ajax cookie 세팅을 해줘야함 success: function(data) { ... } }); But it occurs csrf_token missing errors! So I looked this code … -
Trigger a delete when inserting a new entry on django
I'm learning to code on django and I would like to do something like this: I have a table called "request" in which the user inserts a request. When this request is fulfilled, another user inserts an entry on "assignation". What I want to do is to make the model to delete that specific entry from request when it's fulfilled with an assignation. I've read a little bit about signals on django so I think I'd have to use that but I'm not sure how it's supposed to be done. Thanks -
Django Rest Framework Self-Describing API as PDF
I have a Django Rest Framework API with a fair amount of self-describing documentation built in. I'd like to convert this to a PDF (or some other portable document) to send to clients. What is the best approach? -
MultiValueDictKeyError In Django ModelForm
This error that I am getting is very weird. I have a form: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'description', 'gender', 'language', ] widgets = { 'language': forms.RadioSelect, } So as you can see, the language is using the Radio button method. Then in my models.py, I specify the field for the languages like so: LANGUAGE = (('AR', 'Arabic'), ('FR', 'French'), ('ES', 'Spanish')) language = models.CharField(max_length=20, choices=LANGUAGE, blank=False, default=None) Then in my views.py, I have something like this: if request.method == "POST": # Model first_name = request.POST['first_name'] last_name = request.POST['last_name'] gender = request.POST['gender'] language = request.POST['language'] Profile.objects.create( first_name=first_name, last_name=last_name, description=description, gender=gender, language=language, ) So for the form, if I select an entry for language, then it all works fine and dandy. However, if I leave the language field empty (I don't select anything), it gives me MultiValueDictKeyError. Here is the traceback: Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/andyxu/Documents/ece496-web/matchalgorithm/views.py" in forms 31. language = request.POST['language'] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__ 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /matchalgorithm/forms/ Exception Value: "'language'" -
django how to retrieve 3 fields from a diferent model
there i have 3 models linked to cheader, and i need to display data from the 3 models in a template a don't have any idea how to do it models class Componente(models.Model): Aviacion = 'AV.' Ejercito = 'EJ.' GuardiaNacional = 'GN.' Armada = 'AR.' OP_COMPONENTE = ( (Aviacion, 'Aviacion'), (Ejercito, 'Ejercito'), (GuardiaNacional, 'Guardia Nacional'), (Armada, 'Armada'), ) componente = models.CharField( max_length=3, choices=OP_COMPONENTE,) def __str__(self): return self.componente class Rango(models.Model): OP_RANGO = ( ('G/F.', 'General en Jefe'), ('G/D.', 'General de Divicion'), ('VA.', 'Vicealmirante'), ('CA.', 'Contralmirante'), ) componente = models.ForeignKey(Componente) rango = models.CharField( max_length=6, choices=OP_RANGO ) def __str__(self): return self.rango class Militar (models.Model): autor = models.ForeignKey('auth.User') nombre = models.CharField(max_length=250) componente = models.ForeignKey(Componente) rango = ChainedForeignKey( Rango, chained_field="componente", chained_model_field="componente", show_all=False, auto_choose=True, sort=True, ) imagen = models.ImageField(upload_to='militares') fecha_creacion = models.DateTimeField(default=timezone.now) fecha_publicacion = models.DateTimeField(blank=True, null=True) def __str__(self): return self.nombre class Meta: verbose_name = 'Oficial' verbose_name_plural = 'Oficial' class Sucursal (models.Model): OP_CIUDAD = ( ('Caracas', 'Caracas'), ('Apure', 'Apure'), ('Barcelona', 'Barcelona'), ) autor = models.ForeignKey('auth.User') ciudad = models.CharField( max_length=60, choices=OP_CIUDAD ) director = models.ForeignKey(Militar) correo = models.EmailField(max_length=250) phone_regrex = RegexValidator( regex=r'^(\d{4})-(\d{3}).(\d{2}).(\d{2})') telefono = models.CharField(validators=[phone_regrex], blank=True, max_length=16) direccion = models.CharField(max_length=250) horario = models.CharField(max_length=250) fecha_creacion = models.DateTimeField(default=timezone.now) fecha_publicacion = models.DateTimeField(blank=True, null=True) def __str__(self): return self.ciudad class Meta: verbose_name = … -
Verify Bitcoin transfer from one address to another address in Django
I have a websites which provides a selling platform for individuals. Each individual registers with his bitcoin address and has to input his transaction ID after each transaction. My code - import urllib import re urlr = "https://blockchain.info/q/txresult/"+hash+"/"+receiver.bitcoin_account urls = "https://blockchain.info/q/txresult/"+hash+"/"+sender.bitcoin_account try: res = urllib.urlopen(urls) resread = res.read() sen = urllib.urlopen(urlr) senread = sen.read() except IOError: resread = "" senread = "" try: resread = int(resread) senread = int(senread) if resread >= 5000000 and senread != 0: ... Please i need a better solution, if i can get -
Setting translation language_code for session not working
I'm trying to allow visitors to my site to set the language of the landing page (the language of the rest of the app is set after login based on a parameter in the user's profile). This approach is not working: urls.py (the homepage has links to /translate/fr/, /translate/de/ etc: url(r'^translate/(?P<language_code>[A-Za-z]{2})/$', SetLanguage.as_view(), name="set-language") views.py from django.views.generic RedirectView from django.utils import translation class SetLanguage(RedirectView): def dispatch(self, request, *args, **kwargs): language_code = self.kwargs.get('language_code', 'en') #set language, with english as default request.session[translation.LANGUAGE_SESSION_KEY] = language_code; translation.activate(language_code) return super(SetLanguage, self).dispatch(request, *args, **kwargs) def get_redirect_url(self, *args, **kwargs): # redirect to homepage root url return '/' settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', ... Setting the session language like in dispatch works that way once the user is logged in. Why doesn't it work for AnonymousUser here? -
If True put item from queryset on end of the list
I have app when I want to check if date is in the past. If it is true, I want to put this item on the end of the list. Here is my code but it is not working and I get error message: 'QuerySet' object has no attribute 'extend' My code: for i in queryset: if i.date_end < now(): queryset.extend(queryset.pop(queryset.index(i))) -
Django- Filter Models by date and user then total fields
What I am trying to do is get models that were created, lets say 1/1/17-1/31/17, then total a FloatField of all the models returned. With that total, I want to populate a column on a bar graph labeled January. Then do the same for February... and so on. Here is my model: class Punch(models.Model): flag = models.FloatField(max_length=10) actual = models.FloatField(max_length=10, blank=True, null=True) description = models.CharField(max_length=100, blank=True) user = models.ForeignKey(User) date = models.DateTimeField(auto_now_add=True) I want to filter by user and date range so in my views I have something like this: punch = Punch.objects.filter(date__range=[2017-01-01,2017-01-31]) user = request.user punches = punch.filter(user=user) context = {'punches': punches} So throughout the month the user is filling out a form entering an amount in the flag field then saving the Punch object. I want to get the total amount entered in the flag field for the month. This is were I get lost. I assume that I will need to have a for loop run through the objects but I am unsure how exactly to accomplish this. Also, should this occur in the template or in my views? Any help is appreciated! -
Violation not-null constraint. With a ForeighKey (not user) while trying to post in Django RestFramework
This problem is commented in the whole Internet, but I don't know why, it's almost always with the user. In my case, the problem is not with the User. I have this model: class DocumentDetail(models.Model): date = models.DateTimeField(_('date'), auto_now_add=True) note = models.TextField(_('note'), blank=True) checked = models.BooleanField(_('checked'), default=False) details_sample = models.ForeignKey(DocumentDetailSample, related_name='details_sample', verbose_name=_("details_sample"), blank=False) user_id = models.ForeignKey(User, related_name='document_user_id', verbose_name=_('document_user_id'), blank=False) class Meta: ordering = ('date',) Where I can user the DocumentDetailSample fields. The problem is that with the user, I can do this: def perform_create(self, serializer): serializer.save(user_id=self.request.user) def perform_update(self, serializer): serializer.save(user_id=self.request.user) But with details_sample it should be something passed in the post, because I can't know which "details_sample" it should be. That's why I thought I could pass the id in the post body. { "note" : "Oh, nice", "checked": "True", "details_sample": "1" } But I get this error: django.db.utils.IntegrityError: null value in column "details_sample_id" violates not-null constraint DETAIL: Failing row contains (9, 2017-01-24 14:43:58.75642+00, Oh, nice, t, 2, null). So everything but the details_sample worked. :( And here's the row: "1";"2017-01-24 14:40:37.881802+01";"Life is beautiful";"''";"1";"The life is beautiful. And there's also a movie";"This is about life";"{"name": "Chuck", "phone": "123"}" Does anyone know what could I do? -
Django filtering queryset
Here is my simple view: def transaction_list(request): current_user = request.user month = datetime.date.today().month try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 objects = Transaction.objects.filter(user=current_user, date__month=month) p = Paginator(objects, 10, request=request) transactions = p.page(page) return render(request, 'transaction/list.html', {'transactions': transactions}) It shows a list of transactions which occured in the current month. I want to add an option to change the month of the transactions being displayed but I have no clue how to tackle this and make it work. Should it be done in a view? maybe template? I would appreciate any ideas -
Django formset is not valid- why not?
I am trying to use a form to allow users to upload images to projects stored in a database in my Django project, however, I'm currently getting console output that's telling me that the formset I'm using is not valid... The view that I'm trying to use to upload the images to a project has been defined with: def upload_budget_pdfs(request, project_id): project = Project.objects.get(id=project_id) print("Value of project in 'upload_budget_pdfs()': ", project) presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn') print("Value of presentations in 'upload_budget_pdfs()': ", presentations) drawing_formset = DrawingUploadFormset(prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created')) print("Value of drawing_formset in 'upload_budget_pdfs()': ", drawing_formset) if drawing_formset.is_valid(): print 'Saving drawing_formset' print "Before", [b.id for b in project.budget_versions.all()] for drawing_form in drawing_formset: if drawing_form.instance.budget: print 'Instance', drawing_form.instance.budget drawing = drawing_form.save(commit=False) drawing.budget = drawing_form.instance.budget drawing.save() print drawing, [b.id for b in project.budget_versions.all()] else: print 'Drawing formset not valid.',drawing_formset.errors budget_formset = BudgetPresentationFormset(request.POST, request.FILES, instance=project, prefix="presentations") if budget_formset.is_valid() and budget_formset.has_changed(): updated_budget_presentations = budget_formset.save() elif budget_formset.has_changed(): print 'Budget formset not valid.',budget_formset.errors return HttpResponseRedirect(reverse('projects:concept', args=[project_id])) and the console output I'm getting when this view is called is: ("Value of project in 'upload_budget_pdfs()': ", < Project: Test 1 >) ("Value of presentations in 'upload_budget_pdfs()': ", [< Budget: Test 1: Version -1 >, < … -
Django 1.10.5 Python 3.5.2 Jsignature
The app Jsignature is just what I need. It looks great. Unfortunate for me, I can't get it to work. Is this app the right app for Django 1.10.5 and Python 3.5.2? I used the example code, made no changes and still I only get the button and not the signature field. What I would like to do is this: With data from the site (filled in by the user) I create a pdf. Herefor I use Weasyprint and a template. This all works fine. Now I want to add a signature from the same template into de pdf as well. How do I do that? Can somebody help me? -
Django TemplateDoesNotExist at /rango/
I've seen this question asked before, but I'm already using the newer TEMPLATES data structure which is the common solution. From the tango with django book, I'm currently on unit 4. When I run my program with python manage.py runserver I receive the following error: TemplateDoesNotExist at /rango/ rango/index.html Request Method: GET Request URL: http://127.0.0.1:8000/rango/ Django Version: 1.5.1 Exception Type: TemplateDoesNotExist Exception Value: rango/index.html Here is the relevant code in my ~/Workspace/wad2/tango_with_django_project/setings.py file: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'tango_with_django_project', 'templates') . . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], . . Also, here is the relevant code in my ~/Workspace/wad2/rango/views.py file: def index(request): context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"} return render(request, 'rango/index.html', context_dict) And lastly, my template is located at ~/Workspace/wad2/tango_with_django_project/templates/rango/index.html -
Django/Postgresql : Is the server running on host "xxx" and accepting TCP/IP connections on port 5432?
When I try python manage.py makemigrations or migrate or runserverin django terminal, I am getting this error ; conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "my_remote_ip" and accepting TCP/IP connections on port 5432? I'll give you my settings.py - databases settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_database_name', 'USER': 'my_user', 'PASSWORD': 'my_password', 'HOST': 'my_remote_ip', <-- and also I try localhost 'PORT': '', <-- default 5432 } } this is my postgresql.conf settings ; listen_addresses = 'my_remote_ip' port = 5432 also I try listen_addresses = '*' port = 5432 and this is my pg_hba.conf settings ; #IPv4 local connections: host all all my_remote_ip/32 md5 #IPv6 local connections: host all all ::1/128 md5 In my remote server, all port is opened by host and there is no problem with firewall. What is the problem ?. -
What signal to listen to for new Many-To-One relations?
from django.db import models class Reporter(models.Model): pass class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) With the models above, what signal should I listen to if I want to know when an article is added to a reporter? >>> new_article = Article() >>> new_reporter = Reporter() >>> new_reporter.article_set.add(new_article)