Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
@login_required decorator within an 'if' statement?
I have a model 'Playlist' with an attribute 'private' that can be True or False (and therefore private or public). I want to use the @login_required decorator only if 'private = False', but can't figure out how to achieve this result. Here is my models.py file: class Playlist(models.Model): """Allow a user to create a customized list of songs.""" name = models.CharField(max_length=100) image = models.ImageField(upload_to='playlists/%Y/%m/%d', blank=True, null=True) songs = models.ManyToManyField('Song') description = models.TextField(blank=True, null=True, max_length=1000) date_added = models.DateTimeField(auto_now_add=True) private = models.BooleanField() def __str__(self): """String for representing the model object.""" return self.name def get_absolute_url(self): """Returns the url to access a detail record for this song.""" return reverse('playlist-detail', args=[str(self.id)]) And my views.py file: def playlist(request, playlist_id): """Show a single playlist and associated data.""" playlist = Playlist.objects.get(id=playlist_id) songs = playlist.songs.all() for song in songs: if song.url: song.video_id = song.url.replace("https://www.youtube.com/watch?v=", "") context = {'playlist': playlist, "playlist_songs": songs} return render(request, 'great_songs_app/playlist.html', context) I stumbled across a similar thread but there was no answer to the problem:Conditionally apply login_required decorator in Django I imagine code looking something like what the OP posted, with the view function being preceded by: if playlist.private == True: @login_required ... But obviously that won't work. Any ideas? -
OneToOne autofill with the parent's value
class Seccion(models.Model): name = models.CharField(max_length=80, unique=True) def __str__(self): return self.name class Meta: ordering = ["pk"] class Contenido(models.Model): title = models.OneToOneField( Seccion, on_delete=models.CASCADE, primary_key=True, verbose_name ="TΓtulo", ) exp = RichTextField(blank=True) practice = RichTextField(blank=True,verbose_name="Buenas PrΓ‘cticas") lecture = RichTextField(blank=True) ending = RichTextField(blank=True) recomendations = RichTextField(blank=True) def __str__(self): return self.title.name So, I have those models, I'd like to know if there's a way to autofill the title with the parent's value "name". -
There is a way to solve 'Error tokenizing data. C error: out of memory' pandas python?
I create a website where I can set the numbers of training and testing data for K-NN, SVM and Random Forest, for each separate. If I start the django server and train one of the algorithms with 1.000 data, it's work, but if I train again another one or the same algorithm with > 1.000 data or if I train first time with more data this error appear (ParserError at /statistic/trainknn Error tokenizing data. C error: out of memory) I have two csv files for train and test, train_csv with 60.000 rows and 785 columns and test_csv with 10.000 rows and 785 columns. I try to use chunk to read csv, but the same error appear. This is the way I read data from csv data = pd.read_csv("E:\Django\mnist_train.csv", nrows=x).as_matrix() And this is with chunk mylist = [] for chunk in pd.read_csv("E:\Django\mnist_train.csv", nrows=x, chunksize=10): mylist.append(chunk) data = pd.concat(mylist, axis=0) del mylist -
can't decode req.body in django api
I've checked out this question asked already but for one reason or another, I keep getting this error: JSONDecodeError: Expecting value: line 1 column 1 (char 0) When I test the route the route through the admin page "http://localhost:8000/admin/peeps_api/people/add/" it makes a post request and I get the Jsonresponse I'm looking for. I am testing the route "http://localhost:8000/people/register" on postman with the body filled out correctly, headers content-type set to application/x-www-form-urlencoded and the error comes back to haunt me. should I be importing something that I'm not? data = req.body.decode('utf-8') data = json.loads(data) is learned to begin post routes at General Assembly so I'm confused as to why its just erroring out. can you spot what I'm doing wrong? views.py from django.http import JsonResponse from django.views.generic import View from .models import People from django.views.decorators.csrf import ensure_csrf_cookie , csrf_exempt from django.utils.decorators import method_decorator # vaugely know how to use this import json import datetime #for later use class Register(View): @csrf_exempt def dispatch(self, req, *args, **kwargs): return super(Register, self).dispatch(req, *args, **kwargs) def post(self, req): if req.method == "POST": data = req.body.decode('utf-8') data = json.loads(data) print(data) try: new_user = People(first_name = data.get('first_name'), last_name = data.get('last_name'), age = data.get('age'), birth_year = data.get('birth_year'), birth_month = β¦ -
Deploy Django webapps to Azure with Azure Sql Server DB, Azure Storage, and ability to integrate Azure Rest APIs
This is the first time I am deploying a webapp to a server. Background: - Python 3.3 - Django 2.1 (windows installation) - Azure - Github Goal: - Have a functioning hosted Django based website that i can add more webapps (authentication, blog, ecomm, email service, file storage/uploads, etc..) to and tap into Azures AI and other components. I want to use Sql Server backend as i am familiar with this and ability to leverage Azures Data Factory, AI, etc.. Where I am: - I built a simple Django based web page (1 app) using Atom. I uploaded code to Github. -I've searched almost ever site and django doc i can, but none seem to meet my needs Need: - Instructions or resources to deploy this windows based django app to azure to meet the goals defined above. Please help! -
Search Bar in Django
I would like to add a search bar to my template in Django I would like to include a search box in above a list of articles so users can search through the data. When I enter something in the bar nothing happens though... here below my code Thanks for the help in advance <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> def article_overview(request): search_term = '' if 'search' in request.GET: search_term = request.GET['search'] articles = Article.objects.all().filter(feeder__icontains=search_term) articles = Article.objects.all() return render(request, 'overviews/overview.html', {'articles' : articles, 'search_term': search_term }) -
Database table Error when run python manage.py migrate command
I have cloned a django project. I have installed all dependency and also change dbname ,username, password. When I run this command python manage.py migrate or python manage.py makemigrations then I got the following error. File "/home/imsaiful/Desktop/abdul_bhai/myvenv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 298, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: notification_ID I have worked django earlier. The new table always created inside database after we run the migration command. What should I do? -
Django - What is the most efficient way to query the average ratings for a list of objects?
I have a simple Product and Rating class like so: class Product(models.Model): name = ... price = ... class Rating(models.Model): product = models.ForeignKey("Product", ...) score = models.PositiveSmallIntegerField(...) Now I want to get a list all products and the average rating for each product. Simply getting all products is easy: product_list = Product.objects.all() If I have a single product and I want to get the average rating for that single product: product = get_object_or_404(Product, pk=product_id) ratings = Rating.objects.filter(product=product) product_avg_rating = ratings.aggregate((Avg("score"))) But let's assume I want to list all products and their average rating. This sounds like it's quite resource/compute heavy. So what is the best way to solve this? Should I make a class method for the Product class that just returns the average, so I can then call this in the template: {{ product.get_average_rating }} Or is there a better way to do this? I'm not quite sure what to do here and need some guidance. Thank you so much in advance! -
As I click a link (which is a country name) I have the list of all cities, even from other countries. How to fix it?
I have links (which are list of the countries) when I click (for example) "USA" I get list of the cities from other countries too. But I only want the list of the cities in the USA. Here is my github link. You are welcome to clone and play with it. https://github.com/ualmaz/post I tried to filter that like this. queryset = Post.objects.all().values_list( 'city', flat=True).distinct() But it did not work. This is my views.py def cities(request): queryset = Post.objects.all().values_list( 'city', flat=True).distinct() context = { 'cities': queryset } return render(request, 'users/cities.html', context) my models.py class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="First name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) def __str__(self): return self.username class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.URLField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('users:blog') my countries.html (it contains countries list) {% extends 'shared/base.html' %} {% load staticfiles %} {% block content %} <div class="content-section p-5 mt-5 pl-4"> <table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <th>No: </th> <th>Countries: </th> </tr> </tbody> β¦ -
Confused with the relationship of the models
So I am trying to create the following type of relationship: Teacher has many students, Student has many Teachers, Student has many(2) Parents, Parent has many Students. The thing that confuses me is that I am trying to archive that with the extenesion of the AbstractUser. I totally confused myself over how I would create the models. Currently I have this: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) parent = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='parents' ) class Parent(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) student = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='students' ) class Teacher(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) student = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='students' ) -
What is Oauth2 Token Authentication in Rest Framework
I want to authenticate which user is accessing my Api i got a tutorial but it is not that much informative to understand and implement. Do you have any good tutorial regarding Oauth2 token Authentication. https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html -
Speed Up the Django Get Query to Retrieve Data
In the get_context_data function I am trying to retrieve the data from variable table and the current code worked fine when I had less data, but now I have more than 1M records and it takes around 15-20 secs for the page to load. I tried using the objects.filter function but it returned the entire list rather then the filtered object. class Variables(PermissionsRequiredMixin,TemplateView): required_groups = ['Admin', 'Facility', 'Operator'] def get_template_names(self): try: a = self.kwargs['pk'] if self.request.is_ajax(): return ['variable.ajax.html'] else: return ['container/variable_id.html'] except: if self.request.is_ajax(): return ['variables.ajax.html'] else: return ['container/variables.html'] def get_context_data(self, **kwargs): context = super(Variables, self).get_context_data(**kwargs) context['colors'] = colors shuffle(context['colors']) try: context['variables'] = variable.objects.get(id=self.kwargs['pk']) if not CustomUser.objects.filter(id=self.request.user.pk, role=context['variables'].area.role).exists(): if not self.request.user.opGroup == 'Admin': context['variables'] = {'name': 'Access denied'} except: pass return context Is there any other way of retrieving this data faster in Django? I am really worried that the performance will further be affected when my data will grow from 1 Million to 2 Million. -
Mypy Cannot Find All Modules in Python3 Django App
Problem I work in a large Python3 repo that is type checked with Mypy. In accordance with PEP420 we do not use __init__.py files. Mypy recently added support for implicit namespace packages, but the implementation now follows the chain of import statements from a given entrypoint. In the case of this repo, (a Django app) there are many modules that are imported dynamically (like middleware) or not imported at all (tests and one-off scripts). Consider this example: my-py3-repo/ βββ hello/ β βββ services/ β β βββ hello_service.py β βββ hello.py βββ scripts/ β βββ db/ β β βββ migrate.py β βββ manage.py βββ tests/ βββ hello/ βββ services/ β βββ hello_service_test.py βββ hello_test.py Question How can I configure Mypy such that the scripts and tests directories are always type checked? Configuration # Pipfile [dev-packages] mypy = "==0.670" [requires] python_version = "3.7" # setup.cfg [mypy] python_version = 3.7 ignore_missing_imports = True namespace_packages = True See also this issue I created in the Mypy repo. -
Create graphene-django interface from models
I'm using graphene-django and i want to create four Interfaces, each representing models in Django, i'll start with only one model: class TestInterface(graphene.Interface): items = graphene.Field(models.Test) But i keep getting this error: AttributeError: type object 'Test' has no attribute 'name' Any ideas? -
How do I add a queue to a custom message consumer at run-time
I have a use-case where my Django App needs to process messages from an external source. Celery supports this with Custom Message Consumers, and this part is working fine. The exchange type is headers so that a message may route to different queues based on conditions. The conditions are configured through the Django Admin. From the code below, you can see, for instance a QueueItem may be activated / inactivated at any time. This works find on loading a worker for the first time. On a fresh Rabbit, the exchange, queues and routes all get built and the custom consumer consumes messages correctly. The issue lies when a user adds a new QueueItem or flips the active status of an existing QueueItem. I can dynamically create the new queue, but no matter how hard I try the Custom Consumer does not consume from it. I would like the app to: Relaunch the custom consumer (I tried app.control.broadcast('pool_restart')) Add the queues and consume it using the Custom Consumer. (I tried app.control.add_consumer(...)) Gracefully restart all workers which when I do manually works to pick up the new settings. class MyConsumerStep(bootsteps.ConsumerStep): alias = 'MyConsumerStep' def get_queues(self): from app.models import QueueItem qs = QueueItem.objects.filter(active=True, β¦ -
why do i get syntax error on manage.py makemigrations?
I'm making a test project with python and django (for learning purposes). At some point I have to make a django app called products. then in the models.py file in the "products" app directory I have to write this code: class Products (models.Model) title = models.TextField() description = models.TextField() price = models.TextField() and then after adding the new app in the settings file when I attend to make migrations as shown: > python manage.py makemigrations the error I get is this: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\django\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\django\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\django\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\django\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\django\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\django\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\django\mystore\products\models.py", line 5 β¦ -
celery, not all tasks in a group are executed when there are tasks greater than CPUs?
There is a task, that executes 100 other tasks, to be executed periodically every 0.5 seconds. @task(queue="pages_checker") def run_checker(): active_pages = Page.objects.filter(is_active=True) g = group(page_check.s(page.id) for page in active_pages) #g.apply_async(queue="page_checker") g() return active_pages.count() @task(queue="page_checker") def page_checker(page_id): print("page"+str(page_id))#logging here #some logic Each task takes 0.02 seconds for execution. But, out of 100 only some 70 to 80 tasks are executed, could see in the logs. Why? How to strictly execute all tasks in the group? workers: 4 workers executing run_checker, while 14 workers are executing page_checker tasks. Server: 16gb RAM, 8 vCPUs with Hyperthreading. -
Mandate integer type in django-rest-framework validator for integerfield
django-rest-framework validator accepts string quoted integers as valid data for integer field. Is there a way to mandate data type so that string quoted integers won't be accepted ? -
Django custom manager return all when user is on admin page
I'm creating a Django app. It's an article app. I have a field named hidden and I want to return a queryset without articles when hidden is true and the user isn't in the admin panel. Admin-page -> Show everything Normal -> Show only with hidden = False I'm creating this with a custom manager: class ArticleManager(models.Manager): def get_queryset(self, request): if request.user.is_superuser: return super().get_queryset() return super().get_queryset().filter(hidden=False) but I'm just getting this error: TypeError: get_queryset() missing 1 required positional argument: 'request' -
I am not able to resolve the RecursionError from Django framework
python manage.py runserver gives following Traceback: How do I get my launch webpage on localhost? I have tried Django Slack community group and also tried StackOverflow question regarding RecurrsionError in Django Framework, but the answers are uncertain and confusing. python3 manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x102b926a8> Traceback (most recent call last): File "/Users/kuldeep/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) [Previous line repeated 986 more times] File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 59, in _load_all_namespaces ':'.join(parents + (url.namespace,)) for url in url_patterns File "/Users/kuldeep/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 60, in if getattr(url, 'namespace', None) is not None RecursionError: maximum recursion depth exceeded while calling a Python object I am expecting the flying rocket which gives me confidence of congratulation message on my local host. -
Django query chaining multiple filters
This is my schedule object, class Schedule(Base): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True) first_team = models.ForeignKey(Team, related_name="first_team", on_delete=models.CASCADE, null=True) second_team = models.ForeignKey(Team, related_name="second_team", on_delete=models.CASCADE, null=True) first_score = models.IntegerField(default=0, null=True) second_score = models.IntegerField(default=0, null=True) sport = models.ForeignKey(Sport, on_delete=models.CASCADE, null=True) date = models.DateTimeField() I want to fetch the schedules for a specific sport, for the past 30 days for tournaments which have anything other than a 0.0 bias. This is my query schedules = Schedule.objects.filter(sport=sport).filter(date__gte=date.today()).filter( date__lte=(date.today() + timedelta(days=30))).order_by("date").exclude(tournament__bias=0.0) This doesn't work, can someone help me here. Thanks. -
Webpack is serving a few file from image directory.Is there any limit?
I want to use webpack with django. But the problem is it serves only a few part of the total image files. I am using node 8.15. This is my webpack module part { test: /\.(png|jpg|svg|ttf|eot|woff|woff2)(\?.*)?$/, loader: 'file?name=[path][name].[ext]' } For example: It serves "static/src/img/refresh_icon.png" while it does not serve "static/src/img/search-icon.png".Though they reside in same folder. What can be the reason for such behavior? -
generate token as default value django
So I'm using python secrets library so I can generate token, so I want to add it as a default like this token=models.CharField(max_length=32, default=secrets.token_urlsafe(32)) strange thing it will generate 43 characters rather than 32, so can anyone help me understand why? Thanks -
Getting mad on Docker networking
i really have no clue anymore, i tried almost every combination i could imagine but in the end was not able to find a solution that fits. Have have a dockerized app that depends on elasticsearch, redis, traefik and postgres but for some reason the networking communication between traefik and my actuall app seems to be somehow broken. I simply want that im able to reach my app at 127.0.0.1:80 but traefik alsways returns 404 not found version: '3' networks: backend-app: internal: true frontend-app: internal: false volumes: esdata: driver: local postgresdata: driver: local services: app-proxy: container_name: app-proxy image: traefik # The official Traefik docker image command: --api --docker # Enables the web UI and tells Traefik to listen to docker ports: - 80:80 # The HTTP port - 8080:8080 # The Web UI (enabled by --api) volumes: - /var/run/docker.sock:/var/run/docker.sock # So that Traefik can listen to the Docker events depends_on: - myproject networks: - frontend-app - backend-app redis: image: redis:alpine container_name: app-redis networks: - backend-app ports: - 6379 labels: - traefik.enable=false postgres: image: postgres:latest container_name: app-postgres networks: - backend-app ports: - 5432 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: mysupersecretpass POSTGRES_DB: myproject volumes: - postgresdata:/var/lib/postgresql/data labels: - traefik.enable=false elasticsearch: image: elasticsearch:6.5.3 container_name: app-elasticsearch β¦ -
Django join button to goal
I try to create changing button after user join to Goal. I have work buttons, but i don't know how to change this in template. I try to do this with boolean field, when user click "Join", boolean field change to True, and then in template I try: {% if goal.joined %} <Delete join> {% else %} <join to goal> {% endif %} Models: class Goal(models.Model, Activity): title = models.CharField(max_length=255, verbose_name='TytuΕ') image = models.ImageField(upload_to='goals', verbose_name='TΕo') body = HTMLField(verbose_name='TreΕΔ') tags = TaggableManager() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = AutoSlugField(populate_from='title') def __str__(self): return self.title class Meta: verbose_name = 'Cele' ordering = ['-created_at'] def get_absolute_url(self): return reverse('goaldetail', args=[str(self.slug)]) @property def activity_actor_attr(self): return self.author def add_user_to_list_of_attendees(self, user): registration = Joined.objects.create(user = user, goal = self, created_at = timezone.now()) def remove_user_from_list_of_attendees(self, user): registration = Joined.objects.get(user = user, goal = self) registration.delete() class Joined(models.Model, Activity): goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users') created_at = models.DateTimeField(auto_now_add=True) joined = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.id is None and self.created_at is None: self.created_at = datetime.datetime.now() self.joined = True super(Joined, self).save(*args, **kwargs) @property def activity_actor_attr(self): return self.user Views: def joined_add(request, pk): this_goal = Goal.objects.get(pk=pk) this_goal.add_user_to_list_of_attendees(user=request.user) return redirect('goaldetail', slug=this_goal.slug) def joined_delete(request, pk): this_goal = β¦