Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set allauth login url as home page
I have installed allauth package and i need to set my homepage url as allauth http://127.0.0.1:8000/accounts/login/ url ,this is my urls.py : path('', allauth.account.views.LoginView , name="account_login"), is it correct? -
Make the sekextion of date range in filter optional in Django
I have been working on a simple inventory stock system and i want to make a serch wich has various options but when i search without having an imput in the date range boxes, the application crashes. if request.method == 'POST': category = form['category'].value() queryset = StockHistory.objects.filter( item_name__icontains=form['item_name'].value(), last_updated__range=[ form['start_date'].value(), form['end_date'].value() ], issue_to__icontains=form['issue_to'].value() ).order_by('-last_updated') if (category != ''): queryset = queryset.filter(category_id=category) -
issue implementing django-scheduler in MySQL database
I'm having an issue implementing the component django-scheduler with my project implemented on a MySQL database. I have setup a simple project, one app, installed the django-scheduler component, makemigrations, and migrate. The process starts off well, then dies out with the following: PS C:\Development\Django\TestProject\src> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, schedule, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying schedule.0001_initial... OK Applying schedule.0002_event_color_event... OK Applying schedule.0003_auto_20160715_0028... OK Applying schedule.0006_update_text_fields_empty_string... OK Applying schedule.0004_text_fields_not_null...Traceback (most recent call last): File "C:\Development\Django\TestProject\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Development\Django\TestProject\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Development\Django\TestProject\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Development\Django\TestProject\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Development\Django\TestProject\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1101, "BLOB, TEXT, GEOMETRY or JSON column 'description' can't have a default value") The above exception was the direct cause of the following exception: Traceback (most recent call … -
UniqueValidator throw error when update an email with old email
I have been working on django serializers. Below is my code class UpdateTravelAgentStaffSerializer(ModelSerializer): model = User fields = ( 'full_name', 'position', 'email', ) extra_kwargs = { 'full_name': { 'required': True, }} When I create new Travel Agent Staff, the validator of email unique Email Validator works well. Now During update I added same validation during adding of TravelAgentStaff Now Igot error saying email must be unique. The validation I applied in update was as. extra_kwargs = { 'email': { 'validators': [ UniqueValidator( queryset=User.objects.all() ) ] } } So I tried def validate_email(self, value): self.value= value Now I dont know how to check unique email and also the email of current user need to be allowed if it is unchanged. -
How to create click to call phone button in Django? Or some plugins?
I need to add a button to call a specific phone number. Or maybe you can recommend some plugins which can do that? Thank, you! -
Django ViewSet returns result in command line, provides error when visiting URL
I have a viewset set up like so: views.py class TalentView(generic.DetailView): template_name = 'talent.html' def get_queryset(self): query = CampaignTalent.objects.filter(campaign_id=self.kwargs['pk']) return query models.py class Campaign(models.Model): campaign_name = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) class CampaignTalent(models.Model): talent_name = models.CharField(max_length=250) talent_id = models.BigIntegerField() approved = models.BooleanField() campaign = models.ForeignKey( 'Campaign', on_delete=models.CASCADE ) I am trying to provide the viewset a list of talent attached to the campaign, given by the PK. When I log out in my console the results of query into my console I get <QuerySet [<CampaignTalent: CampaignTalent object (1)>]>, however my page returns a 404 with the error No campaign talent found matching the query. Even if I log out the raw query and run it against my DB, I get results. Why am I receiving a No ... found matching query response? -
How to display a list of the foreignkey items?
I am struggling to display the list of foreignkey items. I can display the list of categories. But I don`t manage to display the list of times belonging to this category. For example, I would like to display the models belonging to the category, if we consider they belonging to the same category: Meat Pizza Veg Pizza models.py class PizzaCategory(models.Model): PIZZA_CATEGORY = ( (1, 'Meat'), (2, 'Fish'), (3, 'Vegetarian'), ) name = models.CharField(max_length=250) category = models.IntegerField(choices=PIZZA_CATEGORY,default=1) def __str__(self): return self.name class PizzaTopping(models.Model): name = models.CharField(max_length=60, unique=True) def __str__(self): return self.name class MeatPizza(models.Model): name = models.CharField(max_length=60, unique=True) pizza_category = models.ForeignKey(PizzaCategory, on_delete=models.CASCADE, blank=True, null=True) pizza_topping = models.ForeignKey(PizzaTopping, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class VegPizza(models.Model): name = models.CharField(max_length=60, unique=True) pizza_category = models.ForeignKey(PizzaCategory, on_delete=models.CASCADE, blank=True, null=True) veg_type = models.CharField(max_length=60, unique=True) pizza_topping = models.ForeignKey(PizzaTopping, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name views.py @login_required(login_url="/login/") def category_detail(request, category_id): category = get_object_or_404(PizzaCategory, pk=category_id) categorys = PizzaCategory.objects.all() context = { 'categorys': categorys, } return render(request, 'pizzas/category_detail.html', context) category_detail.html <tbody> {% for category in categorys.all %} <tr> <td>{{ category.name }}</td> </tr> {% endfor %} </tbody> -
where this "username" came from, self.kwars.get('username')?
In url parameters I didn't pass username but when I used self.kwars.get('username) where did username comes from In urls.py path('', views.PostList.as_view(), name='all') In views.py class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ('user', 'group') template_name = 'posts/post_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self.kwargs.get('username')) context['user_groups'] = models.Group.objects.filter(members__in=self.kwargs.get('username','')) return context I tried to print self.kwargs.get('username') but it is printing "None" -
Google Calendar API: enable the user to make request with their own account
I'm using django-allauth to enable Google login in my app. I already have everything configured and login is working fine! But when I try to make a request to Calendar API (using my own credentials) it gives me: Request had insufficient scopes It feels quite strange to me, a user should be able to access it's own calendar! Here is how I'm trying to set the credentials: google.py from allauth.socialaccount.models import SocialToken, SocialApp from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request SCOPES = ['https://www.googleapis.com/auth/calendar'] def get_credentials(user): token = SocialToken.objects.get(account__user=user, account__provider='google') social_app = SocialApp.objects.get(provider='google') creds = Credentials( token=token.token, refresh_token=token.token_secret, token_uri='https://oauth2.googleapis.com/token', client_id=social_app.client_id, client_secret=social_app.secret, scopes=SCOPES ) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) return creds This is the code I use to make the request: def search_calendar(request, event_name): user = request.user creds = get_credentials(user) service = build('calendar', 'v3', credentials=creds) now = datetime.datetime.utcnow().isoformat() + 'Z' events_result = service.events().list(calendarId=user.email, timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: return HttpResponseNotFound('No events found!') correspondent_event = {} print('Looking for an event named %s...' %event_name) for e in events: try: event_matches = re.search(event_name, e['summary'], flags=re.IGNORECASE) if event_matches: print(request.user.username, 'found %s!' %e['summary']) correspondent_event = { 'name': e['summary'], 'start': date.iso_to_datetime(e['start'].get('dateTime', e['start'].get('date'))), 'end': … -
Same query returns different results
I have a strange behavior of Django. I do this query: import time from dateutil.relativedelta import relativedelta list_ids = Model1.objects.filter(date_created__gte=datetime.now().date() - relativedelta(years=2)) \ .select_related('model2').order_by('model2_id', '-date_created') \ .distinct('model2_id').values_list('id', flat=True) But it's returns a different results every time, when I execute it. It's interesting, that subquery_loans.count() returns 153838 every time. But when I compare results of list_ids and list_ids2 (with the same query) I get a difference around 5800 records and this value changes every time! I compare it this way: diff = set(sorted(list_ids)) - set(sorted(list_ids2)) len(dff) 5800 -
How do I import settings when using DJANGO_SETTINGS_MODULE?
I have a Django project and am using the DJANGO_SETTINGS_MODULE for managing each environment settings. I have created different settings files for each environment, however, I'm confused how I can access these settings without having to change the imports in my code. For example, I have this settings directory structure: stats/ config/ settings/ __init__ base.py dev.py prod.py base.py has all my default settings, include some API keys for third party services. I override these in each environment: base.py API_KEY = "default" dev.py from base import * API_KEY = "dev" prod.py from base import * API_KEY = "prod" When I start up my server, I use ./manage.py runserver --settings=stats.config.settings.dev But how do I access the API_KEY without having to change "dev" to "prod" every time I deploy? This is how I currently access the API_KEY in my code: from stats.config.settings.dev import API_KEY I can't seem to find the proper answer to this anywhere. Thanks! -
How could frontend hosted on another server be compiled in Django apps?
In my firm we have several applications hosted on different servers and jails. They are all based on the same frontend. Is there a way we could organise everything to have the frontend in one place only so that when a dev compiles their specific app with webpack, it retrieves and compiles the latest version of the frontend? Thanks for your help. -
NoReverseMatch at /login/ (Django)
I'm getting a NoReverseMatch error at login/ , when it redirects to profile.html , if i login through other pages where it redirects to another page, then it works fine , but when I click on the login button which redirects to the profile.html page , I get the NoReverseMatch error. Do you know what is wrong in this code ? , I can't seem to find the fault. NoReverseMatch Error profile.html <div class="main-content"> <div class="container mt-2"> <div class="row"> <div class="col-xl-8 col-md-10 m-auto order-xl-2 mb-5 mb-xl-0"> <div class="card card-profile shadow"> <div class="row justify-content-center"> <div class="col-lg-3 order-lg-2"> <div class="card-profile-image"> <img src="{{ u.profile.image.url }}" class="rounded-circle" width="160px" height="160px" /> </a> </div> </div> </div> <div class="card-header text-center border-0 pt-8 pt-md-4 pb-0 pb-md-4" ></div> <div class="card-body pt-0 pt-md-4"> <div class="row"> <div class="col"> <div class="card-profile-stats d-flex justify-content-center mt-md-5" > <div> <span class="heading">{{ u.profile.friends.count }}</span> {% if request.user == u %} <span class="description" ><a href="{% url 'friend_list' %}">Friends</a></span > {% else %} <span class="description">Friends</span> {% endif %} <span class="heading">{{ post_count }}</span> <span class="description" ><a href="{% url 'user-posts' u.username %}" >Posts</a ></span > </div> </div> </div> </div> <div class="text-center"> <h3 class="user_link"><a href="{% url 'user-posts' u.username %}">{{ u }}</a></h3> <p>{{ u.profile.bio }}</p> <hr class="my-2" /> {% if request.user == … -
How to create 2 or multiple worker in celery on django app
i had setup a django app with celery and also able to run run one single task on background. i have a task and i want to run this task on 4 or 5 worker so i can finished my task faster . I am new to celery so i dont have any idea how to create 4 or 5 worker and run these worker sepreatly so same task will run on each worker at the same time . Now i have a 'celery.py' in my project folder and it is working fine when i run this command 'celery -A project_name worker -l info' . i want to run the same task in this way but on different worker BUt i dont know how to create these worker and run seperately . please give me a solution so i can create 4 or 5 worker and run them seperately . -
How to create a simple form in the base html template django
I have a Django app that contains multiple pages. Like the menu or footer, some elements are repeated in all of these pages, so I created a base template and added these duplicated codes. Now I want to have a form above the footer in the base template. But I don't know how to make it work. Should I make a view that returns the base.html? How can I inherit this form on every page of the website? Please guide me; I'm in a bit of a pickle! -
Django model created DateTimeField & now difference
I need data from MYSQL table using Django model ORM. How can I get Query Set having data filtered on the bases of difference for created(DateTimeField) and now. Here created is table column and now is MYSQL NOW(); My Use Case is to get rows those were created 7 days OR 168 hours ago. -
Django models not rendering when I use boiler plate
There is no error when i try to render. it works fine when i don't use django dashboard boiler plate. I tested the query set on shell and its working. the data can be seen on admin. its just not rendering on the html template. not sure if the url setup impacts it. I have tried changing how to render on the template, still not working. any one with an idea how to correct it? urls from django.urls import path, include, re_path from . import views urlpatterns = [ # The home page path('', views.index, name='home'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] Views from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.http import HttpResponse from django import template from stockmgmt import views from .models import * from .forms import * @login_required(login_url="/login/") def index(request): context = {} context['segment'] = 'index' html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) def list_tables(request): title = 'List of Items' # form = StockSearchForm(request.POST or None) queryset = Stock.objects.all() context = { "title": title, "queryset": queryset, "form": form, } return render(request, "list_tables.html", context) list_tables.html {% for instance in queryset %} <tr> <td><input type="checkbox" class="checkthis" /></td> <td>{{forloop.counter}}</td> <td>{{instance.category}}</td> <td>{{instance.item_name}}</td> … -
How to use the CostumUser in modles.py and views.py applications
If you take a look at the following example you can find a ManyToManyField with the varialbe settings.AUTH_USER_MODEL #modles.py class Post(models.Model): # note: posts can have tables as well and they can save it in the description (JSONField) title = models.CharField(max_length=200) description = models.CharField(max_length=9999999) preBuildStyle = models.ManyToManyField( Style, related_name='Styles', blank=True) style = models.CharField(max_length=9999999, blank=True) # type = ['Paper','post','template','comstume_component'] postType = models.CharField(max_length=50, blank=True) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) who_can_see = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='poster_user', blank=True) who_can_edite = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='who_can_edite_Component', blank=True) def __str__(self): return self.title However, I create a costume User instead of using the default one, and now using settings.AUTH_USER_MODEL cause few errors in my app one of them looks like this column API_post_who_can_see.account_id does not exist LINE 1: ...N "API_post_who_can_see" ON ("API_account"."id" = "API_post_... Maybe you need to know that I followed the following stets. 1.in settings.py I added AUTH_USER_MODEL = 'myApp.CostumUser' and ACCOUNT_EMAIL_REQUIRED = False 2. Also in settings.py I added "USER_DETIALS_SERLIZER": 'API.serlizer.CostumUserSerlizer' to the REST_FRAMEWORK list 3. I created the following registration serlizer class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=settings.ACCOUNT_EMAIL_REQUIRED) first_name = serializers.CharField(required=False, write_only=True) last_name = serializers.CharField(required=False, write_only=True) address = serializers.CharField(required=False, write_only=True) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, … -
celery periodic task must start working after it is triggered
I successfully run the periodic task in celery but I need it to start the periodic task after I triggered it. Basically, the system has a request that starts the periodic task. The task is running but I need to trigger it before it starts. Also, I should remove the periodic task after another trigger comes. -
I want to create an API that can retrieve daily, weekly, monthly, and yearly reports in the Django REST framework.(Frontend:React)
I'm making an app on Django that records the amount of time I'm working on my daily steps, but I want to create an API that can get daily, weekly, monthly, and yearly reports (time percentage for each category, total time, etc.) However, I did not understand how to make it even after various investigations, so I asked a question. #CategoryModel class Category(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name #WorkModel class Work(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name='works', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='works', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name I have such a model, and I want to create an API that can format the recorded data into daily, weekly, monthly, and yearly formats, and create graphs and tables for each of them. When creating each API, do you create a new Daily Model, Weekly Model, etc. or design each API with Serializer? I would appreciate it if you could tell me more about it. -
Connecting Django with MongoDB using pymongo
Instead of using Djongo or mongoengine to connect the django app with mongoDB, i want to create an API to insert data using pymongo into MongoDB. Any help in suggesting the structure of workflow would be really helpful. -
Object of type CharField is not JSON serializable
I'm learning Django by trying to build what comes to the mind. Now I'm trying to build Django rest API that returns item or all items from a postgres data table. models.py class AdModel(models.Model): id = models.IntegerField name = models.CharField(max_length=50), address = models.CharField(max_length=50), web = models.CharField(max_length=50), class Meta: db_table = 'mock_location_data' serializers.py class AdSerializer(serializers.ModelSerializer): class Meta: model = AdModel fields = '__all__' views.py class AdAPIView(APIView): def get(self, request): queryset = AdModel.objects.all() serializer_class = AdSerializer(queryset, many=True) return Response(serializer_class.data) On GET request I'm getting Internal server error 500 with "Object of type CharField is not JSON serializable" I'm using Django 3.1.5 and DRF 3.12.2 -
Heroku build of django app successful but open app throws error
Django app runs locally OK, and build to heroku successful, but app not showing. Error logs say No module named 'my_app.wsgi' I am at a loss. I have tried different app names and locations of procfile. This is Procfile. It is found by heroku and shows as resource dyno. web: gunicorn my_app.wsgi this is file structure file structure this is wsgi.py (if relevant) import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_wsgi_application() and this is heroku error logs 2021-02-25T14:11:44.731878+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-02-25T14:11:44.731878+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2021-02-25T14:11:44.731879+00:00 app[web.1]: ModuleNotFoundError: No module named 'my_app.wsgi' 2021-02-25T14:11:44.732085+00:00 app[web.1]: [2021-02-25 14:11:44 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-02-25T14:11:44.764764+00:00 app[web.1]: [2021-02-25 14:11:44 +0000] [4] [INFO] Shutting down: Master 2021-02-25T14:11:44.764844+00:00 app[web.1]: [2021-02-25 14:11:44 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-25T14:11:44.849187+00:00 heroku[web.1]: Process exited with status 3 2021-02-25T14:11:44.920807+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-25T14:11:44.923622+00:00 heroku[web.1]: State changed from crashed to starting 2021-02-25T14:11:55.765297+00:00 heroku[web.1]: Starting process with command `gunicorn my_app.wsgi` 2021-02-25T14:11:58.971074+00:00 app[web.1]: [2021-02-25 14:11:58 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-02-25T14:11:58.971543+00:00 app[web.1]: [2021-02-25 14:11:58 +0000] [4] [INFO] Listening at: http://0.0.0.0:41265 (4) 2021-02-25T14:11:58.971644+00:00 app[web.1]: [2021-02-25 14:11:58 +0000] [4] [INFO] Using worker: sync … -
AttributeError: module 'personal.models' has no attribute 'get_default_profile_image' Django
I am using this tutorial to build a simple network. This is my error: AttributeError: module 'personal.models' has no attribute 'get_default_profile_image' And this is my code: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.files.storage import FileSystemStorage from django.conf import settings import os class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_profile_image_filepath(self, filename): return 'profile_images/' + str(self.pk) + '/profile_image.png' def get_default_profile_image(): return "codingwithmitch/logo_1080_1080.png" class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, 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) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) hide_email = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.username def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index('profile_images/' + str(self.pk) + "/"):] # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return … -
No css work is visible after loading the static file in django
I have just started learning django and got stuck in one place with the 'static' step i did all the steps of static like load static ,STATIC_DIR,ROOT and also wrote in all the image,.js and also in the css line bt still i could only view the html text and not the temp. let me know what to do pls