Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO_SETTINGS_MODULE not recognizing my base module when starting a new project with Virtualenvwrapper
I am starting a new Django project with virtualenvwrapper, and for some reason django-admin does not recognize my settings module: $ mkproject djangotest (djangotest) $ pip install Django Collecting Django Using cached Django-2.0-py3-none-any.whl Collecting pytz (from Django) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, Django Successfully installed Django-2.0 pytz-2017.3 (djangotest) $ django-admin The above command works and gives me the menu of django-admin subcommands. However, when I try to set DJANGO_SETTINGS_MODULE, my new djangotest app is not recognized: (djangotest) $ cd ../ (djangotest) $ django-admin startproject djangotest (djangotest) $ cd djangotest (djangotest) $ ls djangotest manage.py (djangotest) $ export DJANGO_SETTINGS_MODULE=djangotest.settings (djangotest) $ django-admin Traceback (most recent call last): File "/Users/sam/Dropbox/.virtualenvs/djangotest/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File … -
How to refer multiple model object using one model field in django?
Suppose, I have Project and Manager model. class Project(models.Model): name = models.CharField(max_length=50) class Manager(models.Model): name = models.CharField(max_length=50) projects = This would be array of Project object. But how can I implement this? PostgreSQL has ArrayField for this implementation. But I want a solution that will work for any database. Any alternative solution would be highly appreciable. -
could not use custom templatetags in Django 2.0
I'm using Django 2.0. I have written few custom template tags to use in the template inside notes/templatetags/note_tags.py file where notes is app directory I have written few custom tags inside this file from django import template from django.template.defaultfilters import stringfilter from notepad.utils import simplify_text from notes.models import Note, ColorLabels register = template.Library() @register.filter(name='note_simplify') @stringfilter def note_simplify(value): return simplify_text(value) @register.filter(name='default_color_label') def default_color_label(): default_label = ColorLabels.objects.filter(default=True).first() print(default_label.value) return default_label and inside the template file, I have loaded the tag as {% load note_tags %} I'm able to use the first tag note_simplify but second tag default_color_label is not being called. I'm using both tags in the same file. One for modifying the passed data and another to simply print something # modify the note.content <p>{{ note.content|truncatechars:200|note_simplify }}</p> # to print some value {{ default_color_label.value }} I have also restared server many times. Is there something wrong? Why the tag is not being called in template? -
TypeError: object of type 'EmailMultiAlternatives' has no len()
Django app, sending an email using a script (using runscript), only on weekdays. Trying to use Google's STMP. Here's the relavent script: import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labschedule.settings") django.setup() import datetime from datetime import date import smtplib from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from labschedule import settings def run(): today = date.today() subject = "Daily Report for %s" % today to = [settings.EMAIL_ADMIN] from_email = 'blahblah@gmail.com' # My email reservations = Event.objects.filter(day=today).order_by('cart') last = Event.objects.latest('day') if today >= today + datetime.timedelta(days=5): countdown = last - datetime.timedelta(today) warning = "Hey! You run out of open slots in %s days" % countdown else: warning = None ctx = ({ 'reservations' : reservations, 'warning' : warning, 'cart_choice' : cart_choice }) html_content = render_to_string('schedule/email.html', ctx) text_content = render_to_string('schedule/email.html', ctx) msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email) msg.attach_alternative(html_content, "text/html") weekend = set([5, 6]) # Python week starts on Monday as 0 if today.weekday() not in weekend and settings.DAILY_EMAIL == True: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(settings.gmail_user, settings.gmail_password) server.sendmail(from_email, to, msg) server.close() print ('Email sent!') else: pass I went mostly of the tutorial here. The error I receive: TypeError: object of type 'EmailMultiAlternatives' has no len() I'm newish, and I know it's something dumb, and would … -
Django uses default reset form instead of my Html
I'm new in Django. Have urlpatterns = [ path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout_then_login, name='logout'), path('reset/', auth_views.password_reset, name='reset'), path('reset/done', auth_views.password_reset_done, name='password_reset_done'), path('reset/<slug:uidb64>/<slug:token>/', auth_views.password_reset_confirm, name='password_reset_confirm'), path('reset/done/', auth_views.password_reset_complete, name='password_reset_complete'), ] in my urls.py and have password_reset_done.html and other files at accounts/templates/registration. But Django uses deafult form for reset, but use my login.html from the same directory. What am i doing wrong? Thanks! -
NoReverseMatch: Reverse for 'detail' not found. (Django Tutorials)
I've been going through the Django 2 tutorials. I got the following error: #Error: #django.urls.exceptions.NoReverseMatch #django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern #name. Did some googling and confirmed that I had named my view 'detail' and also had my app named. Below are my codes. Please tell what is wrong. I am following the tutorial by heart, but this came up. How can I fix it keeping in par with the tutorials? Thank you! Files: mysite/polls/templates/polls/index.html {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} mysite/polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), # ex: /polls/ # path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/polls/views.py def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) Additional: mysite/urls.py urlpatterns = [ path('polls/', include('polls.urls', namespace='polls')), path('admin/', admin.site.urls), ] -
How to annotate queryset with another queryset
Now I'm trying to build complex queryset that uses annotations with conditional related queries. I have the following models: class MenuItemCategory(CreateUpdateModel): name = models.CharField(max_length=255, blank=True, null=True) class MenuItem(CreateUpdateModel): category = models.ForeignKey(MenuItemCategory, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) class LineItem(models.Model): order = models.ForeignKey(Orders, blank=True, null=True) menu_item = models.ForeignKey(MenuItems, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=3) amount = models.DecimalField(max_digits=10, decimal_places=2) class Order(CreateUpdateModel): waiter = models.ForeignKey(Employees, blank=True, null=True) guests_count = models.IntegerField(blank=True, null=True, default=0) closed_at = models.DateTimeField(blank=True, null=True, db_index=True) class Employees(CreateUpdateModel): restaurant = models.ForeignKey(Restaurants, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) My goal is to build json with following scheme: [ { employee_name: 'Jane', menu_item_categories: [ { name: 'Drinks', line_items_quantity: 10, //times when this waiter brings any item from this category to the customer at the period amount: 49.00, // price of all drinks sold by this waiter at the period menu_items: [ name: 'Vodka', amount: 1.00, line_items_quantity: 4, # times when this item has been ordered for this waiter at the period ] } ], visits: 618, guests: 813, cycle_time: 363 } ] With following serializer: class EmployeeSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=255) visits = serializers.SerializerMethodField() guests = serializers.SerializerMethodField() cycle_time = serializers.SerializerMethodField() menu_item_categories = serializers.SerializerMethodField() def get_visits(self, obj): # works def … -
Django many-to-many, display in admin
Please help to understand how to display list of groups in Django admin Person instance in this case: class Person(models.Model): name = models.Charfield(max_length=120) class Group(models.Model): title = models.Charfield(max_length=120) persons = models.ManyToManyField(Person) -
Pass date range in URL in Django Rest
I have a JSON structure like, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] I am using Django Rest Framework. Whenever, I do a GET request to, localhost/namelist/{{name}}/ is returns the JSON where "name": "ab" . Now, I want to return JSON based on date range. I will pass the start date and end date in the url and it should return the value within that specific date range, time should be ignored. Also, we have to consider months also, not only dates. Here, in this example, month is same but in real scenario months might be different. Like, localhost/namelist/{{name}}/{{start_date}}/{{end_date}}/ If the URL is , localhost/namelist/abcd/2017-12-17/2017-12-19/ then it should return, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] views.py :- def get_queryset(self): param = self.kwargs.get('pk') param2 = self.kwargs.get('ak') return namelist.objects.filter(name=param, date = param2) urls.py :- urlpatterns = { url('^namelist/(?P<pk>[\w\-]+)/(?P<ak>[\w\-]+)/$', ListViewParam.as_view()), } I can pass the date in the URL, but what the recommended way to pass the date range ? -
Extract data from range with both empty and filled data
My problem is i need the objects from certain range date . In that i am having filled data for some dates and for some dates there is no data. For one date one form ,if user fill the form and submit then it will store for that date rows = Grades.objects.filter( user_ql__created_at__range=(from_date, to_date).order_by('-user_ql__created_at').values() when I print length of rows I got only 5 objects . Actually the date range is 7 days I am getting only 5 dates object because in that date range only 5 date are filled remaining 2 dates are not filled i need to show that all the objects of rows which are filled not filled dates also -
django cannot connect mysql in docker-compose
I'm very new for docker, now I am trying to run django with mariadb in docker through docker-compose, but I always get this error: I use Docker version 17.09.1-ce, build 19e2cf6, docker-compose version 1.18.0, build 8dd22a9 django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'mariadb55\' (111 "Connection refused")') I can connect db correctly after run docker-compose up db in local or remote, and I even can run python manage.py runserver 0.0.0.0:6001 correctly in anaconda virtual environment to connect db service in docker by setting parameters of settings.py file like below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'belter', # 'HOST': 'mariadb55', 'HOST': '127.0.0.1', 'PORT': '3302', 'PASSWORD': 'belter_2017', 'default-character-set': 'utf8', 'OPTIONS': { 'sql_mode': 'traditional', } } } This is my docker-compose.yml file version: '3' services: db: image: mariadb:5.5 restart: always environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 - MYSQL_ROOT_HOST=% - MYSQL_DATABASE=test - MYSQL_USER=belter - MYSQL_PASSWORD=belter_2017 - MYSQL_ROOT_PASSWORD=123456_abc volumes: - /home/belter/mdbdata/mdb55:/var/lib/mysql ports: - "3302:3306" web: image: onlybelter/django_py35 command: python3 manage.py runserver 0.0.0.0:6001 volumes: - /mnt/data/www/mysite:/djcode ports: - "6001:6001" depends_on: - db links: - db:mariadb55 I almost tried everything I can find, but still cannot figure it out, any help would be nice! What I have tried: Docker compose mysql connection failing … -
Why will django form not summit data to dabase but instead displays result as a url on the broswer
When ever i summit my Django form from the template .I get the result bellow http://127.0.0.1:8000/Search_match_distributors/?csrfmiddlewaretoken=3rDq624irqw2L0WDQCvzFHM5pAux3ep9cXWTeKQ4WlNyd5JWJxQrHVfBOLAPMHI1&CompanyRegisteredName=unine&CompanyRegisteredState=weqeqqw&CompanyRegisteredAddress=qewq&CompanyRegisteredCity=qwqw&CompanyEmail=qweq%40yahoo.com&Country=Belize&RegisteredCompanyType=corperation&title=SeaFood&YouOwnBusiness=Yes&AreaCode=%2B375&WorkPhone=121212&TypeOfDistributorPrefered=IntensiveDistributors data to save in saver is displayed on the browser instead . Does someone has an idea why such happens. My code in views.py ,form.py and model.py and url.py has no error -
Allow staff user to only read the data
I want to allow the staff users to view (read only)the transaction data. But when I login as a staff user, it displays 'You don't have permission to edit anything.' and rest of the page is blank. models.py #models.py from django.db import models from django.contrib.auth.models import Permission, User from django.core.validators import RegexValidator # Create your models here. alphanumeric = RegexValidator(r'^[0-9a-zA-Z-]*$', 'Only alphanumeric characters and "-" are allowed.') TransactionTypes = ( ('P','Purchase'), ('S','Sell'), ) class Transactions(models.Model): client_name = models.OneToOneField(User(is_staff=True)) transaction_type = models.CharField(choices=TransactionTypes,max_length=1) amount = models.IntegerField() transaction_id = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric]) class Meta: permissions = ( ('read_item','Can read item'), ) Admin.py- #admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Transactions # Register your models here. class TransactionAdmin(admin.ModelAdmin): #list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') def get_readonly_fields(self, request, obj=None): if not request.user.is_superuser and request.user.has_perm('transactionss.read_item'): return [f.name for f in self.model._meta.fields] return super(TransactionAdmin, self).get_readonly_fields( request, obj=obj ) admin.site.register(Transactions, TransactionAdmin) -
Can I change the related_name when I get the nested data in Django-Rest-Framework?
Such as I have two Model, the first is the second's ForeignKey. class MyModel(models.Model): firstDate = models.DateTimeField(auto_now_add=True) another = models.CharField(max_length=30) class MySubModel(models.Model): name = models.CharField(max_length=12) my_model = models.ForeignKey(to=MyModel, related_name="mysubs") In the MyModelSerializer it should be: class MyModelSerializer(ModelSerializer): mysubs = MySubModelSerializer(many=True, read_only=True) class Meta: model = MyModel fields = "__all__" The result will be like bellow: [ { "firstDate":xxxx, "another":xxxx, "mysubs":[ { "name":xxx, } ] } ] I want to replace the key mysubs to children, is it possible to do that? -
How do I access the properties of a many-to-many relationship
How do I access the properties of a many-to-many relationship? and on model. class Courses(models.Model): courses_name = models.CharField(max_length=100) duration = models.CharField(max_length=100) def __str__(self): return u'%s' % (self.courses_name) class Meta: verbose_name_plural = 'Courses' verbose_name = 'Courses' class EducationEntity(models.Model): name = models.CharField(max_length=100) type = models.ForeignKey(EducationEntityType) location_type = models.ForeignKey(LocationType) institute_type = models.ForeignKey(InstituteType) course = models.ManyToManyField(Courses) established=models.DateField(default=datetime.date.today) approved_by=models.CharField(max_length=200) college_facilities=models.CharField(max_length=200) image = models.ImageField(upload_to='images/',default="none") def __str__(self): return u'%s' % (self.name) class Meta: verbose_name_plural = 'Education Entity' verbose_name = 'Education Entity' @property def course_(self): # import ipdb; # ipdb.set_trace() amount='' data = [] duration='' interest_rate='' loan=[] for i in self.course.all(): try: for cou in EducationEntityCourses.objects.filter(course=i): for l in LoanDetails.objects.filter(education_entity_courses__course=i): amount=l.amount for lo in LoanTenure.objects.filter(loan_details__education_entity_courses__course=l): loan.append({"duration": lo.duration,"interest_rate": lo.interest_rate}) except Exception as e: amount='' import ipdb; ipdb.set_trace() data.append({ "courses_name": i.courses_name, "duration":cou.duration, "course_type":cou.course_type, "tution_fees":cou.tution_fees, "hostel_fees":cou.hostel_fees, "other_fees":cou.other_fees, "amount":amount, "loan":loan }) import ipdb; ipdb.set_trace() return data class EducationEntityCourses(models.Model): education_entity = models.ForeignKey(EducationEntity) course = models.ForeignKey(Courses) duration = models.CharField(max_length=100) course_type = models.ForeignKey(CourseType) tution_fees = models.CharField(max_length=100) hostel_fees = models.CharField(max_length=100) other_fees = models.CharField(max_length=100) def __str__(self): return u'%s, %s' % (self.education_entity.name, self.course.courses_name) class Meta: verbose_name_plural = 'Education Entity Courses' verbose_name = 'Education Entity Courses' class LoanDetails (models.Model): education_entity_courses = models.ForeignKey(EducationEntityCourses) # training_coaching=models.ForeignKey(TrainingCoaching,blank=True,null=True) amount = models.CharField(max_length=100) def get_course(self): """ get course name :return: """ return self.education_entity_courses.course.courses_name get_course.short_description="Course Name" … -
Django database routing on request.user
Is it possible to get the user object in Django router class? I'm trying to route query on a database based on the type of user. Is it even possible? Thank you -
How can I run one-off dyno inside another one-off dyno on Heroku using custom django-admin commands?
I need to create one-off dyno in Django application deployed on Heroku using custom django-admin commands. I want to use Heroku Scheduler to run command heroku run python manage.py test_function2. It creates one-off dyno with running function test_function2 in it. Then I would like to use test_function2 function to create more one-off dynos. I added example code below. My problem is associated with line command = 'heroku run:detached myworker2' When I use command = 'heroku run:detached myworker2' in test_function2 I get error sh: 1: heroku: not found. Does anyone have an idea how can I create heroku one-off dyno when I am already in one? test_function2: class Command(BaseCommand): def handle(self, *args, **options): command = 'heroku run:detached myworker2' os.system(command) Procfile: web: sh -c 'gunicorn backend.wsgi --log-file -' myworker2: python manage.py test_function2 myworker2: python manage.py test_function -
Filtering many to many field Django
I have a query like this: queryset = User.objects.filter( ~Q(pk=self.request.user.pk), ~Q(connections_as_initiator__peer=self.request.user, connections_as_initiator__stopped=False)) Beetween one intitator and peer there could be numerous connections bun only one that is not stopped. So what I want this query to do is to find whether between the current user and the queried one there are active connections where the current user is a peer. But this is not what happens at all: SELECT accounts_user.id FROM accounts_user WHERE ( NOT accounts_user.id = 48 AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.peer_id = 48) AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.stopped = FALSE) ); What I was thinking of (and what gives an expected result) is something like: SELECT accounts_user.id FROM accounts_user WHERE ( NOT accounts_user.id = 48 AND NOT accounts_user.id IN (SELECT U1.initiator_id AS col1 FROM connection U1 WHERE U1.peer_id = 48 AND U1.stopped = FALSE) ); Is there a way to achieve that with ORM or should I start using raw SQL. I was also thinking about annotations, but I'm not yet 100% sure how to implement it that way. -
AttrbuteError while using serializer in djangorestframework
I get 'AttrbuteError: 'DeferredAttribute' has no attribute 'isoformat'' when i try to serialize the django model using the djangorestframework Below is the model that im trying to serialize class PrimaryRecord(models.Model): primaryId = models.AutoField(primary_key=True) primary_track = models.CharField(max_length=30) title = models.CharField(max_length=255) start_date = models.DateField() create_date = models.DateField() year = models.IntegerField() and the serializer class that i'm using is below from rest_framework import serializers from snippets.models import Assesor, PrimaryRecord, PrimaryAssesor class PrimaryRecordSerializer(serializers.Serializer): primary_track = serializers.CharField(max_length=30) title = serializers.CharField(max_length=255) start_date = serializers.DateField(format = None) create_date = serializers.DateField(format = None) year = serializers.IntegerField() def create(self, validated_data): return PrimaryAssesor.objects.create(**validated_data) def update(self, instance, validated_data): instance.primary_track = validated_data.get('primary_track', instance.primary_track) instance.title = validated_data.get('title', instance.title) instance.start_date = validated_data.get('start_date', instance.start_date) instance.create_date = validated_data.get('create_date', instance.create_date) instance.year = validated_data.get('year', instance.year) instance.save() return instance Im following this tutorial for learning djangorestframework. I do the following steps p1 = PrimaryRecord(primary_track='P2017-98',title='ABC',start_date=date(2017,6,23),create_date=timezone().now(),year=2017) p1.save() serializer = PrimaryRecordSerializer(primaryrecord) serializer.data # the error occurs here 'AttrbuteError: 'DeferredAttribute' has no attribute 'isoformat'' -
How can I get the custom nested data in Django?
I have four model as bellow: class AModel(models.Model): name = models.CharField(max_length=11) class BModel(models.Model): name = models.CharField(max_length=11) a = models.ForeignKey(AModel, related_name="bs") class CModel(models.Model): name = models.CharField(max_length=11) b = models.ForeignKey(BModel, related_name="cs") class DModel(model.Model): name = models.CharField(max_length=11) c = models.ForeignKey(CModel, related_name="ds") Now I want to get the bellow data: [ {"name":"a1", "value":1, "image":"xxxxx.png", "children":[ {"name":"b1", "value":1, "image":"xxxxx.png", "children":[ {"name":"c1", "value":1, "image":"xxxx.png", "children":[ {"name":"d1", "value":1, "image":"xxxx.png", } ] } ] } ] } ] note, the value and image key-value are add by myself. I know use the Django-Rest-Framework can get the data like: [ { "id":1, "name":"a1", "bs":[ { "id":1, "name":"b1", "cs":[ "id":1, "name":"c1", "ds":[ { "id":1, "name":"d1", } ] ] } ] } ] But how can I get my requirement data? I also tried query the AModel instance first, the forloop the AModel instance's bs, and then do the next, but I find that is too complex, not a simple and convenient way to get it. -
Basic Authentication in Django Rest Framework
I want to Authenticate the username and password for an API. If the username and password is correct, then it will display the userlist, otherwise NOT. I have stored all the username and password in my own table named USERS. Can you please help how to authenticate the username/password from the USERS table entry. Or all the authentication can be made only from "auth_user" table by default. Please me help me with the code. NOTE: I am using Postgresql as Database. class UsersList(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request): dict_data = {} userlist = Users.objects.all() if userlist: serializer = UserlistSerializer(userlist, many=True) return Response(serializer.data) else: return Response([]) -
Setting up Sentry with Django
I installed Sentry with docker-compose And I set up Django according to this manual https://docs.sentry.io/clients/python/integrations/django/ But errors do not come in Sentry I tested it: python manage.py raven test and got this result: DEBUG 2017-12-26 08:49:51,033 base 67 140371587118848 Configuring Raven for host: Client configuration: base_url : http://adyy.ru:9000/sentry project : 2 public_key : 946327fca2844e8684d8233c89826062 secret_key : 96fb7bee962c413ba7356434c84985b1 Sending a test message... DEBUG 2017-12-26 08:49:51,305 base 67 140371587118848 Sending message of length 3464 to http://adyy.ru:9000/sentry/api/2/store/ Event ID was '28ca8194b1904081938fc2189cc3b7d2' ERROR 2017-12-26 08:49:51,325 base 67 140371430176512 Sentry responded with an error: HTTP Error 403: OK (url: http://adyy.ru:9000/sentry/api/2/store/) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/raven/transport/threaded.py", line 165, in send_sync super(ThreadedHTTPTransport, self).send(url, data, headers) File "/usr/local/lib/python2.7/dist-packages/raven/transport/http.py", line 43, in send ca_certs=self.ca_certs, File "/usr/local/lib/python2.7/dist-packages/raven/utils/http.py", line 66, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 437, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 550, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 475, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 558, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: OK ERROR 2017-12-26 08:49:51,326 base 67 140371430176512 [u'This is a test message generated using ``raven test``'] what to … -
Call Rest API with user using Python requests
I want to call an API using requests.get() method where I have to give username and password as authentication like below. response = requests.get(url, auth=requests.auth.HTTPBasicAuth('username', 'password')) but I don't want to give password in auth as it will work dynamically where password will be encrypted. so is there any way to do this by only giving username and not password? -
Django error - 'function' object has no attribute 'MyForm'
I am new to Django and was working with Django forms and stuck at an error for which I am not finding any relevant solution. My Form.py is : from django import forms class MyForm(forms.Form): name = forms.CharField() email = forms.EmailField() text = forms.CharField(widget=forms.Textarea) and My views.py is : from django.shortcuts import render from django.http import HttpResponse from . import forms # Create your views here. def index(request): return render(request, 'basicapp/index.html') def forms(request): form = forms.MyForm() return render(request, 'basicapp/forms.html', context = { 'form' : form }) All the routing is Fine as I have checked by replacing forms with a normal HttpResponse but there is some problem in the forms.py or views.py as they the form in not being displayed in the browser and the Error is coming 'function' object has no attribute 'MyForm' Please Someone help :( I gotta move Forward -
TypeError: not enough arguments for format string python mysql
I want to collect each people's grade in the special subject of course with python. I get each person's grade one by one. For this reason, I write a SQL code like below. row come from easrlier sql result and it prints subject and course and it shows like ('CS', '201') categoriesWithFeedback contains unique nickname. I write sql code but it cannot understand row contains 2 parameter I think. sqlgrade = "SELECT `grade` FROM `enrolledtable` WHERE `subject`=%s and `course`=%s and `nickname`=%s" IE_students.append(categoriesWithFeedback) cursor.execute(sqlgrade, (row, categoriesWithFeedback)) IEaveragegrades += cursor.fetchone() ` Python ERROR is that Traceback (most recent call last): File "C:\wamp\www\MLWebsite\website\new.py", line 85, in cursor.execute(sqlgrade, (row, categoriesWithFeedback)) File "C:\Python27\Lib\site-packages\pymysql\cursors.py", line 163, in execute query = self.mogrify(query, args) File "C:\Python27\Lib\site-packages\pymysql\cursors.py", line 142, in mogrify query = query % self._escape_args(args, conn) TypeError: not enough arguments for format string Can anyone help me to solve that error? I don't want to use sqlparse if there is any solution without that.