Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Telegram BOT webook sending empty POST
I'm trying to get the payload of the webhook in a BOT webhook in Django. @csrf_exempt def webhook(request): print(request.get_full_path()) print(request.POST) print(request.GET) return HttpResponse("OK") The webhook calls are working fine {"ok":true,"result":{"url":"...","has_custom_certificate":false,"pending_update_count":0,"last_error_date":1516490058,"last_error_message":"Wrong response from the webhook: 503 Service Unavailable","max_connections":40}} (last_error_message was solved) <QueryDict: {}> <QueryDict: {}> [20/Jan/2018 23:16:17] "POST /webhook/secure/ HTTP/1.1" 200 2 But above text is what I'm getting in the POST and GET method each time I get a message. Always empty. Maybe I'm missing something in the Telegram part, since I've made a POST request to the same URL and it's printing correct information. -
Error: RuntimeWarning: DateTimeField Comments.timestamp received a naive datetime while time zone support is active
I'm getting this error when I run python manage.py test - I believe it could be because of my transition from Django 1.10 to 1.11. I've commented out the actual field # timestamp = models.DateTimeField(default=timezone.now, blank=True) in my models, and I was still getting the error so I commented out all instances of it in the Migration history: class Migration(migrations.Migration): dependencies = [ ('comment', '0003_comment_new_position'), ] operations = [ # migrations.RemoveField( # model_name='comment', # name='timestamp', # ), ] class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('post', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('destination', models.CharField(blank=True, default='1', max_length=12)), ('parent_id', models.IntegerField(default=0)), ('comment_text', models.TextField(blank=True, max_length=350, null=True)), # ('timestamp', models.DateTimeField(blank=True, default=django.utils.timezone.now)), ('children', models.IntegerField(default=0)), ('parent_comment', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='replies', related_query_name='replies', to='comment.Comment')), ('post', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='post.Post')), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], however I'm still getting the error. Full traceback Creating test database for alias 'default'... /Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/db/models/fields/__init__.py:1451: RuntimeWarning: DateTimeField Comments.timestamp received a naive datetime (2018-01-20 23:11:33.621828) while time zone support is active. RuntimeWarning) Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) … -
Error when creating superuser with custom user model | Django
I have created a custom user model in Django (see my code below), but when I do 'python manage.py createsuperuser' and enter an email and password in my terminal I get the error: in create_superuser is_admin=True TypeError: create_user() missing 2 required positional arguments: 'last_name' and 'email' Any help would be much appreciated! from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None, is_staff=False, is_admin=False): user_obj = self.model( first_name = first_name, last_name = last_name, email = self.normalize_email(email), ) user_obj.set_password(password) #set and change password? user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) USERNAME_FIELD = 'email' objects = UserManager() def __str__(self): return self.email def get_first_name(self): return self.email def get_last_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def get_short_name(self): return self.email @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin -
How to make Celery PeriodicTask start running in future?
I want to create a periodic task, but also want to add a "start-time" for that periodic task. Is there a way to do this ? -
Django testing: assertionError 'form' not used to render response
I am getting this error message when I try to test a form validation in Django. AssertionError: The form 'form' was not used to render the response I am trying to test a couple things around a FileUpload form. What is strange is that only one test is failing, out of bunch that use the form. For example, the first and second test below are almost identical, yet the first one is successful and the second returns this AssertionError. The only difference between first and second is file path and the field attribute. And I can't narrow down the problem to these two items. def test_invalid_file_extension_error(self): date = dt(2018,1,14) with open(bad_path) as fp: data = { 'account': self.account.pk, 'date': self.date.strftime("%d-%m-%Y"), 'file': fp } response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True) field = 'file' self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', field, u'Unsupported file extension.') def test_invalid_due_to_future_date(self): date = dt(2020,1,1) with open(good_path) as fp: data = { 'account': self.account.pk, 'date': self.date.strftime("%d-%m-%Y"), 'file': fp } response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True) field = 'date' self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', field, u'The date cannot be a future date!') Here's my view: class UploadView(CreateView): model = SaveReports form_class = SaveReportsForm def form_valid(self, form): report = form.save() account = ReportsToTraxns( account = … -
create separate Django admin panel
I'm new into Django had 5 years of experience in PHP I couldn't find the answer to my questions after hours of research! is it possible to create completely separate admin panel in Django? how authentication works on Django?! on a user control panel for example how to control sessions and let user log in into the panel etc. what is the correct way to use NOSQL DB's like Mongodb as backend for Django? -
How to exclude inactive (soft deleted) foreign key fields in Django Model Forms?
I have 2 models: Category and Listing where Listing belongs to Category. I've created a Listing ModelFrom. How do I exclude category models that are inactive from displaying on forms? class Category(models.Model): active = models.BooleanField(default=False) .... class Listing(models.Model): category = models.ForeignKey('Category') .... class ListingForm(forms.ModelForm): class Meta: model = Listing fields = ['category'] form = ListingForm(initial={}) When I render 'form' on html, it displays the category select field displays the inactive categories. -
django formset validation MultiValueDictKeyError
Using django 1.8, I am making a custom inline form. models.py: class Task(models.Model): description = models.CharField(max_length=255) project = models.ForeignKey('Project') def __unicode__(self): return str(self.description) class Project(models.Model): name = models.CharField(max_length=255, unique=True) views.py @login_required def project(request, proj_id): proj = Project.objects.get(id=proj_id) TaskFormSet = inlineformset_factory(Project, Task, fields=('description',), extra=0) if request.method == "POST": proj_form = ProjectForm(request.POST, instance=proj) formset = TaskFormSet(request.POST, instance=proj) if proj_form.is_valid() and formset.is_valid(): formset.save() proj_form.save() return HttpResponseRedirect('/project/{}'.format(proj_id)) else: formset = TaskFormSet(instance=proj) proj_form = ProjectForm(instance=proj) data = {'proj_form': proj_form, 'formset': formset, 'proj_id': proj_id} return render(request, 'project.html', data) my template: project.html {% extends "admin/base_site.html" %} {% block extrahead %} {% endblock %} {% block content %} Project {{project_id}} <form method="post" action=""> {% csrf_token %} {{proj_form}} <table border="2"> {{formset}} </table> <input type="submit" value="Save"/> </form> {% endblock %} This works fine; but I want to customize it more so I change the template as below new template: {% extends "admin/base_site.html" %} {% load staticfiles %} {% block extrahead %} <script src="{% static "js/jquery.min.js" %}"></script> <script src="{% static "js/dynamic_formset.js" %}"></script> <script type="text/javascript"> $(function () { $('.add-row').click(function() { return addForm(this, 'form'); }); $('.delete-row').click(function() { return deleteForm(this, 'form'); }) }) </script> {% endblock %} {% block content %} Project {{project_id}} <form method="post" action=""> {% csrf_token %} {{proj_form}} <table id="id_forms_table" border="1" cellpadding="0" … -
Django middleware: UnboundLocalError: local variable 'background_color' referenced before assignment
I'm trying to randomise certain elements of my theme across a website I'm building. I thought it might be quite nice to experiment with defining some custom middleware to handle this. But it looks like I've gone wrong somewhere: middleware.py: class RandomThemeAppearanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): theme = { background_color: '#266040', contrast: '#3bbfad', color: '#ffffff', } background_colors = ['#266040', '#009a16', '#015e85', '#d6006d'] background_color = random.choice(background_colors) if background_color == '#266040': theme['contrast'] = '#3bbfad' elif background_color == '#009a16': theme['contrast'] = '#fedf21' elif background_color == '#015e85': theme['contrast'] = '#0590b3' elif background_color == '#d6006d': theme['contrast'] = '#f97fb5' else: pass theme['background_color'] = background_color request.background_color = theme['background_color'] request.contrast = theme['contrast'] request.color = theme['color'] return self.get_response(request) Django debug is telling me the following: UnboundLocalError at / local variable 'background_color' referenced before assignment Can anyone shed any light on why this is error is being thrown? -
How to set a Background image in Django template?
I am new to Django and was using it for my project until I faced a small problem which is really small but is bothering me from 2 days. How to apply a background image in the django template ? Here's my index.html :- <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel=" stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Cabin+Sketch" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Dosis:800" rel="stylesheet"> <title>Document</title> <style type="text/css"> body { background: url({% static "images/dumb2.jpg" %}); background-size: cover; } .heading { color: white; font-family: 'Sedgwick Ave Display', cursive; font-size: 10vw; letter-spacing: 20px; color: rgb(0, 255, 170); padding-top: 20px; font-family: 'Cabin Sketch', cursive; } .data-rows { padding-top: 10px; } .textfield-labels { color: white; font-weight: 600; } .textfield { border: 5px solid black; } .signup-heading { color: white; font-family: 'Dosis', sans-serif; letter-spacing: 20px; } .bored { height: 300px; width: 300px; } .font-icons { color: white; font-size: 50px; } .description { color: white; font-weight: 600; } .first-description { padding: 10px; border-radius: 20px; border: 1px solid rgb(117, 19, 19); animation-name: first-block; animation-duration: 6s; animation-iteration-count: infinite; animation-direction: alternate; } .left-column { padding: 20px; } ::-moz-placeholder { text-align: center; } ::-webkit-input-placeholder { text-align: center; } @keyframes first-block … -
Remove filter in xlsx file with pandas
I am new to pandas, and I am doing a graph visualization using plotly from an xlsx file. I have manager to do this, but the thing is that the xlsx file has a daily filter, so it accumulate the rows that have same date. But what I want, is to desactivate the daily filter, in order to show the values of hours in the days. This is how the data are in the xlsx file And here is the bit of code that am using to visualize the data : df = pd.read_excel("Hourly_daily.xlsx").sort_values('Date') df = df[(df['Date'] != str(datetime.now().date()))].tail(7) trace1 = go.Scatter( x=df['Date'], y=df['TEST'], mode='lines+markers', name='Trafics' ) trace2 = go.Scatter( x=df['Date'], y=df['%'], mode='lines+markers', name='Pourcentage', yaxis='y2' ) data = [trace1, trace2] layout = go.Layout( title='Graphe avec double axes', yaxis=dict( title='Trafic' ), yaxis2=dict( title='Pourcentage', titlefont=dict( color='rgb(148, 103, 189)' ), tickfont=dict( color='rgb(148, 103, 189)' ), overlaying='y', side='right' ) ) fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='C:/Users/elmou/Desktop/albumaster_final/test0\music/templates/music/multiple-axes-double.html', auto_open=False) -
Parse data from yaml file to dictionary and updating in Django models
I have a yaml file, which i am parsing into dictionary. as follow- def parse(self): with open("/students.yml", 'r') as stream: try: return (yaml.load(stream)) except yaml.YAMLError as exc: print(exc) After parsing this file into dictionary i am getting a large data in dictionary as like follow - { u 'A101\ab0\ab0': { 'NAME': 'RAZ', 'AGE': '17', 'ROLLNO': u 'A101\ab0\ab0', 'CLASS': 'SIX', }, u 'A102\ab0': { 'NAME': 'OM', 'AGE': '15', 'ROLLNO': u 'A102\ab0', 'CLASS': 'SEVEN', }, u 'A103\ab0': { 'NAME': 'PURI', 'AGE': '15', 'ROLLNO': u 'A103\ab0', 'CLASS': 'SEVEN', } } I have created the Djangomodel for name, age, rollno, class field. I wanted to update models with the getting response after parsing. What could be efficient way to create object and bulk update. Any help would be appreciated. -
How do I reference a model column via string?
I'm making a terminal command where the user enters two strings. One will correspond to a model and the other to a column from that model. class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--model", dest="model", required=True, ) def add_arguments(self, parser): parser.add_argument( "--col", dest="col", required=True, ) def handle(self, *args, **options): # Handle stuff here I know I can do from django.apps import apps and put options["model"] in apps.get_model() to get an instance of the model the user inputs, assuming it exists. But How can I reference the column the user inputs in options["col"]? -
Django - 'module' object is not callable
I'm trying to serve images from the database with django, but when I add + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns i get this error: TypeError at /: module object is not callable this is the traceback: File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. resolver_match = resolver.resolve(request.path_info) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in resolve 494. for pattern in self.url_patterns: File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/utils/functional.py" in __get__ 36. res = instance.__dict__[self.name] = self.func(instance) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in url_patterns 536. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/utils/functional.py" in __get__ 36. res = instance.__dict__[self.name] = self.func(instance) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in urlconf_module 529. return import_module(self.urlconf_name) File "/usr/lib/python3.6/importlib/__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>" in _gcd_import 994. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load 971. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load_unlocked 955. <source code not available> File "<frozen importlib._bootstrap>" in _load_unlocked 665. <source code not available> File "<frozen importlib._bootstrap_external>" in exec_module 678. <source code not available> File "<frozen importlib._bootstrap>" in _call_with_frames_removed 219. <source code not available> File "/home/watch/Documents/projects/herokuapp/mysite/mysite/urls.py" in <module> 27. ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Exception Type: TypeError at / Exception Value: 'module' object is not callable I tried using it in both the main urls.py and the app urls.py, … -
How to assign Foreign Key static in Django Post Model
I want to add static user my Foreign Key field because of guest's post, but i can't. I try to add first id like 1, "1", "id=1" but no result. Can you help me pls? Here is my model.py; class Post(models.Model): user = models.ForeignKey('auth.User', related_name='posts') title = models.CharField(max_length=120) views.py; post = form.save(commit=False) post.user = request.user if request.user == '': post.user = 1 post.save() else: post.save() return HttpResponseRedirect(post.get_absolute_url()) etc. Thanks. -
manage.py collectstatic not working in macOS 10.13.1
I'm having issues while running collectstatic in macOS. The error is OSError: [Errno 45] Operation not supported: '/home/juan' ./manage.py collectstatic Copying '/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/admin/static/admin/css/widgets.css' Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file self.storage.save(prefixed_path, source_file) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 236, in _save os.makedirs(directory) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) OSError: [Errno 45] Operation not supported: '/home/juan' ---------- The same command in the same project is running fine in ubuntu -
integrate postgresql with Django on windows
I am new to Django and Postgresql. I am trying to integrate Django with the PostgreSQL database, I modified the code in settings.py file under DATABASES. and tried to make PostgreSQL my default database. DATABASES = { 'defaults': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Test', 'USER': 'postgres', 'PASSWORD': 'test1234', 'HOST': 'localhost', 'PORT': '', } } I am using PyCharm 2017.3.2 for the Django framework. I have installed PostgreSQL and running pgAdmin 4. My database name is Test, and I have not done anything else. but when I am trying to execute python manage.py makemigrate I am getting following error: C:\Users\Ayush\PycharmProjects\Tutorial2\tutorial2>python manage.py makemigrations Traceback (most recent call last): File "C:\Python3.6\lib\site-packages\django\db\utils.py", line 167, in ensure_defaults conn = self.databases[alias] File "C:\Python3.6\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python3.6\lib\site-packages\django\db\utils.py", line 154, in databases if self._databases[DEFAULT_DB_ALIAS] == {}: KeyError: 'default' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python3.6\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python3.6\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Python3.6\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python3.6\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Python3.6\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Python3.6\lib\importlib\__init__.py", line 126, in … -
Could not resolve URL for hyperlinked relationship using view name ( django-rest-framework )
Problem : I am getting an error like this . ImproperlyConfigured at /api/users/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I read this post but it didn't work. serializers.py class UserSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='profile') class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'url') class UserProfileSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') class Meta: model = UserProfile fields = "__all__" # user = serializers.ReadOnlyField(source='owner.username') def create(self, validated_data): pass def update(self, instance, validated_data): pass urls.py user_profile_list = UserProfileViewSet.as_view({ 'get': 'list', 'post': 'create' }) user_profile_detail = UserProfileViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) user_list = UserViewSet.as_view({ 'get': 'list' }) user_detail = UserViewSet.as_view({ 'get': 'retrieve' }) user_profiles_detail = UserViewSet.as_view({ 'get': 'profile' }) router = DefaultRouter() router.register(r'userprofiles', views.UserProfileViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] views.py class UserProfileViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) pagination_class = LimitTenPagination @detail_route(renderer_classes=[renderers.JSONRenderer]) def perform_create(self, serializer): serializer.save(user=self.request.user) class UserViewSet(viewsets.ReadOnlyModelViewSet): """ This viewset automatically provides `list` and `detail` actions """ queryset = User.objects.all() serializer_class … -
How to display Image from a Model in Django - Python
I'm new to Django and i'm studying it for making a University related project. I can't figure out how to fix it: the problem is that it doesn't display the images. I'm stuck with this python code: model.py class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='img') created = models.DateField(auto_now_add=True) quote = models.TextField() def __str__(self): return self.title class Meta: verbose_name = _("Image") verbose_name_plural = _("Images") def __unicode__(self): return self.quote views.py def image_list(request): image_list = Image.objects.all() return render(request, 'images/image_list.html', {'image_list': image_list}) urls.py urlpatterns = [ # post views url(r'^add_image/', views.add_image, name='login'), url(r'^image_list/', views.image_list, name='image_list'), # url(r'', views.image_list, name='list'), ] project's urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^images/', include('images.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = ( BASE_DIR ) MEDIA_URL = 'images/' and image_list.html: {% extends "base.html" %} {% block title %}The Image List{% endblock %} {% block content %} <h1>Here's all your image</h1> {% for image in image_list %} <h2> <h3> {{ image.title }} </h3> <img src= "{{ image.image }}" alt="img"> <p>{{ image.quote }}</p> <p class="date">{{ image.created }}</p> </h2> {% endfor %} {% endblock %} Thank you all. -
How to use WebSockets in Django to make a multiplayer game room?
I am trying to use websockets in django to make a simple "game room" type website. The error occurs after the socket is connected, all my functions in consumers.py apart from ws_connect do not work (which i tested by printing as shown in the code) and so as a consequence my listen function in script.js does not receive any data. Any help would be appreciated ... Pls answers considering the fact that this is my first encounter with websockets. Thanking you in Advance :) consumers.py - @channel_session_user_from_http def ws_connect(message): message.reply_channel.send({'accept': True}) # Initialise their session message.channel_session['rooms'] = [] print("nikhil1") def ws_receive(message): print("nikhil43") payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("chat.receive").send(payload) print("nikhil2") @channel_session_user def ws_disconnect(message): for room_id in message.channel_session.get("rooms", set()): try: room = Room.objects.get(pk=room_id) room.websocket_group.discard(message.reply_channel) except Room.DoesNotExist: pass print("nikhil3") @channel_session_user @catch_client_error def chat_join(message): room = get_room_or_error(message["room"], message.user) print("nikhil4") if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_ENTER) room.websocket_group.add(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).union([room.id])) room.size += 1 room.save() if room.size == 2: room.websocket_group.send( {"text": json.dumps({"start":"yes","title":room.title,"join":str(room.id)})} ) else: room.websocket_group.send( {"text": json.dumps({"start":"no","title":room.title,"join":str(room.id)})} ) @channel_session_user @catch_client_error def chat_leave(message): room = get_room_or_error(message["room"], message.user) if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_LEAVE) room.websocket_group.discard(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).difference([room.id])) message.reply_channel.send({ "text": json.dumps({ "leave": str(room.id), }), }) @channel_session_user @catch_client_error def chat_send(message): if int(message['room']) not in message.channel_session['rooms']: raise ClientError("ROOM_ACCESS_DENIED") print("nikhil5") room = … -
Django with Postgresql database createsuperuser no response
I've tried to use postgresql 10 database with django 2, when i ran python manage.py makemigrations python manage.py migrate the output indicates the database is doing well. but when i try to create a supseruser python manage.py createsuperuser the console actually hangs like below: root@ca80209360d2:/app# python manage.py createsuperuser Username (leave blank to use 'root'): tdy Email address: Password: Password (again): so after i entered the passwords, it doesn't print out super user created successfully as when I'm using sqlite.. I have to Ctrl+C: ^CTraceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/kombu/utils/functional.py", line 36, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/kombu/utils/functional.py", line 333, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 261, in connect return self.connection File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 802, in connection self._connection = self._establish_connection() File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 757, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.5/site-packages/kombu/transport/pyamqp.py", line 130, in establish_connection conn.connect() File "/usr/local/lib/python3.5/site-packages/amqp/connection.py", line 282, in connect self.transport.connect() File "/usr/local/lib/python3.5/site-packages/amqp/transport.py", line 109, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.5/site-packages/amqp/transport.py", line 150, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call … -
Django: How can I list all available RSS feeds of app?
I know how to create a new RSS feed using Django. However, I'd like to provide a page with an overview over all available RSS feeds the website provides. How can I get all the RSS feeds that are available in Django? Unfortunately, I could not find any answer yet. -
Django. How to restrict "profile" page to only "friends"
I currently have a "profile" page that displays specific users information they have uploaded. Currently it does so by objects.filter(user = request.user) Im trying to figure out how I can allow a, for lack of a better description, a "friend" to view someone else's profile. Cause right now, the user who makes the request gets their own information. I believe I know how to build the ability to "friend" another user... i just dont know how to display another users info since all ive been filtering on so far is "request.user" Im obviously a noob, be merciful :) thank you. -
Android - Django Upload Image Error on Server Side
I am trying to upload a Bitmap to Django backend using HttpUrlConnection. I understand the code quality may be poor but I have tried many different ways of doing this, hence the messy code. Any help here would be greatly appreciated. On Client Side: public class ImageUpload { private Bitmap bitmap; private putImageTask put = null; private String eventId; String token; public ImageUpload(Bitmap bitmap, String eventId, String token){ this.bitmap = bitmap; this.eventId = eventId; this.token = token; put = new putImageTask(bitmap, eventId); put.execute(); } public class putImageTask extends AsyncTask<Void, Void, Boolean> { private Bitmap bitmap; private String eventId; public putImageTask(Bitmap bitmap, String eventId){ this.bitmap = bitmap; this.eventId = eventId; } @Override protected Boolean doInBackground(Void...params) { try { String url = "http://192.168.XX.XX:8000/eventphoto/"; URL object = new URL(url); HttpURLConnection c = (HttpURLConnection) object.openConnection(); c.setDoInput(true); c.setRequestMethod("PUT"); c.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); c.setRequestProperty("Accept", "application/json"); c.setRequestProperty("Authorization", "Token " + token); c.setDoOutput(true); c.connect(); OutputStream output = c.getOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, output); JSONObject ev = new JSONObject(); try{ ev.put("event", eventId); }catch(JSONException e){ e.printStackTrace(); } output.write(ev.toString().getBytes("utf-8")); output.close(); StringBuilder sb = new StringBuilder(); int HttpResult = c.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(c.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line … -
Query with many tables works very long time in Django
I have some models: class TagToPublish(models.Model): tag_to_publish = models.TextField() ru_tag = models.TextField(blank=True) eng_tag = models.TextField(blank=True) def __str__(self): return self.tag_to_publish class Tag(models.Model): tag = models.TextField(unique=True) active = models.BooleanField(default=False) tag_to_publish = models.ForeignKey(TagToPublish, blank=True, null=True, on_delete=models.SET_NULL) not_to_publish = models.BooleanField(default=False) def __str__(self): return self.tag def count(self): return self.gif_set.count() class Gif(models.Model): link = models.URLField(unique=True) # link = models.ImageField() post = models.ForeignKey(Post) tagged = models.ManyToManyField(Tag) to_publish = models.BooleanField(default=False) never_publish = models.BooleanField(default=False) choices = models.IntegerField( choices=[ (1, 'To publish'), (2, 'Never Publish'), (0, 'Null') ], default=0) def image(self): return '<image src={} />'.format(self.link) image.allow_tags = True def __str__(self): return self.link def tag_to_publish(self): for tag in self.tagged.all(): tag_to_publish = tag.tag_to_publish if tag_to_publish: return tag_to_publish class Order(models.Model): order_name = models.TextField(blank=True) class InOrder(models.Model): order = models.ForeignKey(Order) gif = models.ForeignKey(Gif) place_in_order = models.IntegerField(blank=True) published = models.BooleanField(default=False) I want to get a list with unique gif_links with the tag to publish. I wrote this code: tags = TagToPublish.objects.all() tags_to_publish = Tag.objects.filter(tag_to_publish__in=tags) gif_set = Gif.objects.filter(tagged__tag_to_publish__tag__in=tags_to_publish).distinct()[:100] But it works very long time because each Gif can have many tags and different tags can have same TagToPublish. If use filter without distinct I got many duplicates. Gif has about 180 000 items. Tags have about 70 000 items. TagToPublish has about 130 items. Each Gif has …