Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using djstripe for multiple subscriptions per customer
I've been using dj-stripe to handle customer subscriptions but I'm now exending the functionality so each customer can have a number of associated accounts, each of which requires a subscription and these accounts can be added at any time. I could invoice on a monthly basis depending on the number of active accounts but this could very complicated. From the documentation it seems it's possible to have multiple subscriptions but I'm not clear how to link them to the accounts and how to create a new plan/subscription when I add an Account. class MyCustomer(AbstractUser): multi_accounts = models.BooleanField(default=False) class Account(models.Model): customer = models.ForeignKey(MyCustomer) subscription_ends = models.DatetimeField() According to the documentation http://dj-stripe.readthedocs.io/en/latest/settings.html#djstripe-subscriber-model-settings-auth-user-model, I could add another model: class CustomerAccount(models.Model): customer = models.ForeignKey(MyCustomer) account = models.ForeignKey(Account) subscription_ends = models.DatetimeField() @property def email(self); return self.customer.email But I'm still not clear how I might use that as the example callback http://dj-stripe.readthedocs.io/en/latest/settings.html#djstripe-subscriber-model-request-callback-none assumes there is only one of this class of object per customer. Is there a way to do what I want with djstripe? -
cant see my post in my list .html
i created a blog this is my models.py configurations: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ('admin','admin'), ) title=models.CharField(max_length=250,null=True) author=models.ForeignKey(User,related_name='blog_posts',null=True) slug=models.SlugField(max_length=250,unique_for_date='publish',null=True) body=models.TextField(default='') publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True,null=True) updated =models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices =STATUS_CHOICE, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail',args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%dz'), self.slug]) and this is my views.py: from django.shortcuts import render from .models import post # Create your views here. def post_list(request): posts= post.published.all() return render(request,'blog/post/list.html',{posts:posts}) def post_detail(request,year,month,day,post): post=get_object_or_404(post,slug=post, status = 'published', publish__year=year, publish__month=month, publish__day=day) return render(request,'blog/post/index.html',{'post':post}) and this is my base.html: {%load staticfiles%} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %} <link rel="stylesheet" href={% static "/css/blog.css"%}> {% endblock %} </title> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>my blog</h2> <h3>this blog</h3> </div> </body> </html> and my list.html file: {% extends "blog/base.html" %} {% block title %}My blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </h2> … -
Cannot see the video
I am creating app in django in which user can upload video but in that app I am unable to see the video. Code: <video width='400' controls> <source src='{{ MEDIA_URL }}{{ pic }}'> </video> I am writing this code and whats going wrong I am unable predict it. The Output is: I am seeing this output Please help I am creating it for my college project. Please help. -
django - Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I have a droplet in digitalocean working with django and mysql. From a month ago I have a problem. All is working well until an error appear (server error 500): (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I open mysql from putty terminal and the problem is solved. (The page works). When a client send a form with a lot of data the problem returns. Can u help-me? Thanks -
How I can change render to return json in view Django
I have function in view from django.shortcuts import render from .models import myModel def articleTheme(request): if request.method == 'POST': article_id = request.POST['id'] article = myModel.objects.get(id=article_id) theme = article.theme return render(request, 'theme.html', {'newTheme': theme }) now it works normal. But I have excess html. I want return json object. What I can import and return? -
Creating child paged in migrations files
I'm trying to create to index pages that are children of home page, some like this: # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-13 22:50 from __future__ import unicode_literals from django.db import migrations def create_blogindexpage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') BlogIndexPage = apps.get_model('blog.BlogIndexPage') HomePage = apps.get_model('home.HomePage') blogindexpage_content_type, __ = ContentType.objects.get_or_create( model='blogindexpage', app_label='blog') # Create a new blogindexpage blogindexpage = BlogIndexPage.objects.create( title="Blogs", draft_title="Blogs", slug='blogs', content_type=blogindexpage_content_type, path='000100010001', depth=3, numchild=0, url_path='/blogs/', ) home_page = HomePage.objects.get(id=3) home_page.add_child(instance=blogindexpage) class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ('home', '0002_create_homepage'), ] operations = [ migrations.RunPython( create_blogindexpage, ), ] This index of blogs have to be a child from the home page and this migration file depends of home create_homepage migration, but it give me this error: File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/salahaddin/Proyectos/Works/partnerlatam/blog.xprende/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in … -
Migration file don't change Site name and domain
I have this migration file: from django.db import migrations from django.contrib.sites.models import Site as DjangoSite def change_django_site(apps, schema_editor): site = DjangoSite.objects.get(id=1) site.delete() DjangoSite.objects.get_or_create(id=1, domain='www.xprende.com', name='XPrende') def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') HomePage = apps.get_model('home.HomePage') # Delete the default homepage # If migration is run multiple times, it may have already been deleted Page.objects.filter(id=2).delete() # Create content type for homepage model homepage_content_type, __ = ContentType.objects.get_or_create( model='homepage', app_label='home') # Create a new homepage homepage = HomePage.objects.create( title="Home", draft_title="Home", slug='home', content_type=homepage_content_type, path='00010001', depth=2, numchild=0, url_path='/home/', ) # Create a site with the new homepage set as the root Site.objects.create( hostname='www.xprende.com', site_name='XPrende', root_page=homepage, is_default_site=True ) def remove_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') HomePage = apps.get_model('home.HomePage') # Delete the default homepage # Page and Site objects CASCADE HomePage.objects.filter(slug='home', depth=2).delete() # Delete content type for homepage model ContentType.objects.filter(model='homepage', app_label='home').delete() class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ('sites', '0002_alter_domain_unique'), ] operations = [ migrations.RunPython( create_homepage, remove_homepage, change_django_site, ), ] As you can see i made a function that have to change the django site name and domain. But it doesn't do it, after apply the migrations i get the same default values: In [3]: DjangoSite.objects.get(id=1) Out[3]: … -
Coverage.py warning: No data was collected. (no-data-collected)
I am trying to find the coverage using coverage module for a django project but gets "Coverage.py warning: No data was collected. (no-data-collected)". My project folder has src and tests folders. When I run coverage run -m pytest && coverage report It produces a report with 100% coverage with the list of files inside the tests folder. Whereas when I run coverage run --source=src -m pytest && coverage report it says Coverage.py warning: No data was collected. (no-data-collected) No data to report. When I try to give the source=src or include=src in the .coveragerc also the same warning occurs. The tests passes for all the above cases. I want the coverage of the src folder. Is it because I am missing some path setting? -
Django make changes in DB only for certain user / django-reversion revert version`s object only for a certain user
After a long time spent for googling without a big success I really need a help from someone who faced with this question earlier than me. I am using the django-reversion for storing an object changes, and my goal is to allow user to access a list of the object versions and select needed one, so the object will be changed for that version, however these changes shoud be visible only for that user. Other users should see the actual data of the object, until they also activate some other object version. But the django-reversion package works so that when you reverting the object to some version, this will affect original object in DB. Some possible solutions I was considering are django session and cookies, however it seems to be realy complicated for this use-case because the object has relations with other models. Please give me some directions, how it is possible to perform the expected behaviour. Or it is not possible to make this with django-reversion? Thanks in advance for any information! -
How to override Allauth login template in app in Django?
I tried overriding Django Allauth login templates in my app, but it didn't work. APP_DIRS in settings.py is also True. Login template location: ProjectName\main\templates\main\account\login.html Any idea how to fix this, without creating a templates folder on project level? -
How can I alter the response coming from a delete request in Django Rest Framework?
I am creating an app which retrieves a list of students in the database and enabling the user to add and delete students. I am using Django and Django Rest Framework for the backend and React for the frontend. Upon deleting a student I want the new list of students to be returned in the response this is my views.py: from django.shortcuts import render from django.conf.urls import url from rest_framework import viewsets, status from app.models import University, Student from app.serializers import UniversitySerializer, StudentSerializer from rest_framework.views import APIView from rest_framework.response import Response from django.http import Http404 class StudentList(APIView): def get(self, request, format=None): students = Student.objects.all() serializer = StudentSerializer(students, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = StudentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): student = self.get_object(pk) student.delete() students = Student.objects.all() serializer = StudentSerializer(students, many=True) return Response({'data': serializer.data}) This is the request: axios.delete(`api/students/${id}`) .then((response)=>{ console.log(response); }) The request is working and the student is deleted, but the data in the response returns an empty string: {data: "", status: 204, statusText: "No Content", headers: {…}, config: {…}, …} Is there something I'm doing wrong? -
Which Python Framework should I learn?
Hi i'm learning python web development and using webapp2 framework to build my website and i'm almost done. Now i'm thinking to learn other python framework (Flask or Django). Which framework should i learn Flask or Django ? -
How to pass tuple as arguments in raw mysql in Flask Python? [duplicate]
This question already has an answer here: Python MySQL Connector database query with %s fails 1 answer I'm trying to fetch data from mysql by passing a tuple as argument. The query is perfectly working directly in mysql but when in flask app, its returning Sqlalchemy error image app.py: not_selected = tuple(not_selected) print not_selected for n in not_selected: all_modules = [] modules_data = db.execute("""SELECT id, group_code, group_name, module_name, url, icon FROM modules WHERE id NOT IN %s""",not_selected[n]) for j in modules_data: m = {} m['id'] = j[0] m['group_code'] = j[1] m['group_name'] = j[2] m['module_name'] = j[3] m['url'] = j[4] m['icon'] = j[5] all_modules.append(m) print not_selected printed in console was: (1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48) Note: Mysql query is 100% correct and working in mysql query browser but I don't know why this is returning error in your SQL syntax. Please help me out! Thanks. -
Setting up setattr behavior of Django model without affecting instance initialization
I have a model called A. When b attribute is set of that model, I want to update that attribute like this: # Note that PGJSONField is a field that can store string or json. class A(models.Model): description = PGJSONField(blank=True, null=True) def __setattr__(self, key, val): if key == 'description': val = {'description': val} super(A, self).__setattr__(key, val) This causes a side effect. When I get model instance from DB. It set's up description key as dict event if it's not. >>> a = A.objects.first() >>> a.description ..: {"description": "lorem ipsum"} My expected bahavior is something like this: >>> a = A.objects.first() >>> a.description ..: "lorem ipsum" >>> a.description = "foo bar" >>> a.description = {"description": "foo bar"} I think I must by pass _setattr method when model is being fetched but I couldn't find a way to do it. Any suggestions? -
Application overhead design decision: store needed value on database row or find it dynamically in queryset
I'm developing a simple price tracker application. I'm a bit new to web application design and could use an experienced opinion here. My application pulls price points for hundreds of thousand of products per day by unique price SKU. For each SKU I want to be able to show: All time high price All time low price Average price When my API writes a new SKU price to the database I am able to figure out these three values and write them to the latest/current price row. Is this a better design decision than say using a Django Queryset in my View to query for and/or calculate and display them? -
Onclick Confirm add Checkbox Length
This should be really simple, but I can't get it to work and I'm an absolute beginner with Javascript. I looked at various threads here. I'm working with a django template, on a simple link. I want to add an onclick confirmation message such as 'Trash (14) Projects? Are you sure?' where 14 is the number of checkboxes ready to submit in a form. Right now I have. <button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add projects to trash - Are you sure?')" >Remove / Add To Trash</button> Which of course doesn't have the number of projects to be deleted. I could add a script in the head to count the classes of checkboxes, but I want to know how I might execute javascript inside the confirm dialog itself? Such as... <button type="submit" class="actionbutton" name="delete" onclick="return confirm('Add ($(":checkbox:checked").length) to trash - Are you sure?')" >Remove / Add To Trash</button> Which doesn't work, probably because the ":checkbox:checked" gets escaped inside the onclick " ". Anyone point me in the right direction as to what is the 'usual' way to do this kind of thing... -
Django, How to route the traffic?
Contract an instance in gandi.net but I want to have several domains (vhost) in that same instance only I was satisfied with the support that is only possible redirecting the traffic with my python code, I have no idea how to do it. Thank you for contacting Gandi support. Python instances only have one vhost, named 'default'. If you'd like to host multiple Python website on a single instance, then you will need to route the traffic with your Python code, by using the 'host' header. host = self.headers.get('Host') https://doc.gandi.net/en/simple/python We are at your disposal should you need any further information. Best regards, if someone could clarify, how to do routing with django? -
Different css margins for mobile & desktop without multiple {% block content %} in Django template
I need to change the margin-left that is applied to my main {% block content %} in my base.html template (that contains my navbar and other common elements) based on if the viewer is using mobile or desktop. My current base.html is like: <div class="content container-fluid"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> with a css file containing: .content { margin-left: 40px; } .content_mobile { margin-left: 10px; } Given that in other parts of my application I've accomplished this by using the following dedicated Bootstrap classes, my first thought was to do the same using something like: <div class=".visible-xs-block, hidden-xs"> <div class="content container-fluid"> <div class="row"> <div class="col-md-8"> <!-- This is hidden from mobile view --> {% block content %} {% endblock %} </div> </div> </div> </div> <div class=".visible-lg-block, hidden-lg .visible-md-block, hidden-md .visible-sm-block, hidden-sm"> <div class="content_mobile container-fluid"> <div class="row"> <div class="col-md-8"> <!-- This is hidden from all other views (including desktop) --> {% block content %} {% endblock %} </div> </div> </div> </div> But Django raises an exception because it can only render 1 {% block content %} per template! Any ideas how I can do this without using multiple blocks? -
Where can I to write my logic in APIView?
In the CreateAPIView I can override the create method to add my logic: class OpenstackAccountCreateAPIView(CreateAPIView): """ create openstack account """ serializer_class = OpenstackAccountCreateSerializer def create(self, request, *args, **kwargs): # put my logic here ...... But if I have a APIView, where can I to write my logic? class OpenstackAccountLoginAPIView(APIView): serializer_class = OpenstackAccountLoginSerializer # where can I put my logic? -
Save data of django form in database
I'm using Django 1.3 and I have a form defined with forms.py: class mopa(forms.Form): idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 ) causale = forms.CharField(label="Causale Pagamento *", required=True) imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True) quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True) and in this file I made the checks. My models.py file: class Mopamodel(models.Model): idcarrellosorgente = models.IntegerField() cod_ente = models.CharField() causale = models.CharField() imp_unitario = models.DecimalField() quantita_item = models.IntegerField() and my views.py def paga(request): # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = mopa(request.POST) print('form: ', form.data) #return a dictionary # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required # p=form.save() <--don't works: error: 'mopa' object has no attribute 'save' idcarr = form.cleaned_data['idcarrellosorgente'] caus = form.cleaned_data['causale'] imp_u = form.cleaned_data['imp_unitario'] qta = form.cleaned_data['quantita_item'] dictmopa={} dictmopa['id_carr']=idcarr cod_ente = form.cleaned_data['cod_ente'] mopapay=Mopamodel(idcarrellosorgente=idcarr, cod_ente=cod_ente, causale=causale, imp_unitario=imp_u, quantita_item=qta #mopapay.save() <--this produce the error: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType' .... # redirect to a new URL: return HttpResponseRedirect(reverse('viewsdati/') ) How can I save the form … -
How to check session expiration on close of browser in Django?
Here is the scenario I wish to handle in Django application User logs in web application. SESSION_EXPIRE_AT_BROWSER_CLOSE is set to true. User closes the browser window. Now how to know receive the session info that session has been killed/Destroyed? -
Creating an url within a div button using django url + div button value ie div id
I have created a clickable div to act as a 'button'that links to another page within my site. Is it possible to append the div ID into the url I call such that different divs call the same django url (as the base) but through the appended div id ended up going to different pages . for example: this example works with the pack.id being appended but in the scenario I want to implement I do not used a django model <div id="ticket1"> <a href="{% url 'student-packages-add' pack.id %}"> </div> trying to do: <div id="ticket1"> <a href="{% url 'student-packages-add' div.id %}"> </div> what doesn't work and creates errors: <div id="ticket1"> <a href="{% url 'student-packages-add' ticket1 %}"> </div> or <div id="ticket1"> <a href="{% url 'student-packages-add' "ticket1" %}"> </div> -
Comparing date field in a form with current date
I am trying to check with an if statement if the date entered in a form is before the current date. If so write to an object in the model. I am also not sure if there are a better way of doing this. I get this error '<' not supported between instances of 'DateField' and 'datetime.date' My view: class ActionCreateView(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' template_name = "nodiso/actioncreate.html" form_class = forms.LeadActionCreateForm # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] ) def get_success_url(self, **kwargs): return reverse("nodisoapp:leaddetail", kwargs={'pk': self.kwargs['pk']}) def form_valid(self, form): if form.fields['Duedate'] < datetime.date.today(): self.object.overdue = 1 else: pass self.object = form.save(commit=False) self.object.lead_id = self.kwargs['pk'] self.object.creator = self.request.user.firstname self.object.save() return super(ActionCreateView, self).form_valid(form) The Model: class LeadActions(models.Model): lead = models.ForeignKey(Leads) name = models.CharField(max_length=265) crdate = models.DateField(auto_now_add=True) Duedate = models.DateField() creator = models.CharField(max_length=265) overdue = models.IntegerField(null=True,blank=True) def __str__(self): return self.name The form: class LeadActionCreateForm(forms.ModelForm): class Meta: model = models.LeadActions fields = ['name','Duedate'] -
Extend the user model (avatar)?
I want to extend my user model and add avatar(image) field. I created new app - accounts and inside the models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings from django.contrib.auth.models import User def download_location_of_usrpic(instance, filename): return "%s/%s" %(instance.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( upload_to=download_location_of_usrpic, null=True, blank=True, height_field="height_field", width_field="width_field" ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) My admin.py from accounts.models import Profile admin.site.register(Profile) Made makemigrations and migrate I also have a GCBV @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): model = User fields = ('first_name', 'last_name', 'email', 'image', ) template_name = 'my_account.html' success_url = reverse_lazy('my_account') def get_object(self): return self.request.user But I dont see this field in admin and got the mistake in account Exception Value: Unknown field(s) (image) specified for User What did I miss? -
How do I run pytest in Jenkins server for django application?
I want to run pytest to verify all my unit test cases are passed in Jenkins server before deploying to production server. Can we achieve it without activating the virtualenv in the jenkins server? How is it done generally in jenkins server?