Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nickeditor works locally, but on cloud No
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> This works perfectly , when I run locally. But When I run on cloud its not working. I do not see html menu editor on cloud, why it works locally but not on cloud? any solution? https://i.stack.imgur.com/Hdtkn.png -
Is it possible in Django to iterate the creation of a model?
I'm trying to create a model with 100 columns. Is it possible to iterate in my models.py file to create many entries at once? This is an example of what I'm trying to accomplish. class AgeFactor(models.Model): ''' Used to populate a table with all the age-factor numbers ''' gender = models.CharField(max_length=50, null=True, blank=True) code = models.CharField(max_length=50, null=True, blank=True) event_code = models.CharField(max_length=50, null=True, blank=True) oc = models.DecimalField(max_digits=9, decimal_places=4) for lp in range(101): if lp > 4: (f"{lp} = models.DecimalField(max_digits=9, decimal_places=4)") Thank you. -
wsgi:error ModuleNotFoundError: No module named 'django'
I've looked everywhere for a solution. I can't figure out what is the matter. Maybe I'm not seeing an easy mistake or sometime. I'm using pyenv because during development I used python version 3.8.2 and Django 3.0.5. I also have a virtualenv setup and all the packages are installed when i do pip freeze. When I run which django nothing returns. I'm using apache 2.4 and Ubuntu 18.04 LTS. Thanks in advance. Any extra info needed let me know. Here's the config file: WSGIPythonPath /etutors-site/site-dj/etutorproject <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog /etutors-site/site/logs/error.log CustomLog /etutors-site/site/access.log combine alias /static /etutors-site/site/public/static <Directory /etutors-site/site/public/static> Require all granted </Directory> <Directory /etutors-site/site-dj/etutorproject/etutorproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess etutors-site python-path=/etutors-site/site-dj/etutorproject python-home=/etutors-site/venv WSGIProcessGroup etutors-site WSGIScriptAlias / /etutors-site/site-dj/etutorproject/etutorproject/wsgi.py </VirtualHost> Here is the exact error: [Fri May 15 21:12:27.762544 2020] [wsgi:error] [pid 9063:tid 140656260556544] [remote 72.51.112.97:22446] mod_wsgi (pid=9063): Target WSGI script '/etutors-site/site-dj/etutorproject/etutorproject/wsgi.py' cannot be loaded as Python module. [Fri May 15 21:12:27.762661 2020] [wsgi:error] [pid 9063:tid 140656260556544] [remote 72.51.112.97:22446] mod_wsgi (pid=9063): Exception occurred processing WSGI script '/etutors-site/site-dj/etutorproject/etutorproject/wsgi.py'. [Fri May 15 21:12:27.762899 2020] [wsgi:error] [pid 9063:tid 140656260556544] [remote 72.51.112.97:22446] Traceback (most recent call last): [Fri May 15 21:12:27.762931 2020] [wsgi:error] [pid 9063:tid 140656260556544] [remote 72.51.112.97:22446] File "/etutors-site/site-dj/etutorproject/etutorproject/wsgi.py", … -
Why does Celery periodic tasks fire a function only once
I've built a small web scraper function to get some data from the web and populate it to my db which works just well. Now I would like to fire this function periodically every 20 seconds using Celery periodic tasks. I walked through the docu and everything seems to be set up for development (using redis as broker). This is my tasks.py file in project/stocksapp where my periodically fired functions are: # Celery imports from celery.task.schedules import crontab from celery.decorators import periodic_task from celery.utils.log import get_task_logger from datetime import timedelta logger = get_task_logger(__name__) # periodic functions @periodic_task( run_every=(timedelta(seconds=20)), name="getStocksDataDax", ignore_result=True ) def getStocksDataDax(): print("fired") Now when I start the worker, the function seems to be fired once and only once (the database gets populated). But after that, the function doesn't get fired anymore, although the console suggests it: C:\Users\Jonas\Desktop\CFD\CFD>celery -A CFD beat -l info celery beat v4.4.2 (cliffs) is starting. __ - ... __ - _ LocalTime -> 2020-05-15 23:06:29 Configuration -> . broker -> redis://localhost:6379/0 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2020-05-15 23:06:29,990: INFO/MainProcess] beat: Starting... [2020-05-15 23:06:30,024: INFO/MainProcess] Scheduler: Sending due task … -
No module named 'app.settings' error when running app on heroku
I am this error when I try to run my app on heroku. I have no idea what's causing it ModuleNotFoundError: No module named 'deploytest.settings' 2020-05-15T21:02:25.372974+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-05-15T21:02:25.542793+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [4] [INFO] Shutting down: Master 2020-05-15T21:02:25.542795+00:00 app[web.1]: [2020-05-15 21:02:25 +0000] [4] [INFO] Reason: Worker failed to boot. Procfile web: gunicorn deploytest.deploytest.wsgi I get the same error when my procfile is web: gunicorn deploytest.wsgi wsgi.py: """ WSGI config for deploytest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'deploytest.settings') application = get_wsgi_application() settings.py """ Django settings for deploytest project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
How to access taggit.tag in html template
(as opposed to the WT2.9's new TagBase that gives each tagged model own "tag pool), The wagtail's "TaggedItemBase" tags lead to common "tag pool" even on different page models. How do I access it in the html template? AFAIU i need a get_context method on my page model that does something like context['all_tags'] = taggit.Tag.objects.all() , but I'm a noob, confused about how to write it correctly. -
Django, renaming Image files on upload
I am using Django 2.2 and Pillow library in the models fields to handle the image files. I studied a latest online course on Django where tutor used special method during image save to make sure that similarly named images will not override . But I noticed that when a user upload two different images with same name , Django renames the second file without any function and the files never conflicted when we retrieve. Is this a new feature in Django ? Should I follow file renaming convention ? -
django generic indexview and detailView
I am using generic views for list and details, on the index page I am getting my list but not getting my category list, but I am getting a category list on another template. I want to list the category on the index page, and on click of that category, image go to that list which is filter by that specific category. I hope you understand my question . below is the view for brand index and model for category class BrandsIndexView(generic.ListView): template_name = "brands/index.html" context_object_name = "latest_brands_list" def get_queryset(self): return Brands.objects.filter(created_on__lte=timezone.now()).order_by('-created_on')[:10] model for category class Category(models.Model): category_name = models.CharField(null=False,max_length=200) category_slug = models.SlugField( max_length=200, db_index=True, unique=True) category_image = models.FileField(upload_to="brand_cat_images",null=True,blank=True,validators=[file_ext]) -
Sending emails periodically with Django
I'm working with a dropshipping store in Django and I need to add a feature that sends a csv file every end of the day to my supplier. I'm working with python 3.8.2. I have used celery before, but it doesn't support my python version. I was thinking about using the django-admin commands, but I think that there may be a better option for this. Do you know any library/method to help me with this? Or those are the only options available? -
Django Token Authentication for an endpoint
Following is the sample API I have created and added token based authorisation using Django-Rest framework. @api_view(['GET']) def get_data(request): url = request.GET.get('url') final_ans = do_something() return JsonResponse(final_ans,safe=False) So now, users can access this API if they have token, but if they want to see the response in browser, they can hit the following url. http://localhost:8000/get_data?url=https://www.samplesite.com When they hit this, the browser is asking superuser credentials as shown in the below image. So obviously, we cant provide them the admin credentials, so is there a workaround to generate a unique password just to access this response in UI? -
Automatic result in Django without reload and button
How can I do that: after giving the numbers 'a' and 'b' I get an automatic result without reloading the page and using the buttons in Django: my views.py: def index(request): form = CalculatorForm() if form.is_valid(): a = form.cleaned_data['a'] b = form.cleaned_data['b'] result = a + b return render(request, 'calculator/main.html', {'form': form, 'result': result}) return render(request, 'calculator/main.html', {'form': form}) html: {% block content %} <form action="#" method="post"> {% csrf_token %} {{form}} Result: {{result}} ---> Automatic result without reload and button </form> {% endblock % -
ValueError at /articles/article/19 The 'article_image' attribute has no file associated with it
models.py from django.db import models from ckeditor.fields import RichTextField class Article(models.Model): author=models.ForeignKey("auth.User",on_delete=models.CASCADE,verbose_name="Yazar") title=models.CharField(max_length=50,verbose_name="Başlık") content=RichTextField(verbose_name="İçerik") created_date=models.DateTimeField(auto_now_add=True,verbose_name="Oluşturulma Tarihi") article_image=models.FileField(blank=True,null=True,verbose_name="Fotoğraf Ekleyin") def __str__(self): return self.title detail.html <img class="img-fluid rounded" src="{{articles.article.article_image.url}}" alt=""> when i want add image to my articles i get error and in my vs code it ot creare media folder although i can see my articles but without photo and i can see text like html code not notmal (sorry for bad english) 'The 'article_image' attribute has no file associated with it. ' i put all paths to settings.py but i couldnt solve it views.py from django.shortcuts import render,HttpResponse,redirect,get_object_or_404 from . import forms from .models import Article from django.contrib import messages # Create your views here. def index(request): # Sayfada gorunmesi istedigimiz fonksiyonlari bu klasore yaziyoruz return render(request,"index.html") # bunlada sayfaya index dosyasini ekliyoruz #return HttpResponse("Anasayfa") #Bu sekildede eklenebilir def about(request): return render(request,"about.html") def dashboard(request): articles=Article.objects.filter(author=request.user) context={ "articles":articles } return render(request,"dashboard.html",context) def addarticle(request): form =forms.ArticleForm(request.POST or None,request.FILES or None) if form.is_valid(): article=form.save(commit=False) # Formu kayd edecek ama bir degiskene atayacak commit=False o demekdirki auto kaydetme ozum manuel kayd edecem article.author=request.user article.save() messages.success(request,"Makale Başarıyla Oluşturuldu!") return render(request,"dashboard.html") context={ "form":form } return render(request,"addarticle.html",context) def showarticle(request,id): # article=Article.objects.filter(id=id).first() #listedeki gordugu ilk elemani alir article=get_object_or_404(Article,id=id) … -
how to create superuser in custom user model in django?
I am trying to make a superuser in the custom user model in Django. but after applying migrations no file creates in migration folder but it shows that migration is applied. after that when I try to make a superuser it gives an error as no-table found. here is my code that I have used to create custom user model in Django: from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email, username, age, name, password=None): if not email: raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, age, name, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", "name", "age",] objects = SignUpManager() def __str__(self): … -
Django polls app admin like form for users
I have followed the django docs starter app and have added in a login and register system using django.auth. I am looking to make it so that a user who has logged in can create a new poll and link the choices to the question automatically. Just like it is done in the django admin panel (see photo). In the admin.py, you use admin.TabularInLine and fieldsets but I am not sure how I can do this reuglarly in forms.py or views.py I can't seem to find much in the docs or anywhere else so if someone could get, that would be great.. admin.py from django.contrib import admin from .models import Question, Choice class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['date_posted']}) ] inlines = [ChoiceInLine] list_display = ('question_text', 'date_posted', 'was_published_recently') list_filer = 'date_posted' admin.site.register(Question, QuestionAdmin) models.py from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) date_posted = models.DateTimeField('Date published') def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.date_posted <= now was_published_recently.admin_order_field = 'date_posted' was_published_recently.boolean = True was_published_recently.short_description = 'Posted recently?' def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text … -
Django hitcount order_by("hit_count_generic__hits") gives error on PostgreSQL database
I was using django-hitcont to count the views on my Post model. I am trying to get the most viewed post in my ListView using this query objects.order_by('hit_count_generic__hits') and it is working fine on SQLite but on PostgreSQL, it is giving me this error : django.db.utils.ProgrammingError: operator does not exist: integer = text LINE 1: ...R JOIN "hitcount_hit_count" ON ("posts_post"."id" = "hitcoun.... models.py class Post(models.Model, HitCountMixin): author = models.ForeignKey(User, related_name='authors', on_delete=models.CASCADE) title = models.CharField('Post Title', max_length = 150) description = models.TextField('Description', max_length=1000, blank = True) date_posted = models.DateTimeField('Date posted', default = timezone.now) date_modifed = models.DateTimeField('Date last modified', default = timezone.now) document = models.FileField('Document of Post', upload_to='documents', \ validators=[FileExtensionValidator(allowed_extensions = ['pdf', 'docx']), validate_document_size] \ ) hit_count_generic = GenericRelation( HitCountModified, object_id_field='object_pk', related_query_name='hit_count_generic_relation' ) views.py queryset = Post.objects.order_by('hit_count_generic__hits') I found this issue on Github related to the problem, but I am still not able to figure out the mentioned workaround. -
Readable nested serializer with many2many in django REST
I am running a django app using REST to send data to my API. I have a network that contains many projects and a project can belong to many networks. I want to send this dataset via requests: payload = { "name": "my great testnetwork", "type_network": "xyz", "projects" : [ { "project_name": "Brasil", }, { "project_name": "Sweden", }, ], "creation_date": "2020-05-15T15:57:27.399455Z" } I do not want to create the project_names, they are already in the database. I only want this to work like a normal FK, where I specify the project_name and it shows in my API. It should only relate them. What happens now is that the project list remains empty when I send it like this This is what I get: { "id": 6, "name": "my great test", "type_network": "xyz", "projects": [], "creation_date": "2020-05-15T19:00:05.947542Z" } But I need the projects in the list. My serializer looks like this: class NetworkSerializer(serializers.ModelSerializer): """Serializer for Network. Add extra field buildings from NestedProjectSerializer. """ projects = NestedProjectSerializer( many=True, read_only=True, help_text="Many to many relation. Project instances expected." ) class Meta: model = Network fields = ( 'id', 'name', 'projects', 'creation_date', ) Ok so I tried to overwrite the create method for writable nested … -
DRF - Filter on date instead of date time in URL
I wrote the following code: class FixtureSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Fixture fields = ["home", "away", "league", "round", "date"] class FixtureViewSet(viewsets.ModelViewSet): """ API endpoint that allows fixture to be viewed or edited. """ queryset = Fixture.objects.all().order_by('-date') serializer_class = FixtureSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = ('date', "home", "away",) I want to filter on only on the date of a fixture instead of on the date/time combination. I tried it with the following GET requests: localhost:8000/fixtures?date=2020-05-16 localhost:8000/fixtures?date__date=2020-05-16 I also want the original date to be returned in the response of the request. Any idea on how to do this? -
HTML editor form , Django crispy forms showing different on cloud
On my local machine, I run python3 manage.py runserver..it shows as below enter image description here But on my official website, I don't see the html editor part.. Bold Italic and menu. Why? I am puzzled, and lost. -
Django OneToOneField related name works for one Model but not another
I have a project with common store-like functionality of Q&As and Reviews for each Item. The app is more complex than just this, but this is the boiled down crux of the issue. Here is the basic model and apps setup: # Q&As App Class Question(models.Model): ... # Reviews App Class Review(models.Model): ... # Items App Class Item(models.Model): ... Class ItemQuestion(models.Model): question = models.OneToOneField(Question, related_name='item_question') item = models.ForeignKey(Item, related_name='questions') ... Class ItemReview(models.Model): review = models.OneToOneField(Review, related_name='item_review') item = models.ForeignKey(Item, related_name='reviews') ... This issue comes when using the reverse look ups: Question().item_question # Raises Question.item_question.RelatedObjectDoesNotExist: Question has no item_question Review().item_review # Returns ComponentReview instance detailed stack trace: Traceback (most recent call last): File ".../site-packages/django/db/models/fields/related_descriptors.py", line 415, in __get__ self.related.get_accessor_name() Question.item_question.RelatedObjectDoesNotExist: Question has no item_question I'm not interested in design decision alternatives or anything like that, but more trying to understand why this is happening. Looking at the model setup and the migration files, everything seems identical in terms of code implementation, so why does one reverse lookup work and not the other? How can I get both to work? Thanks! Django Version 2.2 -
Django Field 'id' expected a number but got '<string>'
I'm trying to make a category page for my Django website. Everything works fine when I tested the url; but when I try to pass in the category object that filter the posts, I get this error: Field 'id' expected a number but got '<string>'. "category" is a foreign key in my Post model and I understand that the default that it passes is the id. How do I pass the string itself instead of the id? Here is my models.py: from django.db import models from django.contrib.auth.models import User from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length = 32, default='Uncategorized') def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(default='placeholder.jpg') author = models.ForeignKey(User, on_delete=models.CASCADE) summary = models.TextField(max_length=255, default='') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.title + ' | ' + str(self.author) Here is my views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post, Category def home(request): return render(request, 'blog/home.html', {}) def about(request): return render(request, 'blog/about.html', {}) def contact(request): return render(request, 'blog/contact.html', {}) class BlogView(ListView): model = Post template_name = 'blog/blog.html' ordering = ['-updated_on'] def get_context_data(self, *args, **kwargs): categories = Category.objects.all() context … -
Filter queryset with multiple checks, including value_is_in array in a Django view
I need to check if a user exists before saving a form. The fields are name, surname, and a role which can have one or many values. How can I do that? def save(self, commit=True): profile = super(ProfileForm, self).save(commit=False) first_name = self.cleaned_data['first_name'] surname = self.cleaned_data['surname'] role = self.cleaned_data['role'] if Profile.objects.filter(first_name=self.cleaned_data['first_name'], surname=self.cleaned_data['surname']).exists() raise forms.ValidationError("This profile already exists") elif commit: profile.save() Profile.objects.filter(first_name=self.cleaned_data['first_name'], surname=self.cleaned_data['surname'], role__in[role]).exists() gives me invalid syntax error. Of course I want to check if name & surname & role are all present within the same profile. My models class Role(models.Model): type= models.CharField(max_length=30) def __str__(self): return self.type class Profile(models.Model): first_name = models.CharField(max_length=120, null=True, blank=True) surname = models.CharField(max_length=120, null=True, blank=True) role = models.ManyToManyField(Role, blank=True) -
virtualenv vs virtualenvwrapper
I am new to Django development and stuck at installing part of Django. Actually, before running the following cmd, everyone told me to create virtual enviroment but I got confused about whether I have to install virtualenv or virtualenvwrapper or both. py -m pip install Django Many tutorials on youtube show the installation using pip install virtualenv but I installed pip install virtualenvwrapper and surprisingly it also work. Will anyone tell me which one I have to use to use virtual environment. Also in most of the youtube tutorials after installing virtualenv they get bin folder but in my case no such folder exists... please fully guide me regarding installation in windows for django:) -
Custom class methods in templates in Django
I am trying to use the alphabetical paginator from here: https://djangosnippets.org/snippets/1364/ . I have added the code in the link in my_app/snippets.py. I have imported the class in my views.py and added the code in views and template file as shown in the link. But pagination is not shown in the page. The problem, as far as I know, is that the paginator object is not present in the template. So how can I make sure that NamePaginator class and its methods are present in the template also? If it is some other problem also, please tell how to rectify it. -
How can I exclude rest-auth endpoint from the Django built-in API documentation?
To hide the endpoint in the Django documentation just @schema(None) has to be added for example to GenericAPIView, however I have a problem with these three urls: url(r'^swagger/', schema_view), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), I am not able to add @schema(None) decorator because I do not have declared views for these urls. Any ideas how to work it around? -
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: User() got an unexpected keyword argument 'phone'
I have created one table attribute phone in auth_user manually (if i remove phone attribute it work fine) but when I add phone it gives error. I tried everything but its not working is it really good way to store data in django def signup(request): if request.method == "POST": firstName = request.POST.get('firstName', None) lastName = request.POST.get('lastName', None) username = request.POST.get('username',None) email = request.POST.get('email', None) mobileNumber = request.POST.get('mobileNumber',None) password = request.POST.get('password', None) user=User.objects.create_user( first_name = firstName, last_name = lastName, username = username, email = email, phone = mobileNumber, password = password ) user.save() return HttpResponse('Succesfully user created')