Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/ Python- should I run makemigrations on a local branch, or only on master?
I am working on a project that has been written in Python/ Django, and have recently made some changes to one of the models. I want to test the changes that I have made now, before I go any further into the development of this new feature, but I am aware that I will need to run python manage.py makemigrations & python manage.py migrate before the changes that I have made to the models take effect. I am doing the development on a separate git branch to master, but am a bit unsure what the best practice is here in terms of running migrations on different branches (I am relatively new to both Python/ Django & Git). Would it be sensible to run makemigrations on my development branch, and testing it there, the same way I have been testing the bug fixes that I have worked on so far, or will I need to merge my development branch with master before running makemigrations? I know that if I do run the migrations on my development branch, I will need to run them again on master once I have merged my changes, but I was just wondering if there are any … -
Django Project Serving Static Files With Several Apps
I have the following structure in my Django project. As you can see, there is one app called "blog" as well as the main app that is eponymous with the project itself. The problem I am having has to do with serving static files from the static directory of the main project. The blog app has its own static directory and those files are served properly (when the pertinent URL routes are traversed). Could someone tell me what I am doing wrong? Also, what is the best practice of serving static files when dealing with multiple apps? Is it prudent to dump all styles and scripts into a common static directory in the root of the project or is it better to keep things entirely separated from app to app? settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "..", "django_by_example_blog", "static") STATIC_URL = '/static/' urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="base.html")), url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Home | Triangle</title> <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "css/font-awesome.min.css" %}" rel="stylesheet"> <link href="{% static "css/animate.min.css" %}" … -
Virtual environment starts a different version of python on a different machine
I've been using virtual environment successfully for some time, but this is the first time i run into such a problem. In my virtual environment i have Python 3.5 + Django package + number of other packages. I successfully run my Django app using Python 3.5 from virtual environment on machine A. On machine B, after I source env/bin/activate my virtual environment. python command would start Python 2.7 + no Django package present. How do i investigate this and make venv behave in same way on both machines? -
Login verification using Django Rest API and Android doesn't work
I am using the django rest api as a backend, the android app is the front end. So far I have been able to successfully register a user. I am unable to get the user to login. The urls.py file has the following code to link to the views.py file router.register(r'api/login', views.LoginViewSet) In the views.py file I have the following code which performs the login: class LoginViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSeralizer @detail_route(['POST']) def login_user(self,request,pk=None): if request.method == "POST": username = request.POST['email'] password = request.POST['password'] user = authenticate(email=username, password=password) if user is not None: if user.is_active: return Response(user.data, status=status.HTTP_200_OK) else: return Response(user.error, status=status.HTTP_400_BAD_REQUEST) else: return Response(user.error, status=status.HTTP_400_BAD_REQUEST) This android app is using the retrofit2 library, the following method is called when the sign in button is clicked. public void loginUser() { Retrofit retrofit=new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create()).build(); APIService service=retrofit.create(APIService.class); String username=etUsername.getText().toString(); String pass=etPassword.getText().toString(); Call<Users> call = service.loginUser(username,pass); Log.w("CAll",""+call); call.enqueue(new Callback<Users>() { @Override public void onResponse(Call<Users> call, Response<Users> response) { Log.d("onResponse", "" + response.code() + " response body " + response.body() + " responseError " + response.errorBody() + " responseMessage " + response.message()); } @Override public void onFailure(Call<Users> call, Throwable t) { Log.d("onFailure", t.toString()); } }); } The APIService interface I have created … -
How to add custom model to django_celery
I'm working on making celery suitable for high availability I've forked the django_celery project and this fork of celery in order to make the customizations that I need. The celery link shows the modifications to the beat.py that utilizes the following code: I've added this Lock model to django_celery models.py file and was able to migrate just fine: from django.db import models @python_2_unicode_compatible class Lock(models.Model): name = models.CharField(max_length=127, unique=True) created = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = _('locks') def __str__(self): return self.name In celery in the utils folder I've added this locked.py file: from djcelery.models import Lock from datetime import datetime, timedelta from django.db import transaction, IntegrityError class Locked(object): """A context manager to add a distributed mutex.""" def __init__(self, name, timeout): self.name = name self.lock = None self.timeout = timeout def __enter__(self): # first delete any expired locks expired = datetime.utcnow() - timedelta(seconds=self.timeout) Lock.objects.filter(name=self.name, created__lte=expired).delete() # then try to get the lock try: Lock(name=self.name).save() except IntegrityError: transaction.rollback() raise LockError('Could not acquire lock: {0}'.format(self.name)) def __exit__(self, *args): Lock.objects.filter(name=self.name).delete() class LockError(Exception): """Exception thrown when the requested lock already exists.""" pass with these changes I'm able to run the following commands: celery worker python manage.py runserver python manage.py shell I issues arrises when I … -
Invalid PDF structure with Django and API REST
I'm realizing a significiant project and I'm getting a problem without find a way to solve it. I'm saving pdf file generated thanks to Django (xhtml2pdf library) to LogicalDoc. I create folder, .. but when I want to open the file, I'm getting the following error message : Message : Invalid PDF structure Strangely, It worked before and now it doesn't work. There is maybe an error with generated document, but I don't find where : @login_required def BirthCertificate_PDF(request, id) : birthcertificate = get_object_or_404(BirthCertificate, pk=id) data = {"birthcertificate" : birthcertificate} template = get_template('BC_raw.html') html = template.render(Context(data)) filename_directory = str(BirthCertificate.objects.get(pk=id).id) + "_" + str(BirthCertificate.objects.get(pk=id).lastname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).firstname.encode('utf-8')) + "_" + str(BirthCertificate.objects.get(pk=id).birthday) filename = 'Acte_Naissance_' + filename_directory + '.pdf' path_individus = '/Users/valentinjungbluth/Desktop/Django/Individus/' path = path_individus + filename print BirthCertificate.objects.get(pk=id).folderId file = open(path, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') # If folderID is NULL : create a folder and save pdf file inside if BirthCertificate.objects.filter(pk=id).filter(folderId__isnull=True) : payload = '{{ "name":"{0}", "parentId":3309569 }}'.format(filename_directory) url = 'http://localhost:8080/services/rest/folder/create' headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} resp = requests.post(url, data=payload, headers=headers, auth=('admin', 'admin')) rbody = resp.content data = json.loads(rbody) folderId_person = BirthCertificate.objects.filter(pk=id).update(folderId=data["id"]) # Give the number folderId to a person payload = '{{ "language":"fr","fileName":"{0}","folderId": "{1}" }}'.format(filename, BirthCertificate.objects.get(pk=id).folderId) … -
SuspiciousFileOperation: Storage can not find an available filename for
I have this error after saving an avatar while creating an instance of this model (I didn't rewrite any base django model methods): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def conference_directory_path(instance, filename): return BASE_DIR+'/static/dialogues/conferences/conference_{0}/avatar/{1}'.format(instance.id, filename) class Dialogue(models.Model): ... avatar = models.ImageField(upload_to=conference_directory_path, blank=True) ... What's wrong? -
Is there a way to make a OneToOne field list editable in Django admin?
In a particular Django setup, there is a model (call it item foo) with a OneToOne relationship to another model (call it bar). Is there a way to make a particular field in 'bar' list_editable? List editable is where it appears in the django admin list view as an editable field for each item in the list, so updates to many items can be made. Example: class Foo(models.Model): name = models.CharField(....) class Bar(models.Model): foo = models.OneToOneField(Foo) other_bit = models.BootleanField(default=False) Then in admin what I would like to do (this won't work) is something like: class FooAdmin(admin.ModelAdmin): fields = ('name', ) list_display = ('name', 'bar__otherbit') list_editable = ('name', 'bar__otherbit') Is there a way to make list editable work here? -
Docker containers exiting without identifiable cause (Django web application)
I've taken over the maintenance of a live web project that utilizes docker containers. Immediately, I've noticed that the web app goes down after a couple of hours, and docker ps -a shows me: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9b02f1352f15 nginx:latest "nginx -g 'daemon off" 9 weeks ago Exited (1) 14 hours ago 80/tcp, 443/tcp, 0.0.0.0:80->8000/tcp ng01 8079b3d3b398 webapp_web "gunicorn --error-log" 9 weeks ago Exited (1) 14 hours ago 8000/tcp webapp_web_1 564fe0b72fa6 d0f5f9c3d3a6 "/bin/sh -c 'apt-get " 12 weeks ago Exited (0) 12 weeks ago modest_perlman 6cddbfcfa8f6 d0f5f9c3d3a6 "/bin/sh -c 'apt-get " 12 weeks ago Exited (0) 12 weeks ago backstabbing_goldwasser 7460be4f4451 postgres "/docker-entrypoint.s" 4 months ago Exited (1) 14 hours ago 5432/tcp webapp_db_1 Notice the 3 containers that exited 14 hours ago - those relate to the web app. How do I diagnose/fix this problem? Being a beginner, I'm struggling here. Thanks in advance! Following are some diagnostics I tried to run. I used docker logs on the errant containers to see what could be going wrong. docker logs 9b02f1352f15 (nginx) is empty. docker logs 8079b3d3b398 (application server - gunicorn) shows many incidences of: Exception in thread Thread-725265: Traceback (most recent call last): File "/usr/local/lib/python2.7/threading.py", line … -
Aligning Data in a ReportLab Table
I would like to align data in a ReportLab table so that half the table is aligned to the left, and half the table is aligned to the right. This table is made up of paragraphs and variables. Here is the code: table_data = [] quote_title = Paragraph(qn, styles['Heading1']) table_data.append([ttab_empty, quote_title, ttab_empty]) #tab_empy are empty strings title_table = Table(table_data, colWidths=[5 * cm, 5 * cm, 5 * cm]) title_table.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), "CENTER")])) elements.append(title_table) However, the align tag isn't aligning the text in the table. Same goes if the align is set to left. How can I align my cell data to the center? Thanks -
Select where not working in postgresql
i've been bashing my head the last day or so with an issue i have with my PostgreSQL Database. Here's the database with all the rows: enter image description here The row's content is in Spanish. My issue is that when i try to do a "select * from stores_store_category where name='Some value'", it's working only in a few specific cases. Let me show you what i mean: On the left there's an example of the query working, and on the right of the query NOT working: enter image description here I have no idea why this is happening i'm currently using PostgreSQL 9.6, the encoding on my DB is UTF8 and the tables were created through Django's migration. Looking forward to any answers, cheers. -
user session discrepancy across web addresses pointing to the same DNS name
I maintain a Python/Django web app where users can authenticate and log in. I've noticed that if I log into my app at example.com, I'm still logged out at www.example.com! This behavior replicates on all major browsers (Firefox, Chrome, etc). It seems session information is not being maintained between these addresses? I'm perplexed. Why could this be happening? My DNS name was procured from Azure. E.g. example.cloudapp.net. I use a DNS management service called Hurricane Electric to map example.com and www.example.com to this DNS name. Specifically, in Hurricane Electric I've created CNAME records where the hostname is the azure-provided DNS name, and the name is the web address I want to associate with it (along with a TTL). That's about all I've done. -
Stripe connect integration on a django marketplace
I'm creating a marketplace and I would like to integrate Stripe connect to allow users to make transactions with each other. I have some trouble to understand few things. I have 2 types of users : Customer and Seller. here is what I have in my views : customer = stripe.Customer.retrieve(customer_id) customer.sources.create(source=token) stripe_id = gig.user.profile.stripe_id charge = stripe.Charge.create( amount=1000, # Amount in cents currency="chf", customer=customer, #customer description=gig.title, application_fee = 500, stripe_account=stripe_id, #seller ) And here is what I have in my models : class Profile(models.Model): stripe_id = models.CharField(max_length=200, null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) (gig are the product object of my website, it contains these fields : user,price,title) As I submit the test payment I encounter this error : The provided key 'sk_test_********************' does not have access to account 'cus_*************' (or that account does not exist). Application access may have been revoked. This is the reason I ask these questions : Did I set up a the destinations correctly on my view, if so why do I get this error ? Where should users set up their credit card infos to receive the payment ? On Stripe, if not in Stripe, should I create a model for banking ? (I'm … -
Django Form: Select Multipe allow to add the objects
I have a problem when I want to save the objects such as the Tags, and always returned an error because form validation. Select a valid choice. hello is not one of the available choices. Here, I want to implement the select input dynamically which customs additional value from the users creation. For the frontend demo, like this snippet: https://jsfiddle.net/agaust/p377zxu4/ As conceptually, the tags input provide available tags that already created before... But, the important thing is the Users are allowed to create additional tags what they wants. 1. here is my models.py @python_2_unicode_compatible class Tag(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.title class Meta: verbose_name = _('Detail Tag') verbose_name_plural = _('Tags') @python_2_unicode_compatible class Thread(TimeStampedModel): title = models.CharField(max_length=200) .... tags = models.ManyToManyField( Tag, blank=True, related_name='tags_thread') 2. forms.py from myapp.models import (Tag, Thread) class ThreadForm(forms.ModelForm): description = DraceditorFormField() tags = forms.ModelMultipleChoiceField( to_field_name='slug', # set the value to slug field, not pk/id required=False, label=_('Additional tags'), help_text=_('Sparate by comma to add more than once, or select from available tags'), queryset=Tag.objects.all(), widget=forms.SelectMultiple(attrs={ 'placeholder': _('Additional tags'), 'class': 'ui search fluid dropdown dropdown-add-tags' }) ) class Meta: model = Thread fields = '__all__' exclude = [ 'author', 'topic', 'rating', 'created', 'modified' ] … -
How To Add auth_user models in multiple database at same time
In my django project I need to add auth_user model inside multiple database, first is default second is custom_db. The reason that I want, because I can not use settings.AUTH_USER_MODEL inside model for custom_db -
How to stop Apache redirecting to index.html
I have a Dango app that I am serving with Apache using uwsgi. When I go to http://www.myserver.com/ Apache redirects me to http://www.myserver.com/index.html/ Which then gives me an error "page not found" (the site does not use a index.html page) The other URLs work fine, eg http://www.myserver.com/mystuff - is correctly served. How can I stop Apache redirecting the start site to index.html -
python annoy library import error in GAE project
I am working on GAE using python jinja2 framework, while importing third party library "annoy" I am getting import error. I am following the GAE Installing a third-party library method. My project structure like *projectfolder/ *lib/ *annoy/ main.py app.yaml appengine_config.py Here is my main.py code import os import jinja2 from google.appengine.api import users import webapp2 import csv from jinja2 import Template import annoy JINJA_ENVIRONMENT = jinja2.Environment( # TODO: to add other directories here that contains the templates. loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class Sent2Vec(webapp2.RequestHandler): """docstring for .""" def get(self): template = JINJA_ENVIRONMENT.get_template('sent2vec.html') self.response.headers['Content-Type'] = 'text/html' self.response.write(template.render() app.yaml runtime: python27 threadsafe: ture libraries: - name: webapp2 version: latest - name: jinja2 version: latest - name: annoy version: latest handlers: - url: /.* script: main.app appengine_config.py from google.appengine.ext import vendor vendor.add('lib') -
Django storages giving 400 bad request
This is the first time I was tying to use AWS S3 for media storages. The application is hosted in Heroku, for static files it has not been a problem so I do not want to change static files, but want the applications users to upload files and images which I wish to store in S3. I have already spent 2-3 days so far now and no proper solution was found as I get 400 exception without a proper reason. Here is the documentation which I referred to: http://tech.marksblogg.com/file-uploads-amazon-s3-django.html So, my settings now: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_S3_ACCESS_KEY_ID='dummyid' AWS_S3_SECRET_ACCESS_KEY='dummykey' AWS_STORAGE_BUCKET_NAME='dummyname' AWS_QUERYSTRING_AUTH = False AWS_HEADERS = {'Cache-Control': 'max-age=86400', } MEDIAFILES_LOCATION = 'media' MEDIA_URL = 'http://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME My model: class DummyDocuments(models.Model): document = models.FileField(upload_to='documents') My form: class DummyUploadForm(forms.Form): documents = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) And here is the view, where I am using it: def upload(request): if request.method == 'POST': form = DummyUploadForm(request.POST, request.FILES) if form.is_valid(): files = request.FILES.getlist('documents') for file in files: instance = DummyDocuments(document=file) instance.save() return redirect('activation_upload') else: form = DummyUploadForm() documents = DummyDocuments.objects.all() return render(request, 'activation/dummyupload.html', {'form': form, 'documents': documents}) Here is my CORS config on AWS: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Here … -
Django automatic add date to the form
I have models.py with a date field like this class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField('date published') def __str__(self): return self.text View.py like this: def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blog:topics')) context = {'form' : form} return render(request, 'blog/new_topic.html', context) form.py : class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text', 'date_added'] labels = {'text': ''} Now problem is that i need to automatic add date to the field . To have any DB inputs. -
User fields not appearing on some templates
I am using an extended user model from all-auth. I am able to pull both extended model fields (like organization), as well as the standard user fields (like user.email) easily on all templates except one. Because I struggled to build an update form (as I'm still new to Django), I ended up using properties/instances. This worked. I can edit orgnization. But for some reason on this template I cannot call user.email. I've tried all variations of it, from RequestContext to failed attempts at passing it in other ways. Model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) organization = models.CharField(max_length=100) def __str__(self): return self.user.organization # I got this from an old tutorial: User.profile_p = property(lambda u: Profile.objects.get_or_create(user=u)[0]) View: from django.shortcuts import render, render_to_response from django.http import HttpResponseRedirect from django.template.context_processors import csrf from .forms import UserProfileForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Profile @login_required def user_profile(request): if request.method == 'POST': form = UserProfileForm(request.POST, instance=request.user.profile_p) if form.is_valid(): form.save() return HttpResponseRedirect('/base_home.html') else: logged_user = request.user profile = logged_user.profile_p form = UserProfileForm(instance=logged_user.profile_p) args = {} args.update(csrf(request)) args['form'] = form return render_to_response('profile.html', args) Template: {% extends 'base.html' %} <title>{% block title %}Admul:{% endblock … -
How to make my forms work in Django?
I just created a Bootstrap 3 website with Django. My website has 4 different pop-up modals in the following order: 1. Uploading your display image, 2. adding basic information, 3. choosing login credentials and 4. adding their personal biography. These 4 modals all contain their own html form, so I have 4 different forms for the user to register their account. My question is how do I link all 4 forms together so I can pass the information to my Django server and generate the user in my database? I've seen videos of people generating their frond end forms through a Forms.py file, but I can't do it that way because I already have my forms. If I did not spend my time designing the frond end I would just delete the forms and generate them again through a Forms.py file, but I did. Anyone who can help me out? I'm quite new to Django. -
Pass data from a form to another in django
I have a ModelA and ModelB and i can add ModelB's from the ModelA "window". How do i pass a parameters from ModelA instance to the new ModelB instance when clicking this button(+): ModelA contains more than 1 ModelB Models A instance window This way i can be able to filter fields on the ModelB based on field choices made on ModelA that i sent to ModelB on click that (+) button. -
Can we use same serializer for POST, PUT & GET?
Can we use same serializer for creating, updating and getting a resource. is it a best practice to do so ? -
error while converting Django template engine to jinja2, unable to use 'with'
I have converted a small Django project to use jinja2 as a backebd engine. Now in one of the templates I am writing the following code: {% include 'base/rating.html' with rating=location.get_average_rating() %} The code above works fine with the Django template but when I switch the template engine to Jijna2 I am getting the following error. Request Method: GET Request URL: http://127.0.0.1:8000/location/ Django Version: 1.10.5 Exception Type: TemplateSyntaxError Exception Value: ("expected token 'end of statement block', got 'with'",) ] and the browser shows the following error Really want to know how I need to change such code for it to work in jinja2. tried multiple things from jinja documentation about #with-statement but nothing worked. Thanks in advance. -
send multiple file through $http angularjs
I have a javascript array of multiple files like filelist=[{'name':file1name,file:file1},{'name':file2name,file:file2}] I need to send this file to backend views.py using $http request. How do i send this in angularjs?