Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error with Digital Ocean Droplet for Django
I have been following along with this tutorial to deploy my django site on Digital Ocean. I have just uploaded all my files and restarted gunicorn. The site is giving my this error: ImportError at / No module named braces.views And here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response resolver_match = resolver.resolve(request.path_info) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in resolve for pattern in self.url_patterns: ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/functional.py in __get__ res = instance.__dict__[self.name] = self.func(instance) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/functional.py in __get__ res = instance.__dict__[self.name] = self.func(instance) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in urlconf_module return import_module(self.urlconf_name) ... ▶ Local vars /usr/lib/python2.7/importlib/__init__.py in import_module __import__(name) ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars /home/django/django_project/django_project/urls.py in <module> from blog import views ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars /home/django/django_project/blog/views.py in <module> from braces.views import SelectRelatedMixin ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars I … -
Django - custom non-model form field in admin panel
I would like to find a way to add another choice field next to actions form in my django admin panel. Here is my admin class: class InactiveSiteAdmin(SiteAdmin): change_list_template = 'admin/change_list_inactive.html' list_display = ('is_active', 'thumb', 'name', 'show_url', 'get_desc', 'keywords','category', 'subcategory', 'category1', 'subcategory1', 'group') fields = ('name', 'url', 'id', 'category', 'subcategory', 'category1', 'subcategory1', 'description', 'keywords', 'date', 'group', 'user', 'is_active', 'date_end',) readonly_fields = ('date', 'date_end', 'id') list_display_links = ('name',) actions = [activate_sites, activate_sites1, ] def get_queryset(self, request): return Site.objects.filter(is_active=False) def response_change(self, request, obj): return redirect('/admin/mainapp/site/{}/change/'.format(obj.id)) def has_add_permission(self, request): return False Here is top of my admin panel page: I am looking for way to add another choice field next to admin actions button. Something like: New form field is not related to any model. Choices are stored in database (I use django-constance). I tried to create new form in forms.py - for example with simple charfield: class EmailForm(forms.Form): email_form = forms.CharField(max_length=20) but I don't have any idea how can I use it in my admin template. -
Python traceback parts in Sentry event list
I am getting traceback parts in exception list on sentry.io using Raven 6.1.0 with Django 1.6 and Celery 3.1. Where should I look to make them reported properly? They are triggered only from periodic tasks (celery beat). -
Is there a Django way of comparing the results of a test to a fixture?
I'm trying to understand fixtures and unit tests in Django. I can successfully load a fixture and use the data in my unit test. What I want to do is compare the results of the test to a second fixture, fixture_2, which represents how the data should look. Here's a step-by-step of what I am talking about: Import fixture_1, generating the initial test data. Run the test on the data, changing it. Somehow compare the results of the test to fixture_2. Is there a way to do step 3? Should I somehow overwrite the test database with fixture_2 and do the assertions from there, or is there a way of comparing the test database to a fixture? -
Django 1.10 Template Renders Nested HTML Tags Outside Their Parent
I am a bit puzzled by the following behavior of the Django templates, which prevents me from successfully styling the output. Namely, I have the following template: <article class="article {% if article.is_featured %} featured{% endif %} {% if not article.published %} unpublished{% endif %}"> {% if not detail_view %} <div class="post-preview"> <a href="{% namespace_url 'article-detail' article.slug namespace=namespace default='' %}"> <h2 class="post-title"> {% render_model article "title" "" "" "striptags" %} </h2> {% if article.lead_in %} <h3 class="post-subtitle"> {% if not detail_view %} {% render_model article "lead_in" "" "" "truncatewords:'20'|striptags" %} {% else %} {% render_model article "lead_in" "" "" "striptags" %} {% endif %} </h3> {% endif %} </a> <p class="post-meta" style="margin-bottom: 0;"> Posted by {% include "aldryn_newsblog/includes/author.html" with author=article.author %} on {{ article.publishing_date|date:"F d, Y" }} </p> <p class="post-meta" style="margin: 0"> <h4 style="display:inline-flex">Categories:</h4> {% for category in article.categories.all %} <a href="/articles/category/{{category.name|lower}}">{{ category.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </p> <p class="post-meta" style="margin: 0"> <h4 style="display:inline-flex">Tags:</h4> {% for tag in article.tag %} <a href="/articles/category/{{tag.name|lower}}">{{ tag.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </p> </div> <hr> {% endif %} {% if detail_view %} <!-- <h3>Testing template! (from article with detail_view=True)</h3> --> … -
How to make a website work with Django development server?
I understand that this is never to be done. But I have a situation where I need to get something done real quick. I have to do a website where may be 200 people would register for an event. I need to present a simple registration form. Very basic functionality, register and view list of registrants. Very few hits. It would be live for about a month or so. I know a little bit of Django which can allow me to put together this thing quickly. However, I have only worked with the Django development server. My problem is setting up Apache to work with Django. I understand that, for Django, I need mod_wsgi installed. I have a VPS but mod_wsgi is not installed. I have asked my hosting provider to install it for me. Even if I can get mod_wsgi installed, it appears that it may take me some time to configure it and it may take a while. I have the following questions. Can I run this website on the Django development server? Will it hold up for very light traffic? If I do, how do I get traffic to go from port 80 to the development server … -
trouble using python requests to POST to django 1.8 server
I tried using session and grabbing the cookie. s = requests.Session() s.get(myurl) csrf = s.cookies['csrftoken'] The get had status_code 200 as expected. Then I first tried just a post on the session hoping that the session would do magic. (yeah I know better) r = s.post(myurl, json=mydata) which gives a status_code of 405. And yes, before I forget I have the django settings CSRF_HEADER_NAME='HTTP_X_CSRFToken' CORS_ORIGIN_ALLOW_ALL = True and my view function is marked with @csrf-exempt as well. The view function is known to accept post from my Angular frontend as long as I have 'X-CSRFToken=csrf' where csrf is as in the above setting. So I tried r = s.post(myurl, json=mydata, headers={'X-CSRFToken':csrf}) as well with the same result of 405. I read that it might help to set the referer to the url so I tried that as well. r = s.post(myurl, json=mydata, headers={'X-CSRFToken':csrf, 'Referrer: url}) and still got 405. So what is the correct way to make this work? -
[Django + Chart.js ]Uncaught ReferenceError: temperature is not defined
I tried to use Python Django make a ajax chart from database by javacript I used API VIEW in django restframwork retrieved the field temperature and send to ajax to render in the javascript. But the browser always said Uncaught ReferenceError: temperature is not defined This is my base.html This is my base.js This is my js block in the status.html This is my views.py I referenced this source code But I don't know what my cod get that above error. -
Login Using Microsoft Graph API
I used the following tutorial to create a login with Office365 - https://docs.microsoft.com/en-us/outlook/rest/python-tutorial#implementing-oauth2 It works, except I am allowed to access the http://localhost:8000/tutorial/mail page without having to login. Additionally, even after I logout( I added a log out function), The mail is still displayed, no matter what I do(e.g restart the server,etc.). Any help to solve this would be appreciated. Thanks. -
django-allauth mutli step signup form
I'm using pydanny/coockiecutter-django for a custom project, and I needed to build a custom multi-step signup for customers. django-allauth is a custom authentication tool inside cookiecutter so after some researching and reading the docs I found out how to customize allauth SignupForm and allauth-SignupView so it will fit my needs, but I have some problems, but please bare with me it's a long question. This custom signup needs to use some custom fields for state, zip-code and phonenumber. For this I'm using django-localflavor and for phonenumber-field I'm using django-phonenumber-field. Process of extending signup in django-allauth is a bit different. You can not define normal ModelForm field with class Meta rather you need to do it like this. This is two-step custom signup form. from django import forms from allauth.account.forms import SignupForm from localflavor.us.forms import USStateSelect, USPSSelect from ..models import User class CompanySignupStepOneForm(SignupForm): """ TODO: Custom Signup. :returns: TODO """ company_name = forms.CharField(max_length=225, required=True, strip=True) company_street_address = forms.CharField(max_length=225, required=True, strip=True) city = forms.CharField(max_length=225, required=True, strip=True) state = USStateSelect() zip_code = USPSSelect() def save(self, request): user = super(CompanySignupStepOneForm, self).save(request) company_user = User( step_one=user, company_name=self.cleaned_data.get('company_name'), company_street_address=self.cleaned_data.get('company_street_address'), city=self.cleaned_data.get('city') ) company_user.save() return company_user.step_one Step-two custom Signup Form: from django import forms from allauth.account.forms import SignupForm … -
postgresql query returned more than one row Django/heroku
This is working on local, I print it and it all looks fine to me but when I push to heroku which is running postgres, it gives me this error query returned more than one row. Here's what I have: locations = UserLocations.objects.filter(album =album) wish = UserWishList.objects.filter(traveler = people).values_list('place', flat=True) wish_places = UserLocations.objects.filter(id__in = wish) merge = locations | UserLocations.objects.filter(id__in = wish) and it's error when I'm retrieving merge. I tried doing distinct(), that didn't work. -
Using Django with Firebase
I'm using Django, because I was familiar with it, and firebase together. Obviously the firebase db doesn't connect directly with Django, so I have written custom models like so: class MyModel(object): def __init__(self, var): self.var = var def db_snapshot(self, snapshot): snapshot_value = snapshot.val() var = snapshot_value['var'] return self def to_any_object(self): return { 'var': var, } So everything works out pretty well for creating model objects, I also have some custom get(), save(), create() functions as well. Because I'm not using models or a django db, I'm also not using forms... So my question is, do I need to use forms? Obviously I know its not necessary, because I'm doing it currently, but my question is, am I exposing my customers to any potential security flaws? Is there anything I should know? I do plan on implementing the django rest framework later on, and at that point I would either move to mongodb or figure out how to implement the drf with firebase. I know what I'm doing isn't conventional, and I would appreciate ANY input. I have no degree and I self taught myself everything. Sincerely, Denis Angell -
How can i update class variable by calling a class method from a base class
I am developing a package for my testing purpose. In this package all my database queries are placed. a simple version of package is shown below. I am not using django ORM in my app since it is slower. I am using MySQLdb for accessing database. package.py from django.test import TestCase dbcon='connector' class testcase(TestCase): flag_user=[] @classmethod def setUpClass(cls): global dbcon dbcon=MySQLdb.connect(host=dbHost,port=dbPort,user=dbUser,passwd=dbPasswd,db=dbname) super(testcase, cls).setUpClass() cursor = dbcon.cursor() sql=open("empty.sql").read() cursor.execute(sql) cursor.close() views.MySQLdb=Mockdb() @classmethod def tearDownClass(cls): dbcon.close() def user_table(self,username=username,email=email): cache=[username] self.flag_user.append(cache) cmpdata=(username,email) insert_table(tablename_user,cmpdata) def delete(self,table): delete_table(tablename) self.flag_user=[] tests.py from package import testcase class showfiles(testcase): def setUp(self): print "setup2" self.user_table(username='vishnu',email='vishnu@clartrum.com') def tearDown(self): print "teardown2" self.delete("user") def test_1(self): print "test dbtest link feature" def test_2(self): print "test health/errorfiles with valid device" self.user_table(username='vishnu',email='vishnu@clartrum.com') The insert_table in package execute insert operation in sql and delete_table deletes the entry from user. empty.sql creates tables for the database. Actually when i run the tests, finally the flag_user should contain only [['vishnu']]. But i get [['vishnu'],['vishnu']] and this is because delete function in teardown doesn't updating the value. I think this is due to class property or something? Can any one suggest me a way to do this? -
Django Inheritance and One-To-One issues
I've devised the following relationships: class Security(models.Model): .... class MajorSecurity(Security): inner = models.OneToOneField(Security, on_delete=models.DO_NOTHING) class MinorSecurity(Security): ... I then put together a saved object like so: s = MinorSecurity.objects.create(...) c = MajorSecurity.objects.create(inner=s) Then when I access c.inner I only see that it is a Security and not a MinorSecurity What do I have to do to get django orm to recognize what subclass the one-to-one relationship is pointing to? The idea is that a MajorSecurity can have another MajorSecurity in it, or a MinorSecurity... so it needs to be flexible, which is why I chose to set the class to Security instead of a specific subclass. I was hoping that there is a way for the ORM to differentiate which subclass it is. I'm assuming the type also needs to be stored within the record of the Security. -
Django - Does not insert null and producing ValueError
I am uploading product catalog from csv file into below DB model models.py class Product(models.Model): name = models.CharField(max_length=50) invoice_date = models.DateField(blank=True, null=True) views.py def load_product(relative_path): if relative_path is not None: with open(os.path.join(BASE_DIR, relative_path)) as f: reader = csv.reader(f) for row in reader: if row[0] != 'id': _, created = Product.objects.get_or_create( name=row[1], invoice_date=datetime.datetime.strptime(str(row[2]), "%d-%m-%Y").strftime("%Y-%m-%d") ) else: return "Please enter a relative file name from data folder." Here is the sample csv file data id,name,invoice_date ,sample book1,26-10-2007 ,sample book2,15-10-2010 ,sample book3,22-09-2017, ,sample book4,, ,sample book5,, Some of my books don't have invoice_date so i want to insert None type (or empty), that's why i made blank=True, null=True in models.py, but it does not insert null and gives me following error when i execute the method using shell error File "C:\Python35\lib\_strptime.py", line 510, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "C:\Python35\lib\_strptime.py", line 343, in _strptime (data_string, format)) ValueError: time data '' does not match format '%d-%m-%Y' -
Formatting and incrementing a Django form in HTML
OK so I have a running form in Django that updates the model and displays this on the page, but I was hoping to better format it. What happens is that the page displays all data imputed in the form. What I want to do is to numerically list it. This is what I have in my home.html right now: {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Home</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% for post in posts %} <h2>Object:{{ post.post }}</h2> {% endfor %} </div> {% endblock %} So say I have data "a", "b", and "c". It would display itself as Object: a Object: b Object: c If I added d to the form, it would add Object: d What I'm hoping to do is add an increment to this so it displays itself as Object 1: a Object 2: b Object 3: c And add d as Object 4: How would I go about implementing this? Another thing I wanted to know is whether I can change the "Post:" comment next to the form. Right now my form displays itself with "Post:" at the left side. Is there … -
Django Building A Restful API
I want to build a Django Api App that allows me to render multiple variations of data. For example take a look at my code: urlpatterns = [ url(r'nav-func$', views.FundNavApi.as_view(option='nav_func')), url(r'fund_nav/(?P<fund_id>[0-9]+)$', views.FundNavApi.as_view(option='fund_nav')) ] Views.py class FundNavApi(APIView): option = 'default' model_class = NAV fund_id = None def get(self, request, format=None): if self.option == 'nav_func': res = self.nav_func print(res) elif self.option == 'fund_nav': print(self.kwargs['fund_id']) return Response("Hi") @staticmethod def nav_func(): querysets = NAV.objects.filter(fund__account_class=0, transmission=3).values( 'valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') df = read_frame(querysets, coerce_float=True) df.loc[:, 'valuation_period_end_date'] = pd.to_datetime(df.valuation_period_end_date) df.loc[:, 'timestamp'] = df.valuation_period_end_date.astype(np.int64) // 10 ** 6 df.loc[:, 'total_nav'] = df.total_nav df = df.round(0) print(df[['timestamp', 'total_nav']].values.tolist()) return df[['timestamp', 'total_nav']].values.tolist() As you can see, I want to use the same model but manipulate the data differently based on the url. So, I use the option='' parameter as a way to tell the controller what to render. So I have two questions: The nav_func function doesn't seemed to be called when res = self.nav_func is being run. The print statement isn't displaying anything. Is this the correct approach? Like is this what professionals do in terms of building an API that renders different variations of data while using one type of model? -
Django: display multiple objects on a single page
I have a lot of data from my fantasy basketball league displayed at index.html When I click a player name, I am taken to that player's single season's statistics. What I want to happen, when I click a player name, is for all of that player's career statistics to show up, not just a single year. What's the best method for going about doing that? I've been stuck on this for about two weeks now, lol Note: each 'player' object contains a separate "game_id" that belongs to each real-life player (e.g. each player object in this list of Aaron Brooks objects has the same "game_id"), but I haven't been able to figure out how to use it yet! Thanks in advance! Views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'players_list' def get_queryset(self): return Player.objects.order_by('full_name', 'season', 'team', '-ppg', 'full_name') class PlayerView(generic.DetailView): model = Player template_name = 'polls/player.html' Models.py: class Player(models.Model): def __str__(self): return self.full_name first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') full_name = models.CharField(max_length=200, default='') nba_live_id = models.IntegerField(default=0) season = models.CharField(max_length=4, default='') team = models.CharField(max_length=3, default='') pos = models.CharField(max_length=2, default='') gp = models.IntegerField(default=0) gs = models.IntegerField(default=0) ppg = models.FloatField(default=0) rpg = models.FloatField(default=0) apg = models.FloatField(default=0) spg = models.FloatField(default=0) bpg = … -
Django simple Post request is not working
I am new to Django and trying to build a simple web page. I am trying for post request but there no values getting inserted into the database.I hope the problem should be in views.py forms.is_valid() Since no logs are recorded after this line.Please assist model.py from django.db import models from django.contrib.auth.models import User from django.db.models import Q from django.forms import ModelForm from django import forms # Create your models here. class aws_cred(models.Model): aws_access_user_id = models.ForeignKey(User,null=False,related_name="aws_acc_user") access_key = models.CharField(max_length=300) secret_key = models.CharField(max_length=300) class aws(ModelForm): class Meta: model = aws_cred fields = ['access_key','secret_key','aws_access_user_id'] views.py from django.shortcuts import render_to_response,HttpResponseRedirect,render,redirect,reverse from django.contrib.auth.decorators import login_required from django.template import RequestContext from s3comp.models import aws_cred,aws import logging @login_required def fileinput(req): logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') if req.method == 'POST': form = aws(req.POST) logging.debug(form) try: logging.debug('step 4') if form.is_valid(): logging.debug('step 5') access_key_val = req.POST.get('access key','') secret_key_val = req.POST.get('secret key','') aws_access_user_id_val = req.POST.get('aws access user id', '') logging.debug(access_key_val+" " +secret_key_val+" " +aws_access_user_id_val) cred_obj = aws(access_key = access_key_val,secret_key =secret_key_val,aws_access_user_id = aws_access_user_id_val) cred_obj.save() return HttpResponseRedirect(reverse('s3comp:fileinput')) except Exception as e: logging.debug(e) else: form = aws() return render(req,'s3comp/fileinput.html',{'form':form}) html file <form action="{% url 'fileinput_home' %}" method="post"> {% csrf_token %} <p><label for="Aws access user id">User:</label><input type="text" name="Aws access user id" value={{ user.get_username … -
How can I display a model and a form under one class in views.py in Django?
I am trying to display the data in details template that I would obtain using AgentForm and I am also trying to add a Matrix1Form that will be unique to each agent, and that matrix1form would be displayed in details.html. Here is my views.py and if I try to display the Matrix1Form, the data from Agent model doesn't get displayed and vice versa, if I want to display an agent, I have to comment out the Matrix1Form. There are no errors popping up so far. The data just don't get displayed. views.py class AgentDetailsView(generic.DetailView): template_name = 'User/AgentDetails.html' class Meta: model = Agent def get(self, request, *args, **kwargs): matrix1form = Matrix1Form() return render(request, self.template_name, {'matrix1form': matrix1form}) forms.py class AgentForm(forms.ModelForm): prefix = 'agentform' class Meta: model = Agent fields = '__all__' class Matrix1Form(forms.ModelForm): prefix = 'matrix1form' class Meta: model = Matrix1 fields = '__all__' models.py class Agent(models.Model): AgencyName = models.CharField(blank=True, max_length = 50, verbose_name="Agency Name") OtherAgencyName = models.CharField(max_length=50, blank=True) FirstName = models.CharField(max_length=50, null=True) LastName = models.CharField(max_length=50, null=True) details.html <ul> <li>AgencyName: {{agent.AgencyName}} </li> <li>OtherAgencyName: {{agent.OtherAgencyName}} </li> <li>First Name: {{agent.FirstName}} </li> <li>Last Name: {{agent.LastName}} </li> </ul> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ matrix1form.as_table }} </table> </form> -
Django Rest Framework i18n works on GET but doesn't works on POST
I have API in my project and need to make some data in response translatable. So I have model: class Ticket(models.Model): NEW = 'new' CONFIRMED = 'confirmed' USED = 'used' CANCELED = 'canceled' STATUS_CHOICES = ( (NEW, _('New')), (CONFIRMED, _('Confirmed')), (USED, _('Used')), (CANCELED, _('Canceled')), ) service_subscription = models.ForeignKey(ServiceSubscription) price = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) ticket_order = models.ForeignKey(TicketOrder) begin_stamp = models.DateTimeField() status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=NEW) code = models.CharField(max_length=36, null=True, blank=True) created = models.DateTimeField(default=timezone.now) changed = models.DateTimeField(auto_now=timezone.now) processed_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True) Serializer for that case: class TicketViewSetSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() class Meta: model = Ticket fields = ('begin_stamp', 'status', 'changed') def get_status(self, obj): return obj.get_status_display() And I have viewset where I call this: class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketViewSetSerializer permission_classes = (IsAuthenticated, IsCorpMember) @list_route(methods=['get', 'post'], url_path='check/(?P<event_schedule_pk>[0-9]+)') def check_ticket(self, request, event_schedule_pk, *args, **kwargs): event_schedule = get_object_or_404(EventSchedule, pk=event_schedule_pk) data = {} status = 200 if request.method == "POST": # get ticket code code = request.data.get('code') try: ticket = self.queryset.select_for_update().filter( code=code, begin_stamp=event_schedule.start, service_subscription__data__jcontains={'id': event_schedule.event_id})[0] except IndexError: return HttpResponseNotFound(ugettext('Code invalid or ticket is not for this event')) if ticket.status == 'confirmed': ticket.status = 'used' ticket.processed_by = request.user ticket.save() else: status_msg = { 'new': ugettext('Need to be paid firstly'), 'used': ugettext(u'Already used'), … -
Creae a form from a ListView
I am trying to create a radio form type with using input based on a List object from my model team. To make it clearer I have a model team and I want my user to be able to select from one of the team that was created before. I don't thing that I am taking the right direction: views.py: class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def team_select(request): if request.method == 'POST': print("it is working") return HttpResponse('test') html: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Select one of your team and link it to your project</h2> </div> <div class="col-md-8 col-md-offset-2"> <form class="" method="post"> {% csrf_token %} {% for i in team_list %} <div class="col-md-4"> <div class="radio"> <label><input type="radio" name="optradio"> {{ i }}</label> - details </div> </div> {% endfor %} <div class="col-md-2 col-md-offset-10"> <button type="submit" class="btn btn-primary">Select</button> </div> </form> </div> </div> {% endblock %} models.py from django.db import models from registration.models import MyUser from django.core.urlresolvers import reverse # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return … -
How to redo tables without dropping it in Heroku
Every time I change columns name or length or anything, I need to drop the entire database in heroku. This is after doing makemigrations and migrate. On local, it works fine. I don't need to adjust. On heroku it's becoming to a point where I can't keep resetting. I reset by using heroku pg:reset DATABASE_URL. What is another way where I don't need to drop the entire database every single time i make an adjustment? -
How to setup URLs with subfolders in Django?
I have the following setup of links that allow me to navigate through the different URLs of my Django web app, however, I am missing something that is making my web app to throw a Page not found (404) error. This is the scenario: I have the following structure of folders and html files: personal_website (web app name) -no_results_graphs (folder) -graph_no_results.html --test_no_results_table (subfolder) --table_no_results.html -results_graphs (folder) -graph_results.html --test_results_table (subfolder) --table_results.html header.html home.html When I navigate from: graph_no_results.html -> graph_results.html = OK graph_results.html -> graph_no_results.html = OK table_no_results.html -> graph_no_results.html = OK table_no_results.html -> table_results.html = OK graph_no_results.html -> table_no_results.html = NOT OK graph_results.html -> table_no_results.html = NOT OK And I encounter the following errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graph_results/test_no_results_table/table_no_results/ Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graph_no_results/test_no_results_table/table_no_results/ The setup of the views was set as the following: url(r'^test_no_results_table/table_no_results/$',views.tickets_current_week), url(r'^test_results_table/table_results/$',views.tickets_current_week, name='current_week'), What am I missing or why my pages cannot be found? -
Two values totally different
def count_customers_per_period(self): if not self.request.GET.get('period'): period = self.request.GET['period'] entry_date_production = datetime.datetime(2017, 6, 1) start_date = CustomerProfile.objects.filter(user__date_joined__gte=entry_date_production).\ first().user.date_joined end_date = CustomerProfile.objects.last().user.date_joined @property def start_end_period(period): start = start_date - datetime.timedelta(period) end = start + datetime.timedelta(period - 1) return start, end if period == 'day': array = np.array([]).astype(int) while start < end: count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count() array = np.append(array, count) start_date += datetime.timedelta(1) elif period == 'week': array = np.array([]).astype(int) start, end = start_end_period(7) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(6) elif period == 'month': array = np.array([]).astype(int) start, end = start_end_period(months=1) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(months=1) elif period == 'year': array = np.array([]).astype(int) start, end = start_end_period(years=1) while start < end: count = CustomerProfile.objects.filter(user__date_joined__range=[start, end]).count() array = np.append(array, count) start = end + datetime.timedelta(1) end = start + datetime.timedelta(years=1) return array Analyzes the content when the period is at week : In [181]: array = np.array([]).astype(int) ...: start, end = start_end_period(7) ...: test_count = CustomerProfile.objects.filter(user__date_joined__gte=start).count() ...: while start < end_date: ...: count = CustomerProfile.objects.filter(user__date_joined__range=(start, end)).count() ...: print('The start date is {} …