Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to register user with email verification using django rest auth
I set up Django custom registration using the Django-rest-auth, I also want to verify the email by sending emails which I heard that Django all auth does out the box. but this doesn't seem to work. I don't know if to install any package or what. I created a custom register which ingeris from django-all-auth.but it doesnt seem to work still. my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email my custom register views.py from rest_auth.registration.views import RegisterView from django.contrib.auth import get_user_model class CustomRegisterView(RegisterView): def create(self, … -
DRF - How to change serializer.PrimaryKeyRelatedField's filter lookup key with condition?
I am trying to change serializers.PrimaryKeyRelatedField's filter lookup key based on other boolean field on serializer but I could not be successful. PrimaryKeyRelatedField filtering by pk key by default. In some condition (if condition field on serializer sent as True), I just want to change that filtering key with another field on related model's field like remote_id. class SomeSerializer(serializers.Serializer): condition = serializers.BooleanField(default=False) model_pks = serializer.PrimaryKeyRelatedField(queryset=Model.objects.all(), many=True) I tried to create new field which is inherited from PrimaryKeyRelatedField and override get_queryset method (not sure to override correct method) so far but I could not access condition and model_pks fields values. class CustomPrimaryKeyRelatedField(PrimaryKeyRelatedField): def get_queryset(self): queryset = self.queryset # model_pks = sent model_pks if condition: return queryset.filter(remote_id__in=model_pks) return queryset.filter(id__in=model_pks) Also, I tried to use SerializerMethodField instead of PrimaryKeyRelatedField like; class SomeSerializer(serializers.Serializer): condition = serializers.BooleanField(default=False) model_pks = serializer.SerializerMethodField() def get_model_pks(self, value): pks = self.initial_data.get('model_pks', []) if value.get('condition', False): return Model.objects.filter(remote_id__in=pks) return Model.objects.filter(pk__in=pks) It's provide changing lookup key based on condition but this time I could not access model_pks values with serializer.validated_data. Is there any way to make conditional lookup key filtering using PrimaryKeyRelatedField? -
Frontend editing stopped working in Django CMS after installing application
After installing the application djangocms_blog, and letting it run auto setup my ability to use the frontend editor broke. I installed using pip install djangocms-blog==1.0.0rc1. Normally, the content of placeholders is clickable to be edited. Right now, this feature is broken on all pages. -
How to correctly write custom Renderer to download file with django REST API
I am running a Django app where I can upload files. Now I want to download the files using django REST framework. I am trying to overwrite the custom renderer following the spare documentation on Renderers and on FileResponses as well as this question: How to return generated file download with Django REST Framework? My model: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(storage=PrivateMediaStorage(), null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) My views class PassthroughRenderer(renderers.BaseRenderer): media_type = 'application/pptx' format = 'pptx' def render(self, data, accepted_media_type=None, renderer_context=None): return data class FileView(viewsets.ReadOnlyModelViewSet): queryset = FileCollection.objects.first() Now I am lost.... It's not clear to me how I can use this renderer to create a download for my file. I'm very grateful for help or hints. Thanks so much -
Key error - "type" in django while migrating from existing mysql to mongodb through djongo
while migrating my existing database engine from SlqlLite to MongoDB through djongo ( a django ODM), I am facing this issue of key error, which simply means when a key and its associated value is not present in the dictionary of constraints, I am suspecting its because I am already having existing data model classes. The tutorials I followed were only about starting a fresh project through mongoDB. The key 'type' is not present in the dictionary within file scripts.py (library file). I got to know that through a simple modification of printing the dictionary, plz help me guys as I am a Django newbie! major suspect is identification_identification_slug_27be3d04': {'columns': ['slug'] in dictionary i dont even know type the type field stands for ? its not ven any constraints powershell screenshot settings.py affecting lines in schema.py -
Handle error of a specific time raised at any point
Occasionally we are getting OperationalError: FATAL and we have no idea why. I want to handle this error wherever it happens in the application and send me a personal email. I would also like to set up a system command call to inspect the database activity (I know this is a bad idea but it's the only thing I can think of to try to figure out why this is happening). How can I do this? Summarized: catch an error of a specific type raised at any point and handle it in a custom and granular way. -
How to generate models.py classes by xsd in django?
So, i am trying to generate models.py classes with django. I'm trying to do it with gends_run_gen_django.py. I watched this at this question : Generate Python Class and SQLAlchemy code from XSD to store XML on Postgres I'm trying this command. gends_run_gen_django.py -f -p C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\generateDS.py C:\Users\test\Documents\Files\XMLSchemaPersonAdress.xsd But i getting this error: Traceback (most recent call last): File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 201, in <module> main() File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 195, in main generate(options, schema_name) File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 91, in generate if not run_cmd(options, args): File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 118, in run_cmd process = Popen(args, stderr=PIPE, stdout=PIPE) File "c:\users\test\appdata\local\programs\python\python38-32\lib\subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "c:\users\test\appdata\local\programs\python\python38-32\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, OSError: [WinError 193] %1 is not a valid Win32 application What i need to do? -
Django - Testing Carrying Over POST Variables
I am working on doing some code coverage unit testing for my Django application when I ran into this interesting predicament. tests/test_views.py class TestLogin(TestCase): def setUp(self): self.client = Client() self.url = reverse('account:login') self.template = 'account/login.html' # This test works def test_POST_invalid_login(self): response = self.client.post(self.url, { 'username': 'foo', 'password': 'bar' }) self.assertEqual(response.status_code, 401) self.assertTemplateUsed(response, self.template) # This is not working as intended. def test_POST_no_data(self): with self.assertRaises(MultiValueDictKeyError): self.client.post(self.url, None) views.py class Login(View): form_class = LoginForm template = 'account/login.html' def get(self, request): form = self.form_class(None) context = { 'form': form } return render(request, self.template, context) def post(self, request): try: # Retrieve the username and password username = request.POST['username'] password = request.POST['password'] # Create a user object from authentication, or return None user = authenticate(username=username, password=password) # Check if user was created if user is not None: # Login the user to the website login(request, user) messages.success(request, 'Login successful! Welcome ' + user.first_name + ' ' + user.last_name) # Eventually have this go to profile pages. return redirect('home', permanent=True) else: messages.error(request, 'Login failed: Invalid User.') except MultiValueDictKeyError: messages.error(request, 'Login failed: Invalid User.') # Clear the form since the login attempt failed. form = self.form_class(None) context = { 'form': form } return render(request, self.template, context, … -
Django ListView with post method, get_queryset does not come filtered
In my application i made a ListView, in this ListView i have to make a post so i'm defining the post method, in this post method i need the filtered get_queryset method, but it comes unfiltered as if it is default. I made some research and i've noticed method post() is ran before get_queryset(), my question is: Is there any way i can get the filtered get_queryset() in the post() method? Ex: def get_queryset(self): qs = super(FilteredListView, self).get_queryset() q = Q() if self.request.session.get('make_id'): q.add(Q(owner__make=self.request.session['auto_id']), Q.AND) if self.request.user.is_superuser: return qs.filter(q).distinct('id').order_by('-id') return qs.filter(q, owner=self.request.user.company).distinct('id').order_by('-id') def post(self, request, *args, **kwargs): if 'action' in self.request.POST: action = self.request.POST.get('action') if action == 'batch_approve': queryset = self.get_queryset() # i need the filtered queryset here, but it comes unfiltered return redirect('{}?{}'.format(reverse('flow:filtered_list'), request.GET.urlencode())) return redirect('flow:filtered_list') -
Django Record datetime with timezone
I'm having trouble with timezone time recording. I have on settings.py: TIME_ZONE = 'America/Sao_Paulo' USE_TZ = True I have in model: hour = models.DateTimeField(null=False) In the template I get string time 10:00:00: {% load tz %} {% localtime on %} 10:00:00 {% endlocaltime %} Before saving convert the string to datetime: import datetime form = Form(request.POST) data = form.data hour = datetime.datetime.strptime(data.get("hour"), "%H:%M:%S") When returning to the template, it is show 13:06:00: {% load tz %} {% localtime on %} 13:06:00 {% endlocaltime %} In the database, another different value, like the same timezone 09:59:32-03:06:28: db=# SHOW TIMEZONE; TimeZone ------------------- America/Sao_Paulo (1 registro) db=# select hour from supply; hour ------------------------------ 1900-01-01 09:59:32-03:06:28 (1 registro) I'm confused. Thanks for helping. -
Is it possible to forward processed (in views.py) form data for further use?
I am new to django so sorry if I will not succeed to express myself clear enough. To begin with: I have build simple form to perform simple calculations and return result based on user input. Now I would like to add an option for user to generate PDF from these results, but I am not sure what kind of approach should I use. My first idea was to store calculation data in some sort of global variable and pass it to the view responsible for generating PDF. According to answer to this question there should be few ways to do that (but I am not sure if they fit because for example my url never changes). My second idea that since url never changes maybe data is still somewhere and can be accessed somehow? What I am trying to say, that I have calculation results passed in dictionary form (named context in my code) to results html template. Can I still access this dictionary and use it in another views.py function? Can somebody provide some insights or direct me to what kind of literature I should search (since I do not exactly know what approach I should take and … -
The Celery in Django task is not performed correctly. No errors
I try start the basic celery task according to this tutorial. My configuration looked like this: My Django-Project >> app_rama __init__.py celery.py settings.py urls.py wsgi >> app tasks.py __int__.py in app_rama from __future__ import absolute_import from .celery import app as celery_app Settings.py # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' tasks.py in app from celery.decorators import task @task(name="sum_two_numbers") def celery_task(): print('Celery Task - OK') def typical_task(): print('Typical Task - OK') views.py from django.shortcuts import render from .tasks import celery_task, typical_task def home(request): data = request.GET.get('data', False) if data: print('Start Test') celery_task.delay() typical_task() print('End Test') context = {'data': data} return render(request, 'home.html', context) home.html <h1>{{ data }}</h1> <br> <a href="?data=TEST_STARTING"> <button type="button">Test</button> </a> <br><br><br> <a href="{% url 'app:home' %}"> <button type="button">Come back to start</button> </a> I'm trying to make my celery task work properly. But I don't receive any action or error information. After clicking the test button, the Celery task should be completed. But this does not happen, only a test task is performed. The whole Redis configuration seems to be working properly. I can enable the server from the command line and he respond to the … -
No url other than domain.com are working in my django project production mode,
whole django project works fine on localhost. but when i uploaded it to linux shared server and deployed the project only domain.com works . other links like domain.com/admin or domain.com/xyz are redirecting to 500 Internal Server Error. most of the answers are linked to passenger server problem in passenger_wsgi.py but i can not find any error or problem in it passenger_wsgi.py import myapp.wsgi SCRIPT_NAME = '/home/username/myapp' class PassengerPathInfoFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = myapp.wsgi.application application = PassengerPathInfoFix(application) -
Issue with django POST requests and nginx
I have an nginx in front of my Django application, and I have a frustrating issue with POST requests. It seems that sometimes, the response of a POST request gets "lost" and is not returned to the browser. However, no error is generated. I have tested this with both uwsgi and gunicorn, and I can reproduce the same error under both application servers. My nginx config is quite simple: upstream django { server myapp:8000; # } server { listen 8000 default_server; location / { charset utf-8; #include uwsgi_params; #uwsgi_pass django; proxy_pass http://django; client_max_body_size 512M; # add_header X-XSS-Protection "1; mode=block" always; # add_header X-Content-Type-Options "nosniff" always; } location /media/ { alias /uploads/; add_header X-XSS-Protection "1; mode=block" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Cache-Control "no-store" always; } location /static/ { alias /static/; add_header X-XSS-Protection "1; mode=block" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; expires 1y; add_header Cache-Control "max-age=31536000"; } } The problem is, there is no consistent way to reproduce it. I can sometimes trigger it, by changing my password in django-admin. After changing my password by hitting the "change my password" button, my browser keeps waiting and it never seems to stop, it keeps waiting … -
How to get data from another database
I have created superuser(Admin)inside Admin, I have created a button and after clicking on it is should show data of another database table after clicking on button it should show all data of another Database table inside superuser(Admin) -
Django : Template not found/index.html
I am running a website using Django. There is no problem in login. When i logged in and click on some dashboard, it is showing "page not found"(404). Views.py: def index(request): return(request,'obs_app/index.html') Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates/index.html') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'libraries': { 'get_by_index':'obs_app.templatetags.templatefilters', 'get_by_key':'obs_app.templatetags.templatefilters', 'get_dict':'obs_app.templatetags.templatefilters', 'get_items':'obs_app.templatetags.templatefilters', 'multiple':'obs_app.templatetags.templatefilters', }, }, }, ] urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url from obs_app import views urlpatterns = [ url(r'index/',views.index , name = 'index'), path('admin/', admin.site.urls), path('', views.user_login, name='user_login'), path('dashboard',views.obs_index, name='admin_dash'), path('halls/active',views.obs_halls_active,name='active-halls'), path('halls/pending',views.obs_halls_pending,name='pending-halls'), path('febs/userlist', views.febs_user_list, name='febs-users'), path('bookings/user', views.bookings_user, name='bookings-users'), path('bookings/owner', views.bookings_owner, name='bookings-owner'), path('cancellation/user', views.cancelled_user, name='cancelled-user'), path('cancellation/owner', views.cancelled_owner, name='cancelled-owner'), path('terms/obs', views.terms_conditions, name='terms-conditions'), path('terms/febs', views.terms_febs, name='terms-febs'), path('terms/febs/events', views.terms_febs_events, name='terms-febs-events'), Error i am getting is : Page not found (404) The current path, index.html, didn't match any of these. -
Conditionally nest Django serializers
So, I have a foreign key to my User model in many of my models. Now, the serializers for these models are nested, in that they include the entire user object rather than just the id. I have done so as shown bellow: class BadgeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Badge fields = '__all__' It works as expected. However, I seldom find myself in a situation where I want just the id. I was wondering if there is a way to conditionally nest my BadgeSerializer... -
Unsuccessful command execution on instance id(s)
I am trying to deploy my app on AWS but it seems to stuck at this point: Uploading: [##################################################] 100% Done... 2019-10-22 11:01:57 INFO Environment update is starting. 2019-10-22 11:02:00 INFO Deploying new version to instance(s). 2019-10-22 11:02:09 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-10-22 11:02:10 ERROR [Instance: i-#######] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2019-10-22 11:02:10 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2019-10-22 11:02:10 ERROR Unsuccessful command execution on instance id(s) 'i########'. Aborting the operation. 2019-10-22 11:02:11 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. It says that my requirements.txt is invalid, Why ? Requirement.txt Django django-crispy-forms==1.7.0 pytz==2017.3 gunicorn==19.9.0 django-widget-tweaks psycopg2 Please help me in figuring out what I am doing wrong. -
Django form save related object only if form is valid
I think I have a rather uncommon feature here, at least I couldn't find a answer. What I'd like to achieve is a text input with autocomplete on a related model with its label field. the given text should then get_or_create the related model. this already works but the problem is, that the new related model instance is saved on form submit no matter if the form is_valid or not. given the following situation and implementation (shortened for better overview) class Correspondent(models.Model): label = models.CharField(_("label"), max_length=100, unique=True) class Document(BaseModel): correspondent = models.ForeignKey( Correspondent, verbose_name=_("correspondent"), on_delete=models.PROTECT, related_name="documents", ) with the following form: class DocumentForm(forms.ModelForm): correspondent = forms.CharField( label=_("correspondent"), widget=forms.TextInput(attrs={"class": "awesomplete"}) ) class Meta: model = Document exclude = ["created_by", "modified_by"] def clean_correspondent(self, *args, **kwargs): # ToDo: don't save the FKed instance if complete form isn't valid user = self.initial["user"] data = self.cleaned_data["correspondent"] errors = {} try: obj = Correspondent.objects.get(label=data) except: obj = Correspondent(label=data, created_by=user, modified_by=user) obj.save() return obj so the problem here is obj.save() which is called before form.is_valid() and I couldn't figure a way yet how to solve this. I'd like to prevent the creation of a new Correspondent instance if the form isn't valid yet. Let me know if … -
Python Django: Count business days
I need to count business days between two dates. In addition, I must also remove the days listed in a separate table (holidays). So far I have this code. It counts the days but does not remove the days from the separate table (holidays). class Holidays(models.Model): class Meta: ordering = ['date'] date = models.DateField(null=True, verbose_name='Date') class Situation(models.Model): class Meta: ordering = ['date_time_start'] date_time_start = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time Start') date_time_end = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time End') @property def business_days(self): holidays = Holidays.objects.values_list('date', flat=True) oneday = datetime.timedelta(days=1) dt = self.date_time_start.date() total_days = 0 while (dt <= self.date_time_end.date()): if not dt.isoweekday() in (6, 7) and dt not in holidays.values(): total_days += 1 dt += oneday return total_days -
Exception in thred django-main-thread:
Creating forms from models i'm new to django and try to models form but unfortunate get some bizarre error even i twice check my code as well i checked django documentation but not figure out my issue... i visit this django documentation but not figure out yet!!! quite confusing! https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/ Traceback (most recent call last): File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\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 … -
Django join two models in ListApiView
I listed blog post using django rest api View.py class BlogDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Blog.objects.all() serializer_class = serializers.BlogSerializer models.py class Blog(models.Model): title = models.CharField(max_length=50) content = models.TextField() content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category_id = models.CharField(max_length=50) class Category(models.Model): category_id = models.TextField() category_title = models.TextField() serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'title', 'content', 'created_at',) model = models.Blog But i want to list the blogs under different categories. How to join Cart and Blog model?. Here category id are common in two models. -
__name__ attributes of actions defined in <class 'astromatchapp.report.admin.user.ReportUserAdmin'> must be unique
ERRORS: <class 'astromatchapp.report.admin.user.ReportUserAdmin'>: (admin.E130) __name__ attributes of actions defined in <class 'astromatchapp.report.admin.user.ReportUserAdmin'> must be unique. <class 'astromatchapp.web.admin.user.UserAdmin'>: (admin.E130) __name__ attributes of actions defined in <class 'astromatchapp.web.admin.user.UserAdmin'> must be unique. ?: (urls.E007) The custom handler404 view 'astromatchapp.web.views.http_error.handler404' does not take the correct number of arguments (request, exception). After migrate to my manage.py this error has been generated. -
'in <string>' requires string as left operand, not BoundWidget sendgrid
I am working on a django web application. I have a contact us form. when a user submits the form, the message in the form is sent as a mail to a predefined email id. For sending the email, I am using sendgrid. I created an account and generated an api for this purpose. I stored the api key in a dotenv file and access the api in the settings.py file .env file SENDGRID_API_KEY=XXXXXXXXXXXXXXXXXXXX settings.py import os from dotenv import load_dotenv load_dotenv() ... EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY") views.py def index(request): if request.method == "POST": ContactUsForm = ContactUs(request.POST) if ContactUsForm.is_valid(): firstName = ContactUsForm['firstName'] fromEmail = ContactUsForm['email'] message = ContactUsForm['message'] send_mail(subject=f"{firstName} sent you a message", message=message, from_email=fromEmail, recipient_list=['toaddress@email.com']) return redirect('home') else: ContactUsForm = ContactUs() context = {'contactUs': ContactUsForm} return render(request, 'index.html', context) But when I submit the form, I get this error message TypeError: 'in <string>' requires string as left operand, not BoundWidget I dont know where I went wrong. This is the link I followed to send emails with sendgrid -
Why am i getting importerror: module not found when i have it installed already?
I am migrating from django-sqlite3 to postgresql and so I have installled postgresql and required modules(psycopg2) in my apache2 server. I have installed psycopg2 correctly- >>> import psycopg2 >>> psycopg2.__version__ '2.8.4 (dt dec pq3 ext lo64)' >>> psycopg2._psycopg.__version__ '2.8.4 (dt dec pq3 ext lo64)' Yet, it throws an error as follows-ImportError: No module named psycopg2._psycopg(as shown in my error.log file) I have searched all threads on stackoverflow and github but couldnt find any solution.