Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CustomUser has no attribute 'objects'
I am using jwt auth system When I fill the field it returns jwt token easily but if i want to create a profile with this token it says CustomUser has no attribute 'objects' my users/models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(default=timezone.now) object = UserManager() USERNAME_FIELD = 'email' def save(self, *args, **kwargs): super(CustomUser, self).save(*args, **kwargs) return self and user/views.py class CreateUserAPIView(APIView): permission_classes = (AllowAny,) def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) serializer.save() try: email = request.data['email'] password = request.data['password'] user = CustomUser.object.get(email=email, password=password) if user: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) user_details = {} user_details['id'] = "%s" % (user.id) user_details['token'] = token user_logged_in.send(sender=user.__class__, request=request, user=user) return Response(user_details, status=status.HTTP_200_OK) except Exception as e: raise e else: return Response(status=status.HTTP_403_FORBIDDEN) except KeyError: res = {'error': 'please provide a email and a password'} return Response(res) with this code I am getting a token but with this token I cannot create a profile profile/models.py class Profile(TimeModel): user = models.OneToOneField('user.CustomUser', on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image = models.ImageField(upload_to='path', null=True) def __str__(self): return self.user.email here what i have tried so far. I tried … -
Want to install Django in Ubuntu
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/virtualenv.pyc' Consider using the --user option or check the permissions. -
FileField .full_clean() makes my app behave strange
I'm using a FileField in my models. I have added a validator to it and I'm running .full_clean() so it is ran. I'm getting this error everytime: {'CV': ['This field cannot be blank.']} C:\Users\PC\Desktop\bestVENV\myvenv\bestWEB\oferte\views.py in incarcarecv cv_upload.full_clean() As if the file size exceeds the limit and it is not uploaded because of that. The strange thing is that the file size does not exceed the limit so it should be working, but I just can't get why it does not. views.py from django.shortcuts import render, get_object_or_404 from .models import Oferta, CV from django.contrib import messages from django.core.paginator import Paginator # Create your views here. def incarcarecv(req): context = { 'title': "Incarcare CV | Best DAVNIC73" } if req.method == 'POST': nume = req.POST['nume'] prenume = req.POST['prenume'] telefon = req.POST['telefon'] email = req.POST['email'] cv = req.FILES['CV'] if(req.user.is_authenticated): cv_upload = CV( solicitant=req.user, nume=nume, prenume=prenume, telefon=telefon, emailContact=email ) cv_upload.full_clean() cv_upload.CV.save(cv.name, cv) cv_upload.save() req.user.profile.cvuri.append(cv_upload.id) req.user.profile.save() messages.success(req, 'CV depus cu succes!') else: messages.error(req, 'Trebuie sa fii logat pentru a depune CV-ul!') return render(req, "../templates/pagini/incarcare-cv.html", context) validators.py from django.core.exceptions import ValidationError def validate_file_size(value): filesize=value.size if filesize > 99999999999: raise ValidationError("Fisierul poate avea maxim 5MB!") else: return value models.py from django.db import models from django.contrib.auth.models import User … -
I am having trouble in using list Api view with custom pagination classes in django
I am using ListAPIView in drf along with custom pagination class, but it's only returning the total count correct and the result as an empty array. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } Custom Classes from rest_framework.pagination import LimitOffsetPagination class CustomLimitAndOffset(LimitOffsetPagination): default_limit=100 limit_query_param='limit' offset_query_param='offset' max_limit=100 views.py class bankDetails(ListAPIView): queryset=BankDetails.objects.all() serializer_class = BankDetailsSerializer pagination_class = CustomLimitAndOffset filter_backends = [DjangoFilterBackend] filterset_fields = ['bank_name', 'city'] result { "count": 55, "next": null, "previous": "http://127.0.0.1:8000/? bank_name=ABHYUDAYA+COOPERATIVE+BANK+LIMITED&city=MUMBAI&limit=100", "results": [] } -
Unique together involving multiple foreign keys & a many to many field
Our business' pricing is dependent on multiple parameters, and now we want to introduce another possible M2M parameter to the existing setup in Django. For this, we have an existing table for pricing, which has a unique_together constraint on all fields except the price_field. Apologies for the generic / letter-based naming in the example. class PricingTable(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) price = MoneyField() b = ArrayField(models.CharField(choices=CHOICES)) c = models.ForeignKey(C, on_delete=models.CASCADE) class Meta: ordering = ("a",) unique_together = ("a", "b", "c") def validate_b(self): # b can't be empty if not len(self.b) >= 1: raise ValueError # each element in b needs to be unique if not len(self.b) == len(set(self.b)): raise ValueError # each element in b needs to be unique together with a & c for i in self.b: query = PricingTable.objects.filter( a=self.a, c=self.c, b__contains=[i] ).exclude(pk=self.pk) if query.count() > 0: raise ValueError def save(self, *args, **kwargs): self.validate_b() return super().save(*args, **kwargs) I want to introduce another parameter to this table which has to be unique_together with the non-price params (a, b & c). d = models.ManyToManyField("x.D", related_name="+") The issue with the above is that the validate_b function has to be upgraded into a possibly complex function with heavy DB queries. Along with … -
How to upload file to Django Server with management command?
I am writing a management command to upload a file to my server. I am able to upload the file to media properly when the file is in the project folder. But i couldn't manage to upload a file from outside the folder. Here is the version when the file is in project folder: def handle(self, *args, **options): try: log_module = LogModule.objects.get(customer__id=options['customer_id']) except LogModule.DoesNotExist: return storage = log_module.storage_limit log_objects = Log.objects.filter(module=log_module) for log_object in log_objects: storage -= (os.path.getsize('media/' + str(log_object.log_file)) / (1024 * 1024)) print('Available Storage: ' + str(storage)) if storage - os.path.getsize(options['file_path']) < 0: my_file = open(options['file_path'], 'rb') django_file = File(my_file) log = Log(module=log_module) log.log_file.save(django_file.name, django_file, save=True) else: print('Not Enough Storage Limit!!!') return And this is what i am trying to achieve: my_file = open(options['file_path'], 'rb') django_file = File(my_file) log = Log(module=log_module) log.log_file.save(django_file.name, django_file, save=True) When i try to run this management command, i am getting following error: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/hskl/.local/share/virtualenvs/ramtek_hotspot-fTktNGJ3/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/hskl/.local/share/virtualenvs/ramtek_hotspot-fTktNGJ3/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hskl/.local/share/virtualenvs/ramtek_hotspot-fTktNGJ3/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/hskl/.local/share/virtualenvs/ramtek_hotspot-fTktNGJ3/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/hskl/Projects/ramtek_hotspot/hotspot/modules/log_module/management/commands/upload_log.py", line 43, in handle log.log_file.save(django_file.name, … -
Create http request after model is saved
I've made an ip + port checker in python but I want to make it into a website with django, everything is kinda working but I have some issues, I don't know how to make it so it doesn't create an infinite loop, and if 1000 ip + ports are added to the database I don't want it to make 1000 connections at once. I haven't tried much because I don't know what to try. I've tried using from concurrent.futures import ThreadPoolExecutor with max_workors set to 10 so it only does 10 connections at a time but that kinda works but still have the issue of making an invite loop. the model save function def save(self, *args, **kwargs): # overwrite save function super().save(*args, **kwargs) # saves to database checker.check(self) # calls check function the check function inside checker.py def check(modelthing): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.ip, self.port)) modelthing.is_alive = True # sets is_alive to true if everything went ok except: modelthing.is_alive = False # sets is_alive false when exception is thrown modelthing.save() # ISSUE it saves the model again and it calls the save function that calls checker.check(self) witch creates an infinity loop It saves it to the database, calls … -
How to bind "loaded" javascript action to a variable?
Using Django templates, I'm trying to add a countdown in javascript. Putting the script explicitly in HTML does work but it doesn't when loaded. I think I'm close but I can't figure out what is missing :/. Here is a working piece of code : <!DOCTYPE html> <head> {% load staticfiles %} </head> <body> {% if remaining_time %} <script> function startTimer(duration, display) { var timer = duration; var end = setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { clearInterval(end); document.form_submit_answer.submit() } }, 1000); } window.onload = function () { var allowed_time_seconds = "{{remaining_time | safe}}", display = document.querySelector('#time'); startTimer(allowed_time_seconds, display); }; </script> {% endif %} {{ current_question.title }} <div> <form name="form_submit_answer" action="{% url 'assignment_completion' token current_question_num %}" method="post"> {% csrf_token %} {{ form }} <div> {% if next_question %} <input type="submit" value="Send your answer and go to the next question"> {% else %} <input type="submit" value="Send your answer and end the assignment"> {% endif %} </div> </form> </div> <div> … -
python manage.py test: django.db.utils.OperationalError: no such table: accounts_user
I'm fairly new at testing and while trying to run test for my django project using python manage.py test i end up getting django.db.utils.OperationalError: no such table: accounts_user. I have the User model within the accounts app and the accounts app has been added to installed app within my settings.py I've run makemgirations and migrate for all project apps, i've also gone into the project shell and try creating a user from User model in the accounts app and all of these works well, but when i run my test i get an error. below is the test i'm trying to run which generates the error from django.test import TestCase from django.contrib.auth import get_user_model class UserTestCase(TestCase): def setUp(self): USER = get_user_model() USER.objects.create( email="johndoe@example.com", first_name="John", last_name="Doe" ) USER.objects.create( email="janedoe@example.com", first_name="Jane", last_name="Doe" ) def test_user_full_name(self): """ A user's fullname correctly identified """ jane = USER.objects.get(email="janedoe@example.com") john = USER.objects.get(email="johndoe@example.com") self.assertEqual(jane.get_full_name(), "Jane Doe") self.assertEqual(john.get_full_name(), "John Doe") and below is the code i ran within project shell that works from django.contrib.auth import get_user_model USER = get_user_model() USER.objects.create( email="johndoe@example.com", first_name="John", last_name="Doe" ) USER.objects.create( email="janedoe@example.com", first_name="Jane", last_name="Doe" ) USER.objects.all() # returns both object that has been added and below is my database settings DATABASES = { 'default': … -
Django create effectively sitemap
I want to create effectively sitemap like this; sitename.com/post-sitemap.xml sitename.com/team-sitemap.xml How can i do ? sitemaps.py class PostSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Post.objects.published() def lastmod(self, obj): return obj.created_date -
Migrate fails on warning "'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release'
In my Django project I am trying to change a database field from OneToOne to ForeignKey. When I run 'python manage.py migrate', it breaks with a long traceback ending with the warning I quoted in the title. I know others have hit this problem, but I can't find a solution that gets me around it. I have added the following to my local_settings.py DATABASES: 'OPTIONS': { 'autocommit': True, 'charset': 'utf8mb4', } At first I tried simply changing OneToOne to ForeignKey but hit this problem. So I decided to do it in discrete steps by first deleting the field and later adding it with the new field type. But I can't even delete the field. Here is the migrations file that is produced by makemigrations and is the one that migrate breaks on: # Generated by Django 2.2.3 on 2019-07-18 09:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sweaters', '0011_auto_20190718_0954'), ] operations = [ migrations.RemoveField( model_name='sweater', name='yarn_for', ), ] Here is the full traceback I get: $ python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sweaters Running migrations: Applying sweaters.0012_remove_sweater_yarn_for...Traceback (most recent call last): File "/Users/frankjernigan/Documents/webdev/phrancko-web-dev/phrancko.com/phrancko-project/myenv/lib/python3.7/site-packages/django/db/utils.py", line 96, in inner return func(*args, **kwargs) … -
How to display text on the site from the admin site?
On the admin site, I create ConclusionName and RetrospectiveField. I need the fields baseText and comments to appear on the site under the word Application 2 'Retrospective' Conclusion (app) models.py class ConclusionName(models.Model): name = models.CharField(max_length=250) def __unicode__(self): return self.name class RetrospectiveField(models.Model): user = models.ForeignKey(User) conclusionName = models.ForeignKey(ConclusionName) baseText = models.TextField(max_length=255) comments = models.TextField(max_length=255) project = models.ForeignKey(Project) forms.py class RetrospectiveFieldForm(forms.Form): project = forms.ModelChoiceField(queryset=Project.objects.all(), label=u'Project') conclusionName = forms.ModelChoiceField(queryset=ConclusionName.objects.all(), label=u'ConclusionName') baseText = forms.TextField(max_length=255, label=u'BaseText') comments = forms.TextField(max_length=255, label=u'Comments') class Meta: model = RetrospectiveField fields = ('project', 'conclusionName', 'baseText', 'comments',) views.py def add_form_retrospective_field(request): if request.method == 'POST': form = RetrospectiveFieldForm(request.POST) if form.is_valid(): retro = RetrospectiveField() retro.user = User.objects.get(username=request.user) retro.project = form.cleaned_data.get('project') retro.conclusionName = form.cleaned_data.get('conclusionName') retro.baseText = form.cleaned_data.get('baseText') retro.comments = form.cleaned_data.get('comments') retro.save() return redirect('/') else: form = RetrospectiveForm() return render(request, 'completeness/forms_retrospective_field.html', {'form': form}) def showRetrospectiveField(request, slug): projects = Project.objects.filter(id=slug) retrospectiveFields = RetrospectiveField.objects.get(project=projects) return render(request, 'completeness/view_retrospectiveField.html', {'retrospectiveFields': retrospectiveFields}) conclusion/example.html {% extends 'completeness/base.html' %} {% load staticfiles %} {% load i18n %} {% block title %}{% trans 'Network' %}{% endblock %} {% block head %} <meta charset="UTF-8"> <title>Conclusion</title> <script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script> <link href="style.css" rel="stylesheet" /> <script src="script.js"></script> {% block js %} {{ form.media }} {% endblock %} {% endblock head %} {% block content %} <div … -
how to make resposive web with python code
I want to make website. It is first time to develope website. I don't have idea. Website will have community and news section. news section includes information which result of ptyhon code. I want to this web responsive. Actually I design homepage with javascript, html, css. But I stuck here. for making community section I heared that I need bootstrap? and react or vue for responsive web. and django for using python code. and I found thet are feamework. so, plz help me what I to do..... I know c, c++,python, java(little) -
How to display custom error messages in django rest framework
Here i am trying to create category and while creating category i want display some message like category created or if it gets fail to create the category i want to display some error message for this along with the status code.This code only displays the status code but how can i throw the error messages as well along with status code ? serializers.py class CategorySerializer(serializers. HyperlinkedModelSerializer): name = serializers.CharField( required=True, validators=[UniqueValidator(queryset=Category.objects.all())] ) class Meta: model = Category fields = ( 'id', 'name', 'description', 'parent_id', 'start', 'end', 'is_service', 'display_home', 'is_achievement_option', ) read_only_fields = ('id',) views.py @api_view(['POST']) @authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication)) @permission_classes((permissions.IsAdminUser,)) def add(request): if request.method == 'POST': serializer = CategorySerializer(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) -
python: can't open file 'manage.py': [Errno 2] No such file or directory in Docker
I try to setup docker on my machine. I follow there doc for setup I try to set up Django with MySQL here is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /testing WORKDIR /testing ADD requirements.txt /testing/ RUN pip install -r requirements.txt ADD . /testing/ here is my docker-compose.yml file version: "3" services: db: image: mysql # ports: # - '3306:3306' environment: MYSQL_DATABASE: "ishoErp" MYSQL_USER: "antu" MYSQL_PASSWORD: "secure" MYSQL_ROOT_PASSWORD: "secure" adminer: image: adminer restart: always ports: - 8080:8080 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/testing ports: - "8000:8000" depends_on: - db When I run this command $ sudo docker-compose run web django-admin.py startproject testing it successfully creates a django project but when I try to build by $ docker-compose up Its gives me this following error. docker_db_1 is up-to-date docker_adminer_1 is up-to-date Starting docker_web_1 ... done Attaching to docker_db_1, docker_adminer_1, docker_web_1 adminer_1 | PHP 7.3.7 Development Server started at Thu Jul 18 09:09:55 2019 db_1 | 2019-07-18T09:35:52.935567Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release. db_1 | 2019-07-18T09:35:52.935665Z 0 [System] [MY-010116] … -
Confused How to create an Evaluation form using Django
so guys I'm building django Evaluation form , that show the user 4 options (agree, highly agree, disagree, neutral) I did the models and forms but I don't know how to build the views! I tried and create the views but I think that I couldn't save the form in a proper way. I also did create the html page , the views and html are working but when I finish and press on submit button it throw this error "Environment: Request Method: POST Request URL: http://127.0.0.1:8000/evaluation/form/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cal', 'crispy_forms', 'phone_field', 'django_countries', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Development\LMS\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Development\LMS\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Development\LMS\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Development\LMS\django-calendar\cal\views.py" in evaluation_view 186. evaluation.save() File "C:\Development\LMS\lib\site-packages\django\db\models\base.py" in save 741. force_update=force_update, update_fields=update_fields) File "C:\Development\LMS\lib\site-packages\django\db\models\base.py" in save_base 779. force_update, using, update_fields, File "C:\Development\LMS\lib\site-packages\django\db\models\base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Development\LMS\lib\site-packages\django\db\models\base.py" in _do_insert 908. using=using, raw=raw) File "C:\Development\LMS\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Development\LMS\lib\site-packages\django\db\models\query.py" in _insert 1186. return query.get_compiler(using=using).execute_sql(return_id) File … -
form not saving data in db
i'm creating a form for product create and i have 5 image fields in product model ,user can upload 5 or 0 images as per requirement , but form is not saving data python models.py class Category(models.Model): cate_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=45) class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=45) product_description = models.CharField(max_length=500, blank=True, null=True) price = models.IntegerField() quantity = models.IntegerField() product_category_fk = models.ForeignKey('Category', on_delete=models.CASCADE,db_column='product_category_fk',related_name='pros') image1 = models.ImageField(upload_to='chand_imgs',blank=True) image2 = models.ImageField(upload_to='chand_imgs',blank=True) image3 = models.ImageField(upload_to='chand_imgs',blank=True) image4 = models.ImageField(upload_to='chand_imgs',blank=True) image5 = models.ImageField(upload_to='chand_imgs',blank=True) #forms.py class CategoryForm(forms.ModelForm): category_name = forms.CharField(max_length=50) class Meta: model = Category fields = ('category_name', ) class ProductForm(forms.ModelForm): class Meta(): model = Product fields = ('product_category_fk','product_name','product_description','price','quantity','image1','image2','image3','image4','image5',) #views.py @login_required def product_management(request): form = ProductForm(data=request.POST) if request.method =='POST': if form.is_valid(): post=form.save(commit=True) if 'picture' in request.FILES: form.picture =request.FILES['picture'] return HttpResponseRedirect(reverse('index')) else: return render(request,'chandler/index.html',{'form':form}) else: form = ProductForm() return render(request,'chandler/product.html',{'form':form}) #product.html {% if user.is_authenticated %} <form method=”post” enctype=”multipart/form-data” action="" > <h2>New post</h2> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% else %} <h2>Please login first!!!!</h2> {% endif %} form not saving any data i know my view is incorrect ,already tried different methods -
PWA offline service worker settings
I am building a simple Progressive Web Application with Python Django and django-pwa package. I have set up everything but offline functionality is not working. At this point, service workers (SW) are installed and dev tools recognize application as PWA. But when I check "offline" in devtools->Application and reload the web page there is a "No internet connection" error. Here are my SW settings: var staticCacheName = 'djangopwa-v1'; var filesToCache = [ '/', '/x_offline/', '/static/x_django_pwa/images/my_app_icon.jpg', '/media/images/bfly1.2e16d0ba.fill-320x240.jpg', ]; // Cache on install self.addEventListener("install", event => { this.skipWaiting(); event.waitUntil( caches.open(staticCacheName) .then(cache => { return cache.addAll(filesToCache); }) ) }); // Clear cache on activate self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(cacheNames => { return Promise.all( cacheNames .filter(cacheName => (cacheName.startsWith("djangopwa-v1"))) .filter(cacheName => (cacheName !== staticCacheName)) .map(cacheName => caches.delete(cacheName)) ); }) ); }); // Serve from Cache self.addEventListener("fetch", event => { event.respondWith( caches.match(event.request) .then(response => { return response || fetch(event.request); }) .catch(() => { return caches.match('x_offline'); }) ) }); Listed settings are almost the same as default one from django-pwa repo When I load the page for the first time I see that requests are also made for the urls listed in SW and all of them have status 200. In the cache storage I see … -
Django 2 form is_valid is not working even on valid form
I'm working on a very simple form to post data in Django(2) but always getting the form as invalid because the form.is_valid() not getting called. Here's what I have so far: From models.py: class UserGroup(models.Model): email = models.EmailField(primary_key=True) group = models.CharField(max_length=250, default='notingroup') def __str__(self): return self.group From forms.py: class UserGroupForm(forms.ModelForm): class Meta: model = UserGroup fields = ('group', 'email') From views.py: def group_name(request): error = '' if request.method == 'POST': print(request.POST['email']) group_form = UserGroupForm(request.POST) print(group_form) if group_form.is_valid(): ug_obj = UserGroup() ug_obj.group = group_form.cleaned_data['group'] ug_obj.email = group_form.cleaned_data['email'] ug_obj.save() return JsonResponse({"message": 'Got it inside valid'}) else: error = 'Something went wrong' print(error) return JsonResponse({"message": 'an error occurs!'}) From html template: <form method="post" id="gitForm" action="javascript:call_my_form()"> {% csrf_token %} <label>Groupname: </label> <input id="user_email" type="text" value="{{ user.email }}" hidden> <input id="input" type="text" class=""> <input type="submit" value="Mehet" class="btn btn-primary"> <div id="error" style="color:red"></div> </form> From javasctip function for Ajax: function call_my_form() { $(document).on('submit', '#gitForm', function (e) { e.preventDefault(); console.log($('#input').val()); console.log($('#user_email').val()); $.ajax({ type: 'POST', url: '/groupname', data: { group: $('#input').val(), email: $('#user_email').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (jsonResponse) { document.getElementById("demo").innerHTML = jsonResponse.message; } }).done(function (jsonResponse) { document.getElementById("demo").innerHTML = jsonResponse.message; }) }); } I'm getting the correct data into the view but still the form.is_valid() not get called, Here's … -
CreateWithInlineView - get id from the inline before
I use "django-extra-views" to make it possible to use multiple models in one CreateView. So I want to set all things about an article like article number (first step), then all informations about the article like text, images, documents and more with one post/submit. All informations about the article are in different models with a relationship to the model "article_number". example: models.py class article_number(models.Model): article_no = models.CharField( _('article_no') ,blank=False, null=False, max_length=30) description = models.TextField( _('description') ,blank=True ,null=True, default='') class article_document(models.Model): article_no = models.ForeignKey(article_number, on_delete=models.CASCADE, related_name = 'ad_article_number', verbose_name='article no') file_type = models.ForeignKey(file_type, on_delete=models.CASCADE, related_name = 'ad_file_type', verbose_name='file type') file_name = models.CharField(_('file Name'),max_length=100, blank=False) file = models.FileField(_('file'),upload_to="product/document/", blank=True, null=True) file_created = models.DateTimeField(_('file created'),auto_now_add=True) language_code = models.ManyToManyField(language_code, blank=True) example: views.py class article_documentInline(InlineFormSetFactory): model = article_document fields = ['file_type', 'file_name', 'file', 'language_code'] class ArticleNumberCreateView(SuccessMessageMixin, CreateWithInlinesView): model = article_number inlines = [article_documentInline, ...] fields = ['article_no', 'description'] template_name = 'to_template.html' success_message = _('Article successfully created') -
Django- Clear user cache when user logged out
I am using django.core.cache to store user roles related data in the cache. The user roles are stored as keys roles_<user.id> in the cache. I want to delete the roles_<user.id> key from the cache whenever theuser logs out from the system. I used the user_logged_out auth signal for this but somehow this signal is not working(not deleting the cache data). I have created a receiver in signals.py as: def clear_user_cache(sender, user, request, **kwargs): cache.delete('roles_{}'.format(user.id)) user_logged_out.connect(clear_user_cache) My logout url is: url(r'^accounts/logout/', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='auth_logout'), Logout in template: <a class="dropdown-item" href="{% url 'auth_logout' %}"><i class="la la-sign-out"></i>{% trans 'Logout' %}</a> When I hit the logout button, the user is logged out but the cache is not being cleared. If I try printing some statements in the signal receiver, they are not getting printed. I though the url in the template might have caused this problem so I tried changing it to: <a class="dropdown-item" href="/logout"><i class="la la-sign-out"></i>{% trans 'Logout' %}</a> But still nothing happened. How can I make the logout signal to fire when the user is logged out? I am using Django==1.8.18 and python2.7 -
Here is a link . How is the random string f6909.... Generated?
I got an email for verification . http://xyz.pythonanywhere.com/record/upload/f690928d034d27ebb943b3f9bc9e3ae9/12. How is the string f6909..... Generated and is there a way to find out the pattern ? Is there any function which is generating the random string for different email addresses ? -
Django admin panel list_display show none even after fetching data
I am displaying data in django admin panel for many to many relationship table. I got None instead of list of names. I am using python: 3.6 and django: 2.2 List_display for ManytoMany fields in Admin panel I had also already asked question related with this and change my model too as no one answer over there. models: class Assessment(models.Model): name = models.CharField(max_length=255) class Participant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=255,blank=True,null=True) class Seminar(models.Model): topic = models.CharField(max_length=255) assessment = models.ManyToManyField(Assessment,blank=True) participant = models.ManyToManyField(Participant,blank=True,through='SeminarParticipant',through_fields=('seminar','participant')) class SeminarParticipant(models.Model): seminar = models.ForeignKey(Seminar,blank=True,on_delete=models.CASCADE) participant = models.ForeignKey(Participant,blank=True,on_delete=models.CASCADE) request_time = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0),]) is_survey_completed = models.BooleanField(default=False) admin: @admin.register(Seminar) class SeminarAdmin(admin.ModelAdmin): list_display = ('topic''assessment') def assessment(self,obj): return "\n".join([item for item in obj.assessment.all()]) I was expecting name of assessment in list_display of seminar admin but got assessments.Assessment.None in list_display of admin panel. NEED HELP!!! Already had asked. No one answer. I changed my model and again it is messed up. Please advice me If I am making my models incorrect. This is my first project in django. -
get data from model in view
I have two tables Category and book My Category table with the book table has one-to- many links,that's mean one category can have several books Now I want to display 6 books from each category on my homepage How should I get the information? -
How would I display "New account is created" message after new user have registered
My concern is I want after a user is registered a message should display indicating that a user is registered, I have already added a script but when I click a sign up button a message pop up even I have not registered a user. I am not sure where and how should I place my scripts but I guess if function is required. Help!! views.py def register(request): if request.method == "POST": user_form = UserCreationForm(request.POST) if user_form.is_valid(): user = user_form.save() username = user_form.cleaned_data.get('username') messages.success(request, f"New account created:{username}") login(request, user) return redirect("loststuffapp:IndexView") else: for msg in user_form.error_messages: messages.error(request, f"{msg}:{form.error_messages[msg]}") return render(request = request, template_name = "loststuffapp/register.html", context={"user_form":user_form}) user_form = UserCreationForm return render(request = request, template_name = "loststuffapp/register.html", context={"user_form":user_form}) register.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit">Register</button></p> <script>M.toast({html: "New account is created", classes: 'blue rounded', displayLength:2000});</script> </form> <p>If you already have an account, <a href="/Register">login</a> instead</p> {% endblock %}