Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to repair contact form?
I have a script here from an old design to a contact form and I have been unable to work for a few days. I don't know anything from Django Rest Framework and API. Could someone help me to make this script work without all of captcha. Captcha has to be removed from this script anyway. The problem is that after filling and sending the contact form I don't get the message to the email address. views.py from django.utils.translation import ugettext_lazy as _ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from visualcaptcha import Captcha, Session import os class ContactView(APIView): u"""Widok wysyłający wiadomość email""" def post(self, request): u"""Metoda wysyłająca wiadomość email. Parameters ---------- request : rest_framework.request.Request Obiekt żądania HTTP Returns ------- rest_framework.response.Response Obiekt odpowiedzi HTTP. """ assetsPath = os.path.join(settings.BASE_DIR, r'visualcaptcha', r'assets') visualCaptcha = Captcha(Session(request.session), assetsPath) frontendData = visualCaptcha.getFrontendData() imageField = request.data.pop(frontendData['imageFieldName'], None) audioField = request.data.pop(frontendData['audioFieldName'], None) captcha_valid = False if imageField is not None: captcha_valid = visualCaptcha.validateImage(imageField) if audioField is not None: captcha_valid = visualCaptcha.validateAudio(audioField) if not captcha_valid: print("hakuna matata") return Response({ 'status': 'Bad request', 'message': (_('The captcha sent was not valid')), 'errors': { … -
Django custom file storage
I am writing a dashboard web application with Django. It’s an IoT platform where users will be able to review time-series data from sensors. I am working on a feature that will allow a user to extract row data in json or csv formats. What we have is PSQL + InfluxDB for time-series. We want to have a page in UI where User would generate a file with row data and then could download it after. Also user would be able to review files created before (so we need to keep all generated files and prevent identical to be recreated). We plan to create files with python Celery task and send link to the file to user once file is created. Part we are struggling with is to find a way to write a model for a file generated. We have task which: extract row data and pass it to 2) generate python file object and pass it to 3) create and save file on the disk + create save model object Now we have following model: # models.py from orgs.models import Organization class Report(models.Model): name = models.CharField(_('file name'), max_length=128, unique=True) file = models.FileField() org = models.OneToOneField( Organization, on_delete=models.PROTECT, related_name='org', … -
Requested setting DEFAULT_INDEX_TABLESPACE ,SyntaxError
I got an error,ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So,I run command python manage.py shell & became interactive console and run django-admin.py shell --settings=app.settings.However, File "<console>", line 1 django-admin.py shell --settings=app.settings ^ SyntaxError: invalid syntax error happens.I added space between shell & --settings,same error happens,and deleted space between these,same error happen.I do not think so these is SyntaxError,but how can I fix this? -
OperationalError: 1055, "Expression #1 of SELECT list is not in GROUP BY clause
I don't get why i'm always having this error: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/loc_rad/admin_app/dashboard.py", line 29, in inquiry usage_summary_data = jsonify_result(usage_summary) File "/Users/loc_rad/admin_app/helpers.py", line 196, in jsonify_result result_dict = [a.__dict__ for a in found_entries] File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1240, in __iter__ query = iter(self.query) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 79, in __iter__ self._execute_query() File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 113, in _execute_query self.cursor.execute(self.sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 110, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue OperationalError: (1055, "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'radmin_db.RADUSAGE.ID' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by") Here is my code: def inquiry(request): current_sessions = RadOnline.objects.raw('SELECT * FROM RADONLINE LIMIT … -
Django flatpages middleware
I am unable to get the flatpages app to work correctly when using FlatpageFallbackMiddleware - it produces a 404 error when I go to /about/. Although it does display the page correctly when I remove the middleware and just hard-code the URL in to my root urls.py. Below are some of the sections of code that seem to be relevant based on what I've read so far: Site settings: SITE_ID = 1 Middleware settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'reversion.middleware.RevisionMiddleware', 'codex.core.middleware.AuditTrailMiddleware', ] The flatpage I've created: The result I get: I've tried reordering the middleware, I've tried commenting out some of the non-standard middleware to see if that was interfering with the flatpages middleware, but I still get a 404. I am happy to provide any relevant screenshots or code if anybody can point me in the right direction. Thanks. -
Django: How does model class take constructor arguments when no __init__() is defined?
In my app polls, we have the file models.py: from __future__ import unicode_literals from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) And after starting a shell with python manage.py shell, we can write this: from polls.models import Question q = Question(question_text = "What's new?", pub_date=timezone.now()) The Question class is clearly taking constructor arguments when an object is created. But in our class definition of Question in models.py, there is no specification of any constructor arguments. So how does this work? -
MultipleObjectsReturned when creating multiple objects with same name
If i create two 'box objects' (with the same name and with different users), i get an MultipleObjectsReturned at /username/slug/ get() returned more than one Box -- it returned 2! error. I have tried unique together with (user and box), but this only allows me to create one box object with one unique name. I would like every unique user to have the ability to create a Box object with the same name. example: user1 creates box object with name: 'hi', user2 creates box object with name: 'hi'. I'v also tried filtering the box objects box = Box.objects.filter(user=user, slug=slug) but i get the same result. Model User = settings.AUTH_USER_MODEL BOX_REGEX = '^[a-zA-Z0-9 ]*$' class Box(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) box_name = models.CharField( max_length=100, validators=[ RegexValidator( regex=BOX_REGEX, message='Box must only contain Alpahnumeric characters', code='invalid_box_title' )], ) slug = models.SlugField(max_length=100, blank=True) View def boxView(request, username=None, slug=None): user = get_object_or_404(User, username=username) box = get_object_or_404(Box, user=user, slug=slug) template = "pages/canvas.html" context = { 'user' : user, 'box': box, } return render(request, template, context) url url(r'^(?P<username>[\w]+)/(?P<slug>[\w-]+)/$', boxView, name='box'), -
Django: NoReverse Match with regular expressions in URL
I'm trying to make a url go to the page of a users profile. I am using (?P<pk>\d+)/$ in the urls to do this, however I am getting an error. Error: NoReverseMatch at / Reverse for 'user_profile' with no arguments not found. 1 pattern(s) tried: ['user/(?P<pk>\\d+)/$'] In template /Users/garrettlove/Desktop/evverest/templates/base.html, error at line 23 Reverse for 'user_profile' with no arguments not found. 1 pattern(s) tried: ['user/(?P<pk>\\d+)/$'] 13 14 <body> 15 16 <nav> 17 <div class="container"> 18 <a class="brand" href="{% url 'index' %}">Evverest</a> 19 20 <div class="navbar"> 21 <a class="nav-link btn" href="{% url 'index' %}">Home</a> 22 {% if user.is_authenticated %} 23 <a class="nav-link" href="{% url 'users:user_profile' %}">New Color Set</a> 24 <a class="nav-link" href="{% url 'users:user_logout' %}">Logout</a> 25 {% else %} 26 <a class="nav-link" href="{% url 'users:user_login' %}">Login</a> 27 <a class="nav-link" href="{% url 'register' %}">Register</a> 28 {% endif %} 29 </div> 30 </div> 31 </nav> 32 33 <div class="container"> It highlighted line 23 in the above code as the error. Here is my code: app urls: from django.conf.urls import url from users import views app_name = 'users' urlpatterns = [ url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'), url(r'^(?P<pk>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'), url(r'^login/$',views.user_login,name='user_login'), url(r'^logout/$',views.user_logout,name='user_logout',kwargs={'next_page':'/'}), url(r'^register/$',views.register,name='register'), ] base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>Evverest</title> <meta name"viewport" content="width=device-width, initial-scale=1"> <meta charset="uft-8"> … -
Django User Creation
I am doing a basic user creation using the built-in UserCreationForm in Django. Here is my views.py: def user_register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] raw_password = form.cleaned_data['password1'] user = User.objects.create_user(username=username) if raw_password: user.set_password(raw_password) else: user.set_unusable_password() user.save() return redirect('home') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) However, after registering a user and being redirected to home, the number of Users seen in my Admin page has not changed; no User has been created. Any idea what I am doing wrong here? -
Expecting value: line 1 column 1 (char 0) - jdnago
I have a project that i am working on and I need and i am trying to send a json request. I am getting an error and i don'y know what it means in relation to the request that i am trying to send. The following is the error: JSONDecodeError at /setup_profile/ Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://127.0.0.1:8000/setup_profile/ Django Version: 1.8.6 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\simplejson\scanner.py in _scan_once, line 118 Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Here is the request that I am trying to send: def createUserSynapse(request): url = 'http://uat-api.synapsefi.com' headers = { 'X-SP-GATEWAY' : 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv', 'X-SP-USER-IP' : '127.0.0.1', 'X-SP-USER' : '| ge85a41v8e16v1a618gea164g65', 'Contant-Type' : 'application/json', } payload = { "logins":[ { "email":"test@test.com", } ], "phone_numbers":[ "123.456.7890", "test@test.com", ], "legal_names":[ "Test name", ], "extras":{ "supp_id":"asdfe515641e56wg", "cip_tag":12, "is_business":False, } } print(url) print(headers) print(payload) call = requests.post(url, json=payload, headers=headers) # response = json.loads(call.text) call = call.json() print (call) print(call.content) return render(request, 'tabs/create_user_synapse.html', call) -
How can I get data for the earliest time on a specific day?
For example there is a field called date_published. How can I get the earliest data on a specific day? Let say, I want the earliest date_published for today... I expect the document returned is the closest one to 00:00:00 dated today. -
Python random.choices in a Django Model
Python introduced random.choices in v3.6, and now I'm trying to use a similar functionality in Django. My objective is selecting a Django object "randomly" based on weights. Solution Draft My example class: class WeightedElement(models.Model): weight = models.PositiveIntegerField() With O(1) set as an objective, I found the stochastic acceptance version of Fitness proportionate selection that looks very promising, and did: from random import random class ChoicesManager(models.Manager): def get_random(self, get_weighted_by: str) -> models.Model: queryset = super(ChoicesManager, self).get_queryset() number_of_rows = queryset.count() max_weight_object = queryset.order_by(get_weighted_by).last() max_weight = getattr(max_weight_object, get_weighted_by) while True: random_object = queryset[int(random() * number_of_rows)] random_object_weight = getattr(random_object, get_weighted_by) if random() < random_object_weight / max_weight: break return random_object Safety checks Does it work (right distribution)? I created four objects: <QuerySet [(1, 4), (2, 3), (3, 12), (4, 1)]> That should give this distribution: {1: 2000, 2: 1500, 3: 6000, 4: 500} And I got: {1: 1926, 2: 1526, 3: 6044, 4: 504} Does it perform? I did timeit giving me: 0,0013149236337946007 per number obtained Populating the DB with ten thousand random weights from zero to one hundred, I got: 0,005099541511962798 per number obtained My doubts Is a manager the right place for doing this? Is there a way to reduce DB queries? -
What is the best way to migrate an old django db to a new schema?
I have a django project and its db full of data. I updated the project and changed the models a lot but I was working locally on a new fresh test db. Now I need to migrate the new project to the existing old db to change the schema. Is there a good clean way to do this? -
models.ForeignKey field not showing up in the browsable API.
I have two models(Requests/ Events) that have foreign keys back to the user model. When trying to post with foreign key data using Django Rest Framework, I am receiving a null constraint error. It seems django is not accepting the user_id(requester_id/event_admin_id) references. In the browsable API the foreign key sections(requester_id/event_id) are not present. Is it being hidden by something? Note that event_participant is made up of only Foreign Keys but they appear in the browsable API when posting. I'm not sure what could be the difference Missing event_admin_id foreignkey field Missing request_admin_id fk field models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): user_job_description = models.CharField(max_length = 200) user_profile_pic = models.ImageField(null = True, blank = True) class Event(models.Model): def __str__(self): return self.event_name event_name = models.CharField(max_length = 100) event_location = models.CharField(max_length = 100) event_description = models.TextField(max_length = 300) admin_user_id = models.ForeignKey(User, related_name = 'event_admin') class Request(models.Model): def __str__(self): return self.request_desc requester_user_id = models.ForeignKey(User, related_name = 'requests') request_desc = models.TextField(max_length = 100) fulfiller_user_id = models.IntegerField(null = True, blank = True) fulfilled_status = models.BooleanField() class Event_Participant(models.Model): def __str__(self): return str(self.event_id) user_id = models.ForeignKey(User, related_name = 'event_attendee') event_id = models.ForeignKey(Event, related_name = 'event') serializers.py from django.contrib.auth import … -
Using generic relations in forms
My models.py has: from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class Category(models.Model): name = models.CharField( max_length=100 ) parent = models.ForeignKey('self', null=True, related_name='children') slug = models.SlugField(unique=True) class Institution(models.Model): name = models.CharField(max_length=300, null=False) city = models.CharField(max_length=100, null=False) country = models.CharField(max_length=100, null=False) class Author(models.Model): name = models.CharField(max_length=150, null=False) degree = models.CharField(max_length=150, null=False) degree_completed = models.BooleanField(default=False, null=False) class Article(models.Model): name = models.CharField(max_length=300, null=False) uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) highlights = models.FileField(upload_to='user_uploads/%Y/%m/%d/') word_document = models.FileField(upload_to='user_uploads/%Y/%m/%d/') pdf_document = models.FileField(upload_to='user_uploads/%Y/%m/%d/') #Implementing generic relations content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField(default=None) content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.name My class Article has generic foreign relations with other classes. Now I want to use this Article class to create a form which would include all other classes. As in the documentation, I could use generic_inlineformset_factory to do that but I also needed to create forms for other classes to show up in my template. My views.py has: def submitArticle(request): current_user = request.user ArticleUploadForm = generic_inlineformset_factory( Article, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field='content_type', fk_field='object_id', extra=1) if request.method == 'POST': article_formset = ArticleUploadForm(request.POST, request.FILES, instance=current_user) if article_formset.is_valid(): article_formset.save() #Temporary redirect to homepage return render(request, 'personal/home.html') else: #Need to add error here article_formset = … -
Groupping and aggregating on django model related records
I'm learning Django, and I'm facing a little issue: I have a model which has related rows, and I'd like to get the sum of a column of the related rows grouping by the value of a second column. The model's I'm working with are the following: class Integrante(models.Model): nombre = models.CharField(max_length=80, db_index=True) class EstadoCuenta(models.Model): num_edc = models.PositiveIntegerField(validators=[MinValueValidator(1),]) fecha_edc = models.DateField(null=True, db_index=True) class Movimiento(models.Model): TIPOS_MOVIMIENTO = ( # Choices for column 'tipo' ) estado_cuenta = models.ForeignKey(EstadoCuenta, on_delete=models.CASCADE) integrante = models.ForeignKey(Integrante, on_delete=models.CASCADE) fecha = models.DateField(db_index=True) tipo = models.SmallIntegerField(db_index=True, choices=TIPOS_MOVIMIENTO) descripcion = models.CharField(max_length=200, blank=True) importe = models.DecimalField(max_digits=8, decimal_places=2) I've tried the following: edc = EstadoCuenta.objects.filter(grupo__nombre_grupo='A group').latest() edc.movimiento_set.values('integrante').annotate(Sum('importe')) However, I'm getting the following result: for x in edc.movimiento_set.values('integrante').annotate(Sum('importe')): print(x) # {'integrante': 28, 'importe__sum': Decimal('-20.00')} # {'integrante': 28, 'importe__sum': Decimal('23.00')} # {'integrante': 28, 'importe__sum': Decimal('9.60')} # {'integrante': 28, 'importe__sum': Decimal('20.00')} # {'integrante': 28, 'importe__sum': Decimal('-0.60')} # {'integrante': 24, 'importe__sum': Decimal('96.00')} # {'integrante': 24, 'importe__sum': Decimal('28.80')} # {'integrante': 24, 'importe__sum': Decimal('48.00')} # {'integrante': 24, 'importe__sum': Decimal('28.80')} # {'integrante': 24, 'importe__sum': Decimal('96.00')} # {'integrante': 24, 'importe__sum': Decimal('48.00')} # {'integrante': 24, 'importe__sum': Decimal('288.00')} # {'integrante': 24, 'importe__sum': Decimal('144.00')} # {'integrante': 24, 'importe__sum': Decimal('19.20')} # {'integrante': 24, 'importe__sum': Decimal('-510.00')} # {'integrante': 24, 'importe__sum': Decimal('48.00')} # {'integrante': 24, 'importe__sum': … -
Django creating model that contains models selected from multiple choice field
I'm trying to create a way for someone to select and then post multiple instances of a model called Shift. How I want it to work is for the user to enter their user_id and then they will select the shifts that are attributed to their user_id, which will create an instance of the model called Post. Here are my models: class Shift(models.Model): user_id = models.IntegerField(blank=True) start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() class Post(models.Model): shift = models.ForeignKey(Shift) Then I have a form where they enter their user_id, and a form where they select their shifts: class PostForm(forms.Form): user_id = fields.IntegerField() class PostCreate(forms.ModelForm): shift=forms.ModelChoiceField(queryset=Shift.objects.none(),widget=forms.CheckboxSelectMultiple) class Meta: model = Post fields = ['run'] Here is a part of my views.py: def post_create(request): form = PostForm(request.POST) if form.is_valid(): instance = form.cleaned_data return post_creator(request, instance) context = {"form": form} return render(request, "post.html", context) def post_creator(request, id): queryset_list = Shift.objects.filter(user_id = id['user_id']) form = PostCreate(request.POST) form.fields['shift'].queryset = queryset_list if form.is_valid(): instance = form.save(commit=False) instance.save() # go to list of posted shifts context = {"form": form, "object_list": queryset_list} return render(request, "select.html", context)` I'm able to get the user to input their user id and then a list of their assigned shifts with check boxes next to … -
django - displaying each individual user's comment count on a post_detail template
I have my comments set up where users can review blog posts and have those reviews show up fine in the post_detail.html template. What I would like to do is to get the total amount of comments for every user, and display that right next to his/her comments on any one of their comments (in any post). So for example I'd like it to say "user 1: 4 comments", and so on for each user based on the amount of comments that they left. I'd also like that if user 1 has left 4 comments on 4 different posts, if I go to each one of those posts and look at the comments, on all of them I would like to see "user 1: 4 comments". models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') ... def user_rating_count(self): user_ratings = Comment.objects.filter(user=2).count() return user_ratings ... class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments") user = models.ForeignKey(User, related_name="usernamee") ... review_count = models.IntegerField(default=0) views.py @login_required def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post # Makes the post linked to the comment comment.user = request.user # Makes the user linked to the comment comment.email … -
Django: NoReverse Match error and page not found
I've gotten the NoReverse Match error before and I got it to work with a blind guess. and page not found I've always been able to fix so I'm really not sure what is going on. As far as I can tell everything should be working correctly, and I even compared this code to a previous project and it looks fine (I have been tinkering with it so it may not be exactly what I originally typed in). base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>Evverest</title> <meta name"viewport" content="width=device-width, initial-scale=1"> <meta charset="uft-8"> <link rel="shortcut icon" href="/images/favicon.ico"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <nav> <div class="container"> <a class="brand" href="{% url 'index' %}">Evverest</a> <div class="navbar"> <a class="nav-link btn" href="{% url 'index' %}">Home</a> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a> <a class="nav-link" href="{% url 'users:user_logout' %}">Logout</a> {% else %} <a class="nav-link" href="{% url 'users:user_login' %}">Login</a> <a class="nav-link" href="{% url 'users:register' %}">Register</a> {% endif %} </div> </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> app views.py from django.shortcuts import render from users.forms import UserForm,UserProfileForm from users.models import UserProfileInfo from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from … -
ChoiceField: choices are formed only at Django start
Django 1.11.4 My code is below. The problem is that it executes only once: at the Django start. I'd like people to renew when the web page is reloaded. Could you help me with this? def get_people_choices(): people = Person.objects.all() choices = [(None, "----")] choices += [(person.id, person) for person in people] return choices class SearchForm(forms.Form): person_choice = forms.ChoiceField(label='', choices=get_people_choices(), required=False) -
Implementing 2FA in django
I am working with someone in implementing the 2FA on a django project. I came across this link for django 2FA implementation. Does anyone have experience with the package i.e. how reliable it is or is there a better alternative available? -
Django: javascript needs to call a python script, what location do I put it in?
I get really confused about django and file locations a lot, and I'm on django 1.10. But in my static/(django-proj-name)/js/ folder (just showing the way I have my main.js file and I need to call a python script, in conjunction with the jquery tokeninput plugin. Lets call the script keywords.py This script is going to need to call all instances of a model, Keyword, so I need to be able to import from my models file. Im' a bit inexperienced with django, but from reviewing some of the projects I've seen over the summer I was startinng to believe that including the line, from (django-proj-name).models import * was the main way to import from models. This at least works for all of the files that I have in my /management/commands/ folder. But i tried putting keywords.py in my static folder just because I know at the very least I can use the {% static %} template tag to find the file in html. I ran the file without manage. Traceback (most recent call last): File "../../management/commands/import_statements.py", line 5, in <module> from gtr_site.models import * ImportError: No module named gtr_site.models Though I have the same importation line, again, in /management/commands/. And … -
Django Queryset ORM issue with string
I try compare string from AJAX Request with data( name ) at my Database, but my queryset don't working: def create_name(request): if request.method == 'POST': name = request.POST['name'] for i in Name.objects.all(): if i.name != name: Name.objects.create( name=name, ) return HttpResponse(status=200) Comparing don't working and name will storing at my DB. Thanks in advance! -
Django paypal IPN how to get data
I've a piece of code where I need to get data and send it via POST request to my webhook. It looks like class PaymentProcess(TemplateView): template_name = 'users/payment_form.html' def get_context_data(self, **kwargs): context = super(PaymentProcess, self).get_context_data(**kwargs) host = self.request.get_host() paypal_dict12 = { "business": env('PAYPAL_RECEIVER_EMAIL', default=""), "amount": "%s" % 30, "item_name": "Month Membership %s" % 12, "invoice": "%s-%s" % (timezone.now(), 12, ), "currency_code": "EUR", "notify_url": "http://%s%s" % (host, reverse('paypal-ipn')), "return_url": "http://%s%s" % (host, reverse('users:done')), "return": "http://%s%s" % (host, reverse('users:done')), "rm": "2", "cancel_return": "http://%s%s" % (host, reverse('users:canceled')), "custom": "%s %s %s" % (self.request.user.id, 30, 12), } context['pay_form12'] = PayPalPaymentsForm(initial=paypal_dict12) paypal_dict6 = { "business": env('PAYPAL_RECEIVER_EMAIL', default=""), "amount": "%s" % 18, "item_name": "Month Membership %s" % 6, "invoice": "%s-%s" % (timezone.now(), 6,), "currency_code": "EUR", "notify_url": "http://%s%s" % (host, reverse('paypal-ipn')), "return_url": "http://%s%s" % (host, reverse('users:done')), "return": "http://%s%s" % (host, reverse('users:done')), "rm": "2", "cancel_return": "http://%s%s" % (host, reverse('users:canceled')), "custom": "%s %s %s" % (self.request.user.id, 18, 6), } # Create the instance. context['pay_form6'] = PayPalPaymentsForm(initial=paypal_dict6) return context I've a request for a data, using 'rm' (https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#paypal-checkout-page-variables) @method_decorator(csrf_exempt, name='dispatch') class PaymentDone(LoginRequiredMixin, TemplateView): template_name = 'users/payment_done.html' def post(self): params = self.request.POST requests.post('https://polar-basin-23006.herokuapp.com/', params=params) It doesn't work. If you can help me, please write your recommends. Thanks! -
Atom Editor Django model autocomplete db model field types
I like using Atom for Django projects and most of the autocomplete is working as well as linting but .... I would thing the the type of the model fields could be autocompleted for example: name = models.***CharField***(max_length=256) age = models.***PositiveIntegerField***() school = models.***ForeignKey***(School, related_name='students') is there a plugin that autocompletes these db filed types?