Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'update_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment\\/(?P<news_pk>[0-9]+)$']
I'm coding a news site.Now I'm detailing with the comment post function.And meet the issue says: Reverse for 'update_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment\\/(?P<news_pk>[0-9]+)$'] I have tried many ways and times but still can't solve it and I can't find any wrong with my code.And really need your help. The comment post function is in the news_detail.html. There are two important apps in my project news and operation comment models is under operation Here is my root urls.py: path('news', include(('news.urls', 'news'), namespace="news")), path('', include(('operation.urls', 'operation'), namespace="operation")), Here is the news/urls.py path('-<int:news_pk>', newsDetailView, name="news_detail") Here is the operation/urls.py: path('comment/', views.update_comment, name="update_comment"), Here is the news/view.py def newsDetailView(request, news_pk): news = News.objects.get(id=news_pk) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) return render(request, "news_detail.html", { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, }) Here is operation/views.py def update_comment(request, news_pk): news = News.objects.get(id=news_pk) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): if not request.user.is_authenticated: return render(request, 'login.html', {}) comments = comment_form.cleaned_data.get("comment") news_comment = NewsComments(user=request.user, comments=comments, news=news) news_comment.save() return render(request, "news_detail.html", { 'news_comment': news_comment }) And here is … -
Rest Call gives error : Incorrect type. Expected pk value, received str
I currently have these two models. I am trying to create a job using CreateAPIView. Before I show the view here are my models class modelJobCategory(models.Model): description = models.CharField(max_length=200, unique=True) other = models.CharField(max_length=200, unique=False , blank=True , null=True) class modelJob(models.Model): category = models.ManyToManyField(modelJobCategory,null=True,default=None,blank=True) description = models.CharField(max_length=200, unique=False) These two are my serializers class Serializer_CreateJobCategory(ModelSerializer): class Meta: model = modelJobCategory fields = [ 'description', ] class Serializer_CreateJob(ModelSerializer): class Meta: model = modelJob category = Serializer_CreateJobCategory fields = [ 'category', 'description', ] def create(self, validated_data): job = modelJob.objects.create(user=user,category=?,...) #How to get category ? return job Now this is my view class CreateJob_CreateAPIView(CreateAPIView): serializer_class = Serializer_CreateJob queryset = modelJob.objects.all() def post(self, request, format=None): serializer = Serializer_CreateJob(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now I am passing the following JSON { "category" :{ "description": "Foo" }, "description" : "World" } However I get the exception { "category": [ "Incorrect type. Expected pk value, received str." ] } I came across the same question here and it mentions i need to define a slug field which I am not sure where. Any suggestion on how I can fix this ? -
Meta.filter_overrides for IntegerRangeField in django filter view
Using the example in the Django documentation for utilizing IntergerRangeField with Postgres backend to create ranges in "ages" with the following model: from django.contrib.postgres.fields import IntegerRangeField from psycopg2.extras import NumericRange from django.db import models class Event(models.Model): name = models.CharField(max_length=200) ages = IntegerRangeField() def __str__(self): return self.name This works perfectly however when using Django Rest Frameworks and using filter view with the following filter: import django_filters from django_filters import rest_framework as filters from app import Event class EventFilter(django_filters.FilterSet): ages = django_filters.NumericRangeFilter(queryset=Event.objects.all()) class Meta: model = Event fields = ['name','ages'] the view generates an AssertionError at /api/event_filter/ and suggests adding an override to Meta.filters_override. What I would really appreciate is an example based on the example model for this override, the example in django-filters documentation http://django-filter.readthedocs.io/en/latest/ref/filterset.html#filter-overrides, isn't helping me understand how to get this to render. I would appreciate any help with this so I can understand with this example to utilize this in the future. -
OSError: [Errno 30] Read-only file system in Django on Heroku
I'm using Django 2.0 and Heroku to host the application. My media directory settings are like App/settings/production.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root') I'm using gTTS to convert text to speech and save .mp3 file in the media directory tts_file_name = str(int(time.time())) + '.mp3' joined_path = os.path.join(settings.MEDIA_ROOT, 'tts') joined_path_with_file = os.path.join(joined_path, tts_file_name) # create directory if does not exists if not os.path.exists(joined_path): os.makedirs(joined_path) tts = gTTS(text='Good morning', lang='en') tts.save(joined_path_with_file) # tts path to send to template tts_media_url = os.path.join(settings.MEDIA_URL, 'tts', tts_file_name) It is working fine on local system as I can change file permissions manually also. But It is not working on Heroku and giving error OSError: [Errno 30] Read-only file system: '/static_cdn' I tried to locate static_cdn by running heroku shell, but could not even found static_cdn in application path and root path. But it seems to be working as other uploading through form is working perfectly. using Django model's upload_to is working and even directory is created in static_cdn. How can I create directory in static_cdn in heroku same way like Django do using model's upload_to? -
How to custom ModelForm with CSS - Django
I wasn't able to find a way to change the appearance of the created form by using css. here is the simple code i use create.html {% block content %} <h4 class="mb-3">Form Order</h4> <form action="." method="post" class="order-form"> {{ form.as_p }} <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button> {% csrf_token %} </form> {% endblock %} forms.py from django import forms from .models import Order class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city'] views.py from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() return render(request, 'created.html', {'order': order}) # launch asynchronous task order_created.delay(order.id) else: form = OrderCreateForm() return render(request, 'create.html', {'cart': cart, 'form': form}) I want to customize my forms.py fields with bootstrap css file, like following code <div class="row"> <div class="col-md-6 mb-3"> <label for="firstName">First name</label> <input type="text" class="form-control" id="firstName" placeholder="" value="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-md-6 mb-3"> <label for="lastName">Last name</label> <input type="text" class="form-control" id="lastName" placeholder="" … -
Django 1.11 Invalid Literal for ManytoMany field when saving form
I have a model that has a many to many field. When I try to save it, it errors out with a invalid literal for int() with base 10: 'A' error. From other posts I've read it looks like it's something to do with the CharField in my forms.py. In my clean_states, I can print the value for self.cleaned_data['title_states'] and get back the two letter code of the state. I thought that was what was going to be saved to the database. I'm not sure why it thinks I'm trying to save an int. models.py class States(models.Model): state = models.CharField(max_length=2, choices=US_STATES , null=True, blank=True) def __str__(self): return self.state class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) state = models.ManyToManyField(States) views.py class UserProfileUpdateView(LoginRequiredMixin, UpdateView): model = Person form_class = UserProfileChangeForm template_name = 'accounts/profile-update-view.html' def get_context_data(self, *args, **kwargs): context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs) context['states'] = States.objects.all() return context def get_object(self): qs = Person.objects.filter(pk=self.request.user.person.user_id).first() return qs forms.py class UserProfileChangeForm(forms.ModelForm): state= forms.CharField(widget=USStateSelect(), initial='TX') class Meta: model = SkilledLaborer fields = ['user','state'] def clean_user(self): user = self.cleaned_data['user'] return user def clean_state(self): state= self.cleaned_data['state'] return state -
python - DRF - KeyError on Date value when posting a JSON object
My problem is similar to what has been posted here but with some differences. I am writing a user creation web interface with Django (ver. 2) Rest Framework (ver. 3.7) on Python 3.6, using Django's AbstractUser class. My views.py: def post(self, request, format=None): serializer = UserProfileSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py : class UserProfileSerializer(serializers.ModelSerializer): avatar = Base64ImageField() official_docs = Base64ImageField() class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'password': {'write_only': True}, } def create(self, validated_data): hashed_password = make_password(validated_data['password']) # get the hashed password user = UserProfile( username=validated_data['username'], email = validated_data['email'], first_name= validated_data['first_name'], last_name= validated_data['last_name'], phone_number=validated_data['phone_number'], avatar=validated_data.pop('avatar'), gender=validated_data['gender'], city=validated_data['city'], description=validated_data['description'], date_of_birth=validated_data.pop('date_of_birth'), official_docs=validated_data.pop('official_docs'), team_name=validated_data['team_name'], debit_card_number=validated_data['debit_card_number'], favorite_music=validated_data['favorite_music'], ) user.set_password(hashed_password) user.save() return user Now when I post a JSON string to create user, I always have below error : File "views.py" in post 27. serializer.save() File ".virtualenvs/Django/lib/python3.6/site-packages/rest_framework/serializers.py" in save 214. self.instance = self.create(validated_data) File "serializers.py" in create 36. date_of_birth=validated_data.pop('date_of_birth'), Exception Type: KeyError at /users/ Exception Value: 'date_of_birth' I have checked different sources and tried different methods to deserialize and save the JSON object but had no luck. Can someone show me where my problem is? -
Ajax not work in Django post
I'm trying to use ajax in Django to post comment in a news website.However it doesn't work.When I click the submit button,it still refreshes the page and make no difference like no ajax. I'm really new in Django and Ajax.Any friend can help me solve it? Here is my view.py: def newsDetailView(request, news_pk): news = News.objects.get(id=news_pk) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): if not request.user.is_authenticated: return render(request, 'login.html', {}) comments = comment_form.cleaned_data.get("comment") news_comment = NewsComments(user=request.user, comments=comments, news=news) news_comment.save() return render(request, "news_detail.html", { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, 'comment_form': comment_form }) Here is my news_detail template where I get form data: {% if user.is_authenticated %} <form id="js-pl-submit" method="POST" action="">{% csrf_token %} {% for field in comment_form %} {% for error in field.errors %} <div class="alert alert-warning text-center mb-3" role="alert">{{ error }}</div> {% endfor %} {% endfor %} Here in my news_detail template I render all the comments to the template: {% for user_comments in all_comments %} <img class="mr-3 comment-avatar rounded-circle"src="{{ MEDIA_URL }}{{ user_comments.user.image }}"alt="Generic placeholder image"> … -
get() returned more than one Friend -- it returned 2
I'm trying to create a django app in which one user can add other user as Friend. Here's what I did, models.py, class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='all', null=True) views.py # view for adding or removing friends def change_friends(request, pk): new_friend = User.objects.get(pk=pk) data = Friend.objects.get(current_user=request.user) frnds = data.users.all() new_friend in frnds: data.users.remove(new_friend) else: data.users.add(new_friend) redirect(request.META['HTTP_REFERER']) # Displaying frinends, def following(request, id=None): my_friend, created = Friend.objects.get_or_create(current_user_id=id) all_friends = my_friend.users.all() return render(request, 'all/follow.html', {'all_friends': all_friends}) This code was working fine until I added friends from 1 account only, but when I added several friends from several accounts it started showing an error get() returned more than one Friend -- it returned 2!. How can we fix that? Thank You! -
django 1.11.x -> 2.x migration. I got the incorrect 'group by' fields
I just upgraded the Django version. The model or code has not been modified in my app. But... I get different results QuerySet. Fields specified in 'Group by' are different when printing a 'query'. Model: class Content(models.Model): id_field = models.AutoField(db_column='id_', primary_key=True) ... collections = models.ManyToManyField('Collection', through='CollectionMap', through_fields=('contentid', 'collectionid')) class CollectionMap(models.Model): field_index = models.AutoField(db_column='_index', primary_key=True) collectionid = models.ForeignKey(Collection, on_delete=models.CASCADE, db_column='collectionid') hwahaeplusid = models.ForeignKey(Content, on_delete=models.CASCADE, db_column='hwahaeplusid') field_time = models.DateTimeField(db_column='_time') Code: Content.objects\ .annotate(count=Count('id_field')\ .values('id_field', 'collections__name') Group By fields: Version 1.11.X : GROUP BY Content.id Version 2.X : GROUP BY Content.id, Collection.Name I want this... '... GROUP BY Content.id ...' What should I do?? -
multiple many to many relationships with the same two classes - django
I have two classes that have two many to many relationships between them. Since the adjoining tables also have to have additional attributes, I explicitly defined them. But I'm getting an error that says I need to change the related names. Not sure where to do this.. Any help is greatly appreciated. Here's my models.py code: class Client(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __repr__(self): return "<User object: {} {} {} {}>".format(self.first_name, self.last_name, self.email, self.password) class Therapist(models.Model): name = models.CharField(max_length=255) reviews = models.ManyToManyField(Client, through="Review") appts = models.ManyToManyField(Client, through="Appointment") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __repr__(self): return "<Book object: {}>".format(self.title) class Review(models.Model): reviewer = models.ForeignKey(Client, on_delete=models.CASCADE) therapist_reviewed = models.ForeignKey(Therapist, on_delete=models.CASCADE) rating = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.TextField() def __repr__(self): return "<Review object: {} {}>".format(self.book_reviewed, self.reviewer) class Appointment(models.Model): booked_therapist = models.ForeignKey(Therapist, on_delete=models.CASCADE) booked_client = models.ForeignKey(Client, on_delete=models.CASCADE) date = models.DateTimeField() massage = models.CharField(max_length=255) -
Celery, Django, Redis meet Error 99 when deploy with docker
I'm try to deploy my Django project and celery in docker, and I want to use redis as the result backend. My docker-compose.yml are as follows: python: image: python:latest restart: always expose: - "8000" volumes: - ~/django/902Scratch/API:/home/django/API - /var/sb2_files:/var/sb2_files - /home/tuopinpin/JudgeServer/tests/test_case:/test_case links: - celery:celery command: bash -c " cd /home/django/API && python manage.py runserver 0.0.0.0:8000" ports: - "0.0.0.0:8000:8000" celery: image: python:latest restart: always volumes: - ~/django/902Scratch/API:/home/django/API - /var/sb2_files:/var/sb2_files user: nobody depends_on: - redis links: - redis:redis command: bash -c " cd /home/django/API && celery -A API worker" redis: image: redis:alpine restart: always expose: - '6379' ports: - '6379:6379' The celery setting in django are like follows: CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_BROKER_TRANSPORT = 'redis' CELERY_RESULT_BACKEND = "redis" CELERY_BACKEND_URL = 'redis://redis:6379/1' and celery -A proj report command return info like this celery_1 | software -> celery:4.1.0 (latentcall) kombu:4.1.0 py:3.6.5 celery_1 | billiard:3.5.0.3 redis:2.10.5 celery_1 | platform -> system:Linux arch:64bit, ELF imp:CPython celery_1 | loader -> celery.loaders.app.AppLoader celery_1 | settings -> transport:redis results:redis celery_1 | celery_1 | ABSOLUTE_URL_OVERRIDES: { celery_1 | } celery_1 | ADMINS: [] celery_1 | ALLOWED_HOSTS: ['*'] celery_1 | APPEND_SLASH: True celery_1 | AUTHENTICATION_BACKENDS: celery_1 | ('django.contrib.auth.backends.ModelBackend',) celery_1 | AUTH_PASSWORD_VALIDATORS: '********' celery_1 | AUTH_USER_MODEL: 'scratch_api.BaseUser' celery_1 | AVATAR_AUTO_GENERATE_SIZES: celery_1 | (160, … -
Django + WSGI + Apache apps fail after idle time
Using Django 1.11, Python 2.7, and mod_wsgi 4.3 in an Ubuntu and Apache environment. I'm pretty sure this is a configuration issue, and I'm happy to provide more information if this isn't enough. In my Apache configuration file I have: Include "/home/django/wsgi-aliases" WSGIApplicationGroup %{GLOBAL} In the WSGI aliases file indicated above, I have the aliases for my various Django apps written out, along with a specification for WSGI daemon mode. Example: WSGIScriptAlias /EmployeeDirectory /home/django/EmployeeDirectory/EmployeeDirectory/wsgi.py process-group=EmployeeDirectory WSGIDaemonProcess EmployeeDirectory display-name=WSGI_EmployeeDirectory Alias /static/EmployeeDirectory /home/django/EmployeeDirectory/EmployeeDirectoryApp/static This all works just fine unless the process stays idle, at which point the page in question breaks, and will not work again without an Apache graceful restart. One more piece of information: this problem occurs only with apps that utilize either LDAP, or the authentication API to our content resource provider. My apps that utilize neither of these have no issues. An example error message: {'info': 'Connection reset by peer', 'errno': 104, 'desc': "Can't contact LDAP server"} It occurs to me that both the LDAP and API connections, respectively, time out if they are not used. But this was never an issue when these apps ran in non-daemon mode (which I recognize is not recommended and is why … -
python,django, solr, haystack: arg_parse error when editing solr_build_schema BaseCommand.add_argument()
Please help....i am trying use solr, pysolr and haystack on my django site search. I have edited the haystack build_solr_schema script to use BaseCommand.add_argument(), removing the default options_list. Below are my versions used; Python 3.5.2 Django 1.11.11 solr-7.3.0 django-haystack 2.4.0 pysolr 3.7.0 # encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import sys from optparse import make_option from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.template import Context, loader from haystack import constants from haystack.backends.solr_backend import SolrSearchBackend class Command(BaseCommand): help = "Generates a Solr schema that reflects the indexes." def add_arguments(self, parser): # positional arguments parser.add_argument("-f", "--filename", action="store", type="string", dest="filename", help='If provided, directs output to a file instead of stdout.',), # optional positional arguments parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.') """ base_options = ( make_option("-f", "--filename", action="store", type="string", dest="filename", help='If provided, directs output to a file instead of stdout.'), make_option("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.'), ) option_list = BaseCommand.option_list + base_options """ def handle(self, **options): """Generates a Solr schema that reflects the indexes.""" using = options.get('using') schema_xml = self.build_template(using=using) if options.get('filename'): self.write_file(options.get('filename'), schema_xml) else: self.print_stdout(schema_xml) def build_context(self, using): from haystack import connections, … -
Automatically Deploy App on Heroku Based on User Creation
I have a Multi-Tenant Django Application working with Postgres on Heroku. Is there a way to actually instantiate a new dyno/db/subdomain based on when a new User is created on my application? -
Django Admin Inlines and AbstractUser
I'm having issues with trying to have MtoM in my admin.py. I keep getting an error that says: <class 'demo.admin.CustomUserAdmin'>: (admin.E013) The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from app.forms import CustomUserCreationForm, CustomUserChangeForm from app.models import User, GroupUser, RoleAssign class GroupUserInline(admin.TabularInline): model = GroupUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User inlines = [ GroupUserInline, ] admin.site.register(User, CustomUserAdmin) and these are my models: #models.py class Group(models.Model): name = models.CharField(max_length=240) roles = models.ManyToManyField(Role, through='RoleAssign') class User(AbstractUser): username = models.CharField(max_length=240, blank=False, null=False, unique=True) password = models.CharField(max_length=256, blank=False, null=False) email = models.EmailField(max_length=256, blank=False, null=False, unique=True) S3 = models.TextField() groups = models.ManyToManyField(Group, through='GroupUser') class GroupUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) group = models.ForeignKey(Group) Does anyone have any details why my inline may not be working? Or should I be trying a different method? -
Python Julian date to Gregorian date conversion error
i get the error message:an integer is required when i am try to convert from Julian date to Gregorian date in my view.py, after i have query the db i want to convert the date_entered from Julian date to Gregorian date but i got the above error. inside view.py convert_date=(datetime.date.fromordinal(rate.columns.date_entered)) -
Django -- Order by Date (Desc) but Leave Selected Items At End
Can't get my head around how to do this in Django (or if its possible) but figured I'd ask. I would like to sort my items from my model by date with most recent items listed first. BUT, I would also like to have any items marked as EXPIRED=True to go to the end of the list, regardless of date posted. Thus the order might look something like this. Item A Date: Today Expired: False Item B Date: Yesterday Expired: False Item C Date: Today Expired: True Item D Date: Yesterday Expired: True Any ideas? -
ModuleNotFoundError not finding rest_framework on Heroku in my Django application
When attempting to push my Django code to Heroku, this is the feedback I receive: > $ git push heroku master Counting objects: 8, done. Delta compression using up to 4 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (8/8), 704 bytes | 704.00 KiB/s, done. Total 8 (delta 6), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing pip remote: Skipping installation, as Pipfile.lock hasn't changed since last deploy. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'rest_framework' remote: remote: ! Error … -
Django - override get_queryset
I'm new in python and django. I implemented a custom queryset to handle active/deactive and I also installed a package to handle softdelete and it works nice. but when I add my custom model manager to the model (to handle active), it affect softdelete abstract model and all deleted rows return in admin panel! my code: class QuestionModelQuerySet(SoftDeleteQuerySet): def active(self): return self.filter(active=True) class QuestionModelManager(SoftDeleteManager): def get_queryset(self): return QuestionModelQuerySet(self.model, using=self._db) def all(self, *args, **kwargs): qs = self.get_queryset().active() return qs if I append .filter(deleted_at__isnull=True) at the end of get_queryset() , all thing will fix! but I don't want to do this! because I think it's wrong and it's not a good solution. I want a better solution. thanks -
Django-reversion : incompatible version data during field_dict access
I have the following script: import django import os import sys from django.db import transaction from xxx.models import File import reversion from reversion.models import Version from datetime import datetime # Creating a file entry in here: with reversion.create_revision(): f = File(name="foo", mtime=datetime.now(), ctime=datetime.now(), size=33) f.save() reversion.set_comment("Revision 1") # Modifying it: with reversion.create_revision(): f.mtime = datetime.now() f.ctime = datetime.now() f.size = 23 f.save() reversion.set_comment("Revision 2") versions = Version.objects.get_for_object(f) print(len(versions)) for i in range(len(versions)): print(versions[i]) print(versions[i].field_dict) # ERROR! print(versions[i].revision.__dict__) Here's the very long traceback: Traceback (most recent call last): File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 166, in Deserializer data[field.name] = field.to_python(field_value) File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1246, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 241, in _object_version return list(serializers.deserialize(self.format, data, ignorenonexistent=True))[0] File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 168, in Deserializer raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value) django.core.serializers.base.DeserializationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."]: (xxx.file:pk=foo) field_value was '2018-04-24T21:38:14.319' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "play_with_reversion.py", line 47, in … -
Getting button to only show up to certain LDAP groups Django
I have a Django app that uses ldap authentication, and I want certain groups that are "flagged" to see something to be able to see it on login, but other groups to not be able to see it. I've been searching for a way to do this but to no avail. Is this even possible, or do I have to simply load an identical page to the flagged user that has a button on it? I am creating the button using bootstrap 4.0 CSS. -
Django/Python - Serial line concurrency
I'm currently working on gateway with an embedded Linux and a Webserver. The goal of the gateway is to retrieve data from electrical devices through a RS485/Modbus line, and to display them on a server. I'm using Nginx and Django, and the web front-end is delivered by "static" files. Repeatedly, a Javascript script file makes AJAX calls that send CGI requests to Nginx. These CGI requests are answered with JSON responses thanks to Django. The responses are mostly data that as been read on the appropriate Modbus device. The exact path is the following : Randomly timed CGI call -> urls.py -> ModbusCGI.py (import an other script ModbusComm.py)-> ModbusComm.py create a Modbus client and instantly try to read with it. Next to that, I wanted to implement a Datalogger, to store data in a DB at regular intervals. I made a script that also import the ModbusComm.py script, but it doesn't work : sometime multiple Modbus frames are sent at the same time (datalogger and cgi scripts call the same function in ModbusComm.py "files" at the same time) which results in an error. I'm sure this problem would also occur if there are a lot of users on the server … -
django input without forms not binding
I am working on paginator in django template and using inpput for entering user desired page# as below code snippet. For some reason the value entered by user is not persisted <div class="col-md-6 text-left"> {% if items.has_other_pages %} <div class="btn-group" > {% if items.has_previous %} <button type="button" class="btn btn-default btn-md page-first" onclick="location.href='?pagenumber=1&limit={{rows}}';">First</button> <button type="button" class="btn btn-default btn-md page-arrows" onclick="location.href='?pagenumber={{ items.previous_page_number }}&limit={{rows}}';">&laquo;</button> {% else %} <button type="button" class="btn disabled" >First</button> <button type="button" class="btn disabled">&laquo;</button> {% endif %} </div> <span><b>Page </b></span> <input type="text" style="width:50px" onchange="location.href='?pagenumber={{usernumber}}&limit={{rows}}';" value="{{usernumber:default:items.number}}" > <span> of {{items.paginator.num_pages}}</span> <div class="btn-group" > {% if items.has_next %} <button type="button" class="btn btn-default btn-md page-arrows" onclick="location.href='?pagenumber={{ items.next_page_number }}&limit={{rows}}';">&raquo;</button> <button type="button" class="btn btn-default btn-md page-last" onclick="location.href='?pagenumber={{ items.paginator.num_pages }}&limit={{rows}}';">Last</button> {% else %} <button type="button" class="btn btn disabled">&laquo;</button> <button type="button" class="btn disabled" >Last</button> {% endif %} </div> {% endif %} </div> the usernumber always shows up as empty in other words, it will default to items.number which is current page, if I remove default then it always shows empty <input type="text" style="width:50px" onchange="location.href='?pagenumber={{usernumber}}&limit={{rows}}';" value="{{usernumber:default:items.number}}" > <input type="text" style="width:50px" onchange="location.href='?pagenumber={{usernumber}}&limit={{rows}}';" value="{{usernumber}}" > and if I try to print as below <input type="text" style="width:50px" onchange="location.href='?pagenumber={{usernumber}}&limit={{rows}}';" value="{{usernumber}}" > The value {{usernumber}} It always shows as empty The value -
Override Django Password Reset
I was able to set up a Custom User using AbstractUser. I'm trying to find a way to use Django's Password Reset Class to reset my users. So I implemented it the way it is normally used but I get ProgrammingError: column app_user.date_joined does not exist or app_user.is_active does not exist. I shouldn't have to add any of these fields to my AbstractUser and I'm sure there is a way to override the Django auth. Does anyone know how?