Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate column name when migrating Django database
I am trying to migrate my database: E:\PhytonProgects\natarelke>python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, catalog, contenttypes, main, ordering, registration, sessions, users Running migrations: Rendering model states... DONE Applying catalog.0002_auto_20170219_2146...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 356, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 132, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 237, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 409, in β¦ -
Migrate form to modelform
I wrote following form: class VoteForm(forms.Form): choice = forms.ModelChoiceField(queryset=None, widget=forms.RadioSelect) def __init__(self, *args, **kwargs): question = kwargs.pop('instance', None) super().__init__(*args, **kwargs) if question: self.fields['choice'].queryset = question.choice_set class VoteView(generic.UpdateView): template_name = 'polls/vote.html' model = Question form_class = VoteForm def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).exclude(choice__isnull=True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Check duplicate vote cookie cookie = self.request.COOKIES.get(cookie_name) if has_voted(cookie, self.object.id): context['voted'] = True return context def get_success_url(self): return reverse('polls:results', args=(self.object.id,)) def form_valid(self, form): redirect = super().form_valid(form) # Set duplicate vote cookie. cookie = self.request.COOKIES.get(cookie_name) half_year = timedelta(weeks=26) expires = datetime.utcnow() + half_year if cookie and re.match(cookie_pattern, cookie): redirect.set_cookie(cookie_name, "{}-{}".format(cookie, self.object.id), expires=expires) else: redirect.set_cookie(cookie_name, self.object.id, expires=expires) return redirect The problem is that the normal form does not represent a object, like ModelForm and does not have the save() method. But I can't figure out how to migrate the form. There is no choice or choice_set field: class VoteForm(forms.ModelForm): class Meta: Model = Question #throws exception fields = ('choice',) widgets = { 'choice': forms.RadioSelect() } How can the form from above be reproduced as a model form? -
Django Crispy Form Submit Button
I am trying to use Crispy Forms to make my forms look good. I have the following in my forms.py: from django import forms from .models import Team from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions) class CreateTeamForm(forms.ModelForm): class Meta: model = Team fields = [ 'Project_name', 'Project_number' ] helper = FormHelper() helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' Then in my views.py: def create_team(request): if request.method == 'POST': form = CreateTeamForm(request.POST, request.FILES) if form.is_valid(): form.save() return render('/teams/my_team.html',{''}) else: form = CreateTeamForm() return render(request, 'teams/team_form.html', {'form':CreateTeamForm()}) And finally in my template: {% extends "main/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="jumbotron"> {% crispy form %} </div> </div> {% endblock %} However, my submit button that I called isn't being displayed. I have read the cripsy form documentation and I can't seem to find anything wrong with my implementation. Everything except for the submit button is displayed. Any ideas? -
Default isolation level for transaction (@atomic) with Django and PostgreSQL
I was wondering what's the default isolation level when using Django with PostgreSQL database. Serializable Isolation? (https://www.postgresql.org/docs/9.1/static/transaction-iso.html#XACT-SERIALIZABLE) There is a discussion about MySQL (Django transaction isolation level in mysql & postgresql) but despite its name is doesn't seem to discuss PostgreSQL Thanks! -
Django Rest Framework RetrieveAPIView provide object name
I have some simple serializers class TagSerialzier(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class PostSerializer(serializers.ModelSerializer): tags = TagSerialzier(many=True, read_only=True) url = serializers.URLField(source='get_absolute_url') class Meta: model = Post fields = '__all__' extra_kwargs = {'url': {'lookup_field': 'slug'}} And what should be some fairly straightforward API views class PostList(generics.ListAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.prefetch_related('tags') renderer_classes = (TemplateHTMLRenderer,) template_name = 'blog/post_list.html' pagination_class = StandardResultsSetPagination class PostDetail(generics.RetrieveAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.prefetch_related('tags') renderer_classes = (TemplateHTMLRenderer,) template_name = "blog/post_detail.html" lookup_field = 'slug' I want to be able to reuse code in my templates so I have something like the following blog/post_list.html {% for post in results %} {% include "bog/post.html" %} {% endfor %} blog/post.html {{ post.title }} {{ post.subtitle }} {% for tag in post.tags %} {{ tag.name }} {% endfor %} I'm running into problems when I try to reuse this code in the template rendered by the PostDetail view. Since the view returns a single object I'm forced to render everything as follows blog/post_detail.html {{ title }} {{ subtitle }} {% for tag in tags %} {{ tag.name }} {% endfor %} So I made some attempts to alter the PostDetailView to return the post object wrapped in a β¦ -
send django message from a template file
Is it possible to set message using django message framework from inside a template file? {% if not userIsLoggedIn %} <a href="{% url 'login' %}" class="btn btn-primary">Buy</a> {# I want to send message to the user who click this buy button on the login page #} {% elif not game_bought and game.price != 0 %} <form action="/buy" method="POST"> <input class="btn btn-primary" type="submit" value="Buy"> </form> {% endif %} I can think of a hackish way of doing it by using query string, but it would be nice if I could use django's message framework. -
Serializing a Django form using django-rest-framework-braces
I have written a form in Django and I want to pass this form to my front-end client in JSON format. I am using django-rest-framework to serialize my models but I do not know how I can serialize my form with this framework. I have found https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#forms as the solution in here: Serialize from a Django form, but I do not know how to use the package to get the JSON formatted form out of it. I would appreciate any guidance. Thanks, -
how do i validate unique mobile no in the seller model in Django
i am trying to validate mobileno(unique) of model seller. but it giving me error and not doing desired task. what should i do so that uniqueness of mobileno is checked in the forms ? following is my model.py class Seller(models.Model): mobilenno = models.DecimalField(max_digits=10, decimal_places=0, unique=True) # Field name made lowercase. password = models.CharField(max_length=64) name = models.CharField( max_length=64) # city = models.ForeignKey(City) address = models.CharField(max_length=512, blank=True, null=True) # Field name made lowercase. phoneno = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. and form.py class SellerRegistrationForm(forms.Form): mobileno1 = forms.DecimalField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), max_digits=10, decimal_places=0,label=_("Mobile Number")) password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)")) name = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Seller Name")) address = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Seller Address")) phoneno = forms.DecimalField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), max_digits=10, decimal_places=0, label=_("Phone Number")) def clean_mobileno1(self): try: Seller.objects.get(mobileno=self.cleaned_data['mobileno1']) except Seller.DoesNotExist: return self.cleaned_data['mobileno1'] raise forms.ValidationError(_("The mobilenumber already exists. Please try another one.")) def clean(self): if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_("The two password fields did not match.")) return self.cleaned_data views.py def seller_register(request): if request.method == 'POST': form = SellerRegistrationForm(request.POST) if form.is_valid(): Seller.objects.create( mobilenno=form.cleaned_data['mobileno1'], password=form.cleaned_data['password1'], name=form.cleaned_data['name'], address=form.cleaned_data['address'], phoneno=form.cleaned_data['phoneno'] ) return HttpResponseRedirect('/register/success/') else: form = SellerRegistrationForm() return render(request,'registration/register.html', {'form': form }) -
django can not get datetime field year
I have a model like: class Day(models.Model): day = models.DateField(default=datetime.datetime.today) class Attendance(models.Model): employee = models.ForeignKey(Employee) days = models.ManyToManyField('Day') def __unicode__(self): return self.employee.full_name in my template I am sending only date a context like at = Attendance.objects.get(id=2) return render(request, "attendance.html", {'at': at.days}) in my template I am doing : {% for day in at %} {{day|date:'%d'}} {%endfor%} But I am not getting date or day or anything.. Why is this ?? What is the error ?? -
Django: Use other model classes as choices for a field
I'm writing a Django app that includes a poll section, and I want to offer the ability to create different types of questions. So, I have these models for the rating part # Do I really need this class? class BaseRating(models.Model): class Meta: abstract = True # For questions like: "Rate your experience with XXXXX" class FiveStarRating(BaseRating): rating = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MaxValueValidator(5)]) # For questions like: "Would you recommend XXXXX"? class YesNoRating(BaseRating): rating = models.BooleanField() I now want to create a new question, and I want to specify the rating system for it: If I create the question "How would you rate xxxxx", I'd use FiveStarRating model If I create the question "Are you satisfied with xxxx", I'd use YesNoRating So, how should I design the question model? class Question(models.Model): title = models.CharField(max_length=255) # I can't create a foreignkey field to the base class... -
Concurrent requests in The App Engine Standard Environment
I'm using Django 1.10.5 on The App Engine Standard Environment python27 runtime. My app.yaml looks like: runtime: python27 api_version: 1 threadsafe: true instance_class: F4_1G automatic_scaling: min_idle_instances: 1 max_idle_instances: automatic # default value max_concurrent_requests: 8 # default value max_pending_latency: 30ms # default value - url: /.* script: myapp.wsgi.application secure: always So I use wsgi, which supports threads, and threadsafe is true. I'm doing simple stress test with https://github.com/rakyll/hey and get very suspicious results 2 concurrent requests hey -more -c 2 -n 100 -m GET https://<test-app-url>.appspot.com Response time histogram: 0.074 [1] |β 0.214 [62]|ββββββββββββββββββββββββββββββββββββββββ 0.354 [20]|βββββββββββββ 0.495 [6] |ββββ 0.635 [6] |ββββ 0.775 [4] |βββ 0.916 [0] | 1.056 [0] | 1.197 [0] | 1.337 [0] | 1.477 [1] |β 8 concurrent requests hey -more -c 8 -n 100 -m GET https://<test-app.appspot>.appspot.com Response time histogram: 0.083 [1] |β 0.590 [74]|ββββββββββββββββββββββββββββββββββββββββ 1.098 [11]|ββββββ 1.605 [6] |βββ 2.112 [0] | 2.619 [2] |β 3.127 [1] |β 3.634 [0] | 4.141 [0] | 4.649 [0] | 5.156 [1] |β How can I control/monitor/debug threads behaviour? The only setting I know is max_concurrent_requests: 8 (only available while using automatic_scaling), does this mean max 8 threads per instance? How can I control threads per instance in basic/manual β¦ -
How to structure a many to many django model with
I have a issue with how to structure my django model. I have a User model and an Account model. The User can be in multiple accounts. Each User should have a key for each Account. I want to be able to get the key associated with the account and user combination. User 1 is in Account A and B. If I query for Account A and User 1 I should get key1 and if I query for B and 1 I should get key2. keys = {AccountA: key1, AccountB: key2} I'm just confused on how I can store this data. I know I could serialize json and store as a Text Field. But I think that will be messy. I want to be able to regenerate the keys if needed. What is the class User(models.Model): accounts= models.ManyToManyField(Account) keys = models.TextField() OR class User(models.Model): accounts= models.ManyToManyField(Account) keys = models.ManyToManyField(AnotherModel?) Something else? Caveats: I cant use hstore or jsonfield. I'm on django 1.7 -
Python - Creating new model objects leads to updating previously created objects
I'm using Django to create a model called CampaignProfile, then each logged in user can fill in a form to build such an object, and have all of their 'CampaignProfile's displayed on their personal dashboard. What I've found is that when I fill in this form then a new CampaignProfile object is not created like I need, but instead the information entered (title, etc) replaces the first CampaignProfile made. I'm struggling to understand why the model object is being updated as opposed to creating a new object. Models.py: def get_file_name(instance, filename): return ('uploads/%s_%s' % (str(time())).replace('.','_'), filename) class CampaignProfile(models.Model): user = models.OneToOneField(UserModel, related_name='campaignprofile', on_delete=models.CASCADE, null=True) campaign_title = models.CharField(max_length=50, verbose_name='Title') campaign_dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') campaign_dt_updated = models.DateTimeField(auto_now=True, verbose_name='Date Updated') campaign_docs = models.FileField(upload_to=get_file_name, verbose_name='Files', blank=True, null=True) slug = models.SlugField(unique=True, blank=True) class Meta: verbose_name = 'Campaign Profile' def __str__(self): return 'Campaign Title: ' + self.campaign_title + ' - ' + str(self.user) def save(self, *args, **kwargs): if self.user is None: # Set default reference self.user = UserModel.objects.get(id=pk) super(CampaignProfile, self).save(*args, **kwargs) Forms.py class NewCampaignForm(forms.ModelForm): campaign_title = forms.CharField(min_length=1, max_length=80, label='Campaign Name', required=True, widget=forms.TextInput(attrs={'autofocus':'autofocus'})) campaign_docs = forms.FileField(label='Attach .png and .docx files to your campaign', required=False, widget=forms.ClearableFileInput(attrs={'id':'fileupl'})) class Meta: model = CampaignProfile fields = ['campaign_title', 'campaign_docs'] def clean(self): β¦ -
Handling Response Object from Django/JQuery to javascript Urllib3
I need to download the headlines from BBC and using Ajax and jquery in Django. Im currently trying to use Urllib3, to create a request to get the RSS/XML Top News data from the BBC website found at the following: 'http://feeds.bbci.co.uk/news/rss.xml' I have created the request I believe, but when the returned object pass it back to my HTML/Javascript it doesn't work and I get the following error. the object I pass through the window.onload method is: upon_success({{ AllNews }}) and gives me the error 'Uncaught SyntaxError: Unexpected token &' My HTML and Views.py: from django.shortcuts import render import urllib3 import urllib3.request import json def index(request): http = urllib3.PoolManager() r = http.request('GET', 'http://feeds.bbci.co.uk/news/rss.xml') xml_news = r context = {'AllNews': xml_news} return render(request, 'home/NewsHome.html', context) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="application/javascript"> function upon_success (xml) { alert('ok'); xml.find('item').each(function(){ var title = $(this).find('title').text(); msg =+ "<li> " + title + " </li>" $("#AllNews ul").append(msg) } )}; {% if AllNews %} window.onload = upon_success({{ AllNews }}); {% endif %} </script> </head> <body> <h1>Top News: BBC versus CNN</h1> <ul id="AllNews"></ul> </body> </html> i don't understand how to pass the response object back to the Javascript so that i can try to extract the β¦ -
django rest-farmework nested relationships to pass parameters
Using django rest-farmework to implement the API,There is a problem has been unable to solve: How to pass parameters through the view.py to serializers.py? the specific code is as follows: models.py class Category(models.Model): name = models.CharField(max_length=30) amount = models.IntegerField() class Source(models.Model): name = models.CharField(max_length=50) rss_link = models.URLField() amount = models.IntegerField() # ForeignKey category = models.ForeignKey(Category) views.py class CategoryListView(APIView): def get(self, request): # How should this variable be passed to serializers.py? num_parameter = request.GET.get("num") category = Category.objects.all() serializers = CategorySerializers(category, many=True) return Response(serializers.data) serializers.py class SourceSerializer(serializers.ModelSerializer): class Meta: model = Source fields = ("id","name","amount") class CategorySerializer(serializers.ModelSerializer): source_set = serializers.SerializerMethodField('get_sources') def get_sources(self, category): sources = category.source_set.filter(amount=0) # I expect the code as follows,the "num_parameter" from views.py # sources = category.source_set.filter(amount=num_parameter) return SourceSerializer(instance=sources, many=True).data class Meta: model = Category fields = ("id", "name", "amount", "source_set") Program running resultsοΌ [ { "id": 1, "name": "study", "amount": "0", "source": [ { "id": 34, "name": "java", "amount": "0" }, { "id": 35, "name": "python", "amount": "0" } ] } ] As annotated, modified the following codeοΌ sources = category.source_set.filter(amount=0) to sources = category.source_set.filter(amount=num_parameter) the "num_parameter" is from "CategoryListView", How to pass it to "CategorySerializer"? Thanks in advance. -
django date field get day of a week like sunday monday
I have a DateField in django whose default value is set to timezone.now How can I get the week of the day. I mean the day is either sunday or monday or other ?? -
django security and user control
how to prevent people from editing post and publishing and approving and deleting post of other people who are logined in the system in django.i am creating a forum where anyone can post question.i need help to control users who are already registered in the system this my post_deatil.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% else %} {% if id.is_authenticated %} <a class="btn btn-primary" href="{% url 'post_publish' pk=post.pk %}">Publish</a> <a class="btn btn-danger" href="{% url 'post_remove' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <a class="btn btn-success" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> {% endif %} {% endif %} <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> <hr> <a class="btn btn-info" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a> {% for comment in post.comments.all %} {% if user.is_authenticated or comment.approved_comment %} <div class="comment"> <div class="date"> {{ comment.created_date }} {% if not comment.approved_comment %} <a class="btn btn-danger" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <a class="btn btn-success" href="{% url 'comment_approve' pk=comment.pk %}"><span class="glyphicon glyphicon-ok"></span></a> <a href="javascript:history.go(-1)" button type="button" class="btn btn-primary">Cancel</a> {% endif %} </div> <strong>{{ comment.author }}</strong> <p>{{ comment.text|linebreaks }}</p> </div> {% endif %} {% empty %} <p>No comments here yet:</p> {% endfor β¦ -
Saving a matrix as an Image in django and displaying it
I took image from user through Imagefield in a django powered website. I performed some kind of operation like rotating a image. Now I would like to display this rotated image in the website. What's the most efficient way and how? -
change dropdown variant to radioselect
I want to change dropdown variant to radioselect. i forked basket app to my project. then override _create_parent_product_fields. but not work from oscar.apps.basket.forms import * class AddToBasketForm(forms.Form): # quantity = forms.IntegerField(initial=1, min_value=1, label=_('Quantity')) # Dynamic form building methods def _create_parent_product_fields(self, product): """ Adds the fields for a "group"-type product (eg, a parent product with a list of children. Currently requires that a stock record exists for the children """ choices = [] disabled_values = [] for child in product.children.all(): # Build a description of the child, including any pertinent # attributes attr_summary = child.attribute_summary if attr_summary: summary = attr_summary else: summary = child.get_title() # Check if it is available to buy info = self.basket.strategy.fetch_for_product(child) if not info.availability.is_available_to_buy: disabled_values.append(child.id) choices.append((child.id, summary)) self.fields['child_id'] = forms.ChoiceField( choices=tuple(choices), label=_("Variant"), widget=forms.RadioSelect ) -
Django unable to redirect when link is clicked
In my template I have the following: {% block content %} {% for category in categories %} {% url 'post' category as url %} <a href="{{ url }}"> <div class="card"> <img src="" alt="Avatar"> <div class="container"> <h4><b>{{ category }}</b></h4> </div> </div> </a> {% endfor %} {% endblock %} The page renders fine when I run the local development server, however when I click on any of the links, nothing happens. Here is my urls.py file: urlpatterns = [ url(r'^all/', views.all_jobs, name="all"), url(r'^post/', views.pick_category, name="post_category"), url(r'^post/(?P<category>[a-zA-Z]+)/$', views.post_job, name="post"), url(r'^job/(?P<job_pk>\d+)/$', views.get_job, name="get_job"), ] Why is this not working? Thanks in advance. -
permissions.AllowAny DRF
I am using Django, DRF and Angular. Since I started working on my API I have been managing to connect and retrieve data from my db to Angular. All of a sudden today I started getting a 401 unauthorized error. In my settings.py under REST_FRAMEWORK I have this: 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), So at first I thought It was because I was logged out of the admin section of django so I logged in but nothing changed. IN responce to this I changed the line of code above to this: 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',), After this I can now get access to the data and the API is returning information fine. Question Is there harm in setting permissions.AllowAny? What potential problems might this expose me to? Furthermore, can anyone possibly provide me with possible reasons why all of a sudden I am getting the 401 unauthorized error. Fiddler gives me this extra information {"detail":"Authentication credentials were not provided."} -
How using form in ListView Django?
I'm trying to create an action for the ListView, the action will be to delete or to change a parameter in the table in my model, for example, disable user, using checkbox. If I selected all them and click this botton, It'll be delete all selected. **views.py class AccountsManagementView(LoginRequiredMixin, generic.ListView): """ Class Based View para a manipulaΓ§Γ£o de usuΓ‘rios. """ model = User template_name = 'accounts/accounts_management.html' context_object_name = 'users' def get_queryset(self): return User.objects.all() class DeleteUser(DeleteView): model = User success_url = reverse_lazy('accounts:accounts_manager') **urls.py urlpatterns = [ # ListView dos Usuarios url(r'^$', views.accounts_management, name="accounts_manager"), # Deletar Usuario url(r'^(?P<pk>\d+)/deleteuser/$', views.delete_user, name="delete_user"), # Add Usuario url(r'^adicionar_usuario/$', views.accounts_form, name="accounts_form"), # Update Usuario url(r'^editar/(?P<username>[\w_-]+)/$', views.account_edit, name="accounts_edit"), # Visualizar perfil usuario url(r'^visualizar/(?P<username>[\w_-]+)/$', views.account_view, name="accounts_view"), ] templates/accounts_management.html <form action="" method="post"> <div class="panel panel-default"> <div class="panel-heading"> <div class="panel-title"> <a href="{% url 'accounts:accounts_form' %}"><button type="button" class="btn btn-success mb_sm"> <i class="fa fa-user-plus" aria-hidden="true" aria-hidden="true"></i> Add User </button></a> <button type="button" class="btn btn-danger mb_sm"> <i class="fa fa-user-times" aria-hidden="true" aria-hidden="true"></i> Del User </button> </div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped" id="datatables__example"> <thead> <tr> <th scope="col" class="-colaction-checkboxumn"> <span> <input type="checkbox" name="account-users" id="action-toggle" hidden="hidden"/> <label for="action-toggle"></label> </span> </th> <th>Foto</th> <th>Nome</th> <th>UsuΓ‘rio</th> <th>Grupo</th> <th>E-mail</th> <th>Status</th> <th>Ativo</th> <th>AΓ§Γ΅es</th> </tr> </thead> <tbody> {% for usuario in users β¦ -
Data time comparing error Python and Django
Hi i trying to compare times and date from db and utc I have next code: order.total_time = datetime.utcnow() order.pay_time = order.total_time + timedelta(hours=12) order.save() then i take value from db i try to compare with UTC: time_left = datetime.utcnow() - timedelta(hours=1) if order.pay_time > time_left: #do someting and recive and error can't compare offset-naive and offset-aware datetimes -
Store the counts of children models in parent model
I have a parent and child class class parent(models.model): countChidlren = #count of the total children of this parent class childeren(models.model): parent = models.ForeignField(parent) I want to have the count of the childeren in parent but don't have any idea on how to go about it.? -
Could not find a version that satisfies the requirement tensorflow==1.0.0 in Heroku
I am deploying a django project using heroku cloud platform. I have added the dependencies in requirements.txt file. However when I push to heroku master, I get the following error: Collecting tensorflow==1.0.0 (from -r /tmp/build_bc8be989466414998410d3ef4c97a115/requirements.txt (line 17)) remote: Could not find a version that satisfies the requirement tensorflow==1.0.0 (from -r /tmp/build_bc8be989466414998410d3ef4c97a115/requirements.txt (line 17)) (from versions: ) remote: No matching distribution found for tensorflow==1.0.0 (from -r /tmp/build_bc8be989466414998410d3ef4c97a115/requirements.txt (line 17)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to what-the-image. remote: I am using Django v 1.10 and python 2.7. Where would I be going wrong?