Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User getting saved as tuple
I am trying to register a user and save his details. I am not getting any error but the user is getting saved as a tuple. Here is the code: Views.py: @csrf_exempt def signup(requests): if requests.method == 'POST': username = requests.POST['uname'], firstname = requests.POST['firstname'], lastname = requests.POST['lastname'], email = requests.POST['email'], password = requests.POST['password'] user = User(username= username, first_name=firstname, last_name=lastname, password=password) user.set_password(password) user.save() return JsonResponse({"message": "User Registered"}) I am getting a success response but the user is saved like this: -
File upload not working after deploying my Django application on a shared hosting
Hi I have recently deployed my Django application on a shared hosting and the deployment went successful, but after the deployment whenever I try to submit a form that contains an input field with type="file" I get an index page as a response. Basically the form request is not even reaching to it's specific method in the 'views.py' file. I am using Ajax-jQuery to submit my forms. Please help me. settings.py """ Django settings for eLearning_platform project. Generated by 'django-admin startproject' using Django 3.0.8. 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 # 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 = 'r%h3za5pxq%3%^q8lzmpdjoen0k8$p@c%*heawr5c_)*8*l9$3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third-part apps 'eLearning_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'eLearning_platform.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, … -
collectstatic collecting static files but they're not loading on webpage
I am deploying my Django site on A2 Hosting. I can get the page to display but no static files (images/css) are loading. I have this in my settings.py: ROOT_PATH = os.path.dirname(__file__) STATICFILES_DIRS = [os.path.join(ROOT_PATH, 'static')] I am running python manage.py collectstatic in the terminal. It is creating a static folder with a file structure including admin and subfolders within that admin folder. My images css files are appearing in the newly generated static file (in the base folder) yet neither the css nor my images are showing on my webpage (I've been restarting my server). My link to my css file within my html template is: <link rel="stylesheet" href="{% static 'style.css' %}" type="text/css"> Thank you. -
why my pip gives same error when i run Django server?
I updated version of my pip but when i run every time any command with pip on terminal it gives same error.. before i tried to create django project.. and after some time when i run project it gives error. i dont know where i am doing wrong.. File "/Library/Frameworks/Python.framework/Versions/3.8/bin/pip", line 8, in <module> sys.exit(main()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 17, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 22, in <module> from pip._internal.req.constructors import ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 10, in <module> from .req_install import InstallRequirement File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 10, in <module> import uuid File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/uuid.py", line 57, in <module> _AIX = platform.system() == 'AIX' File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 891, in system return uname().system File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 857, in uname processor = _syscmd_uname('-p', '') File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py", line 613, … -
'NoneType' object has no attribute 'keys' at starting of my website
When I open my website then I click to my cart page it show error 'NoneType' has no attribute key. but when I add product it work clearly then, I clear my cart it also work but at starting it doesn't work. what to do? def cartpage(request): ids=list(request.session.get('cart').keys()) products= Product.objects.filter(id__in=ids) return render(request,'cart.html',{'products':products}) -
How to write POST function for nested-serializers Django
I am unable to write a .create method for this nested serailizer. I want to create an appointment row for every new appointment and for appointment_detail table i want to create as many rows as many services are opted. my models.py class Service(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE,null=True, related_name='services') service_name = models.CharField(max_length=100) time = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=False) def __str__(self): return self.service_name + ' in ' + str(self.category) class Appointment_Status(models.Model): status = models.CharField(max_length=15) def __str__(self): return self.status class Appointment(models.Model): """This is the model where all the orders/Appointments will be saved""" user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE, null=True) branch = models.ForeignKey(Zorg_Branche, on_delete=models.CASCADE,null=True, related_name='branch') timestamp = models.DateTimeField(auto_now_add=True, blank=True) status = models.ForeignKey(Appointment_Status, on_delete=models.CASCADE, null=True) totaltime = models.PositiveIntegerField(default=0) total_price = models.DecimalField(decimal_places=2, max_digits=10, default=0) def __str__(self): return str(self.user) + ' -> ' + str(self.zorg) class AppointmentDetail(models.Model): appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE,null=True,related_name='appointment') related_name='category') service = models.ForeignKey(Service, on_delete=models.CASCADE,null=True, related_name='service') def __str__(self): return str(self.appointment) + ' ' + str(self.service) in serializers.py class UserAppointmentSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email_id', 'mobile_number', 'birthdate', 'photo_url', 'gender', ] class ZorgBranchAppointmentSerializer(serializers.ModelSerializer): class Meta: model = Zorg_Branche exclude = ['id', 'zorg'] class CategoryAppointmentSerializer(serializers.ModelSerializer): """ This serailizer is to serialize and deserailize category model """ class … -
How to Filer data between 2 Dates in Django?
I am trying to filter data between 2 dates in Django, I am using single input box for this and I am using jquery daterangepicker for this, Please check my coed and let me know where i am mistaking. here is my views.py file... def myview(request): if request.method == 'POST': startdate = request.POST.get('created_on') enddate = request.POST.get('created_on') if start != None or end != None: result = Model.objects.filter(created_on__range=[startdate,enddate]) else: print('Error') here is my forms ... <form method="POST"> {% csrf_token %} <div> <input type="text" name="created_on" value="" /> </div> <div class="col-sm-4"> <button>Submit</button> </div> </div> </form> I am getting errors to filter data, I think i am mistaking in query, Please let me know how i can Solve this issue. -
JWT token mismatch while OTP verification
I'm generating token while user verified OTP. but while i verify the token in header then I'm getting Invalid payload. if any help for why i'm getting this error then would be much appreciated. serializers.py : class OTPVerifyForResetPasswordAPIView(APIView): permission_classes = (AllowAny,) def post(self,request,*args,**kwargs): data = request.data user = request.user print(user) phone_number = request.data['phone_number'] country_code = request.data['country_code'] verification_code = request.data['verification_code'] if phone_number and country_code and verification_code: obj_qs = User.objects.filter(phone_number__iexact = phone_number,country_code__iexact = country_code) obj = '' if obj_qs.exists() and obj_qs.count() ==1: user_obj = obj_qs.first() #Development if verification_code == '1234': payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) token = 'JWT '+str(token) return Response({ 'success' : 'True', 'message' : 'Your mobile number verified successfully', 'data' : { 'phone_number' : user_obj.phone_number, 'country_code' : user_obj.country_code, 'token' : token, } },status=HTTP_200_OK) else: ##some logic.... else: ## some logic... -
How to authenticate session inside class based view django
I am new to Django I am trying to convert my function-based views to class-based views. Here I ran into a problem. I don't know wether the user is logged in or not. I can't call the user.is_authenticated inside my class-based view. My Code: class UserLoginView(FormView): template_name = 'login.html' form_class = UserLoginForm success_url = reverse_lazy('login') def form_valid(self, form): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: login(request=self.request, user=user) print('Login Successfull') return HttpResponseRedirect(self.success_url) def form_invalid(self, form): print('Login Failed') return HttpResponseRedirect(self.success_url) How can I check wether the use is already logged in and send him directly to the home page. Thanks in advance. -
What is the best way to deploy Django web site ,I have already purchased a domain
I had a django website which was up and running but unfortunately it is down now. I'm moving on to re deploying it .Which is best approach to deploy it? There are few static pages and blog post function, and vacancy posting function. Both this blog post nd vacancy post done through the Django admin console(login in separately to Django admin with the super user created).I want all these to work as it is in the new environment. Please suggest best way to to do this? -
Django: Only getting first element of my list instead of the full list from a GET request
I'm having an issue getting a list of objects with a GET request on this endpoint: /api/stock/{bar_id}/ It should return a list of stock for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. When I make the GET request I only end up getting the first stock, but I should be getting the full list of stocks. I'm getting this: { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } Instead of this: { [ { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 }, { "ref_id": { "ref": "second", "name": "second one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } ] } Here is my BarSerializer: from rest_framework import serializers from ..models.model_bar import Bar from .serializers_stock import * class BarIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Bars models from DB """ class Meta: model = Bar fields = [ 'id', 'name', 'stock' ] class BarDetailsSerializer(serializers.ModelSerializer): """ Serializer showing details of a Bar model from DB """ stock = StockDetailsSerializer(many=True) class Meta: … -
Error executing script because its MIME type
I have a DjangoRest/ Vue.js app that I want to deploy. My app is running fine if I run the two servers separately. So I did a npm run build and tried to run it locally as well. I did change my settings and index.html: index.html % extends "base.html" %} {% load static %} {% block style %} <link type="text/css" href="{% static 'bundle.css' %}"> {% endblock %} {% block content %} <div id="app"></div> {% endblock %} {% block js %} <script type="text/javascript" src="{% static 'bundle.js' %}"></script> {% endblock %} This is my vue.config.js: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "https://trustymonkey.herokuapp.com/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public("https://trustymonkey.herokuapp.com/") .host("https://trustymonkey.herokuapp.com/") .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, }}; This is the console: So my bundle.js is found. But I get a blank page and in the chrome dev tool console I get: -
how to display multiple forms on a page using formset
I'm making a form to add an organization record models.py: class Entity(BaseModel): title = models.CharField(_('Заголовок'), max_length=255, db_index=True) short_description = models.CharField(_('Короткое описание'), max_length=255, blank=True, null=True) body = models.TextField(verbose_name=_('Описание'), max_length=4096) ordering = models.IntegerField(_('Порядок'), default=0, db_index=True) test_field = models.TextField(verbose_name=_('Тестовое поле'), max_length=4096) test_field2 = models.CharField(max_length=255, blank=True,null=True, verbose_name=_('Тестовое поле 2')) class Meta: ordering = ('ordering',) verbose_name = _('Форма') verbose_name_plural = _('Формы') class Industry(BaseModel): name = models.CharField(_('Название'),max_length=255, blank=True, null=True) entity = models.ForeignKey( Entity, verbose_name=_('Организация'), related_name='industries', on_delete=models.CASCADE ) class Meta: ordering = ('ordering',) verbose_name = _('Отрасль') verbose_name_plural = _('Отрасли') def __str__(self): return self.name class BaseAddressClass(BaseModel): address = models.TextField(verbose_name=_('Адрес'), blank=True, null=True) oktmo = models.CharField(verbose_name=_('ОКТМО'),max_length=255, blank=True, null=True) postal_code = models.CharField(verbose_name=_('Почтовый индекс'), max_length=20, blank=True, null=True) entity = models.ForeignKey( Entity, verbose_name=_('Организация'), related_name='addresses', on_delete=models.CASCADE, blank=True, null=True ) class Meta: ordering = ('ordering',) class PhysicalAddress(BaseAddressClass): class Meta: verbose_name = _('Физический адрес') verbose_name_plural = _('Физические адреса') class LegalAddress(BaseAddressClass): class Meta: verbose_name = _('Юридический адрес') verbose_name_plural = _('Юридические адреса') i want the page to show the branches in a list and also have the ability to add addresses. for this in the EntityForm, i added the industry. The form with the address added inlineformset_factory.for rendering the formset i am using django-formset.js. forms.py: class EntityForm(forms.ModelForm): industry = forms.ModelChoiceField(queryset=models.Industry.objects.all()) class Meta: fields = '__all__' exclude = ('ordering', … -
How to set up Google Pay for my django online ecommerce website?
I have an online e-commerce website where the user can trade images with each other What I'm trying to achieve is: seller requests the buyer to give him money, the buyer clicks on the "accept payment" and then set up payment with his Google Pay account, finally the seller will get charged in his Google Pay account How can I do so? I'm using Django 3.1 -
Why django library xhtml2pdf returning an error?
I am using xhtml2pdf library in drf viewset to generate a pdf document from an html template that lists all records from a given model. Below is the action that I have defined inside my vieset @action(detail=False) def pdf(self, request, *args, **kwargs): import datetime filter = self.filter_queryset(Ledger.objects.values_list('name','groupid__name','panno', gstin')) pdf_obj = render_to_pdf('reports/report.html', {'data': filter}) if pdf_obj: response = HttpResponse(pdf_obj, content_type='application/pdf') filename = 'Ledgers-' + str(datetime.date.today()) + '.pdf' content = "inline; filename=%s" % (filename) download = request.GET.get("download") if download: content = "attachment; filename=%s" % (filename) response['Content-Disposition'] = content return response This results in ValueError exception with following message <PmlTable@0x7F7C4304B390 2 rows x 0 cols>... must have at least a row and column I am clueless what am I doing wrong here, Please advise. -
Automatic migration handling in django
I have been thinking about how to manage automatic migration like removing fields which are migrated from changing the branch like let say a field x was migration from dev branch and i have moved to master branch and there is no x field there i want to handle this automatically is there any scirpt/library for this or any idea, Thanks -
Handling Public and Internal version of Django Model
I am currently experiencing difficulties in processing community contributions to my publicly available Database. My Backend is designed using Django, and people are allowed to update some data via API calls. I have a lot of models, quite a few of which can be updated via API(DRF). Every registered user is allowed to post some updates, but these updates should not be publicly available immediately. After one of the moderators has reviewed and accepted these updates, they should be publicly available. The structure of each Database Table is designed with three states: "draft", "accepted" and "rejected". class SomeModel(models.Model): class Status(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted') REJECTED = 'rejected', _('Rejected') top_city = models.CharField(max_length=255) ... all other attributes goes here ... New data should replace the previously accepted data after review. Until this review has been completed (1, 2 or 3 days), the previously accepted data should remain public. Simply said, multiple versions of the model - one is public, the other is "internal" until accepted. Solution like Mixin Model or class decorator would be the best, so I don't need to repeat a lot of code in each Model. My current idea how to solve this does not … -
Filtering record from django model using a tuple
I have a django model such as this id task_id status content_type content_encoding result date_done meta task_args 1 "9bb8b186-da5d-43b2-8fca-1496474b1cc9" "SUCCESS" "application/json" "utf-8" """done""" "2020-09-23 14:15:03.064283+05:30" "{""children"": []}" "('test_user', 1, ['test'], 'id_001')" The task_args field in the model is a text field. How do I filter the model based on this data? Specifically I want the task_id where task_args is ('test_user', 1, ['test'], 'id_001') This is my code so far user = request.user.username num = 1 parsed_data = eval("['test']") id = "id_001" print(type(parsed_data)) args = f"{(user,num,parsed_data,id)}" print(args) task_id = list(TaskResult.objects.filter(task_args=args).values('task_id')) Right now this code outputs an empty list Not sure what I am doing wrong. Is this because I am passing the tuple as a string? I am passing this as a string because the task_args field is a text field. I also tried passing this as a tuple. Even that results in an empty list. -
How to call a request inside a class in view
I am new to Django. I need to set the foreign key as current signed in user for a post model but it says the NOT NULL constraint failed: posts_post.author_id django I dont know why. class UserRegistraionModel(models.Model): post = models.CharField(max_length=5000, blank=False, null=False) image = models.ImageField(upload_to='media', blank=False, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) I don't know what is the error how can I solve this. Thanks in advance. -
Meaning of these lines (python, django and channels)
I was messing aroung with django channels, and I was wondering how can I add a user to a chat, so I've come across this answer in stackoverflow: How to add members to same chat room in Django Channels 2.1.1 using multichat example But then I came across these lines and I realized that I don't understand them: '''if staff in users_and_rooms and len(users_and_rooms[staff]) in range(3):''' '''await channel_layer.send(users_and_channels[random_available_staff], content)''' '''users_and_channels[random_available_staff],''' I guess 'users_and_channels' is a dictionary with value pairs being the user and his/her channel. I got that. But what about the first line? 'len(users_and_channels[staff] in range(3)' Isn't 'range' for loops? What is it doing there? And 'len(users_and_channels[staff]', it is checking the length of what? The number of channels of a user? It's a little confusing to me. Hope someone can help me. Thank you very much. And excuse my English. -
How to send data via http request in django
I was trying to make a django webapp and I can send data through the http request. I want to send the id or number to be sent on the background not on the URL my main goal was to send the data like the user object in django, so we can access the data in the html like the user object {{user}} i tried to send with the request object but i didn't work -
How to login with register api if user already exits while social authentication: Django?
I'm creating custom user social authentication system. whenever user first time login then with social account then his/her social credential will be save in db. if second time will login with social account then it's automatic will login with his/her social_id that saved in db. but in my case, whenever user first time login with social account then his/her social credential saves in db. but in second time it's showing user already exits. Any help would be much appreciated. serializers.py : class CreateSocialUserSerializer(serializers.ModelSerializer): login_type = serializers.CharField(allow_blank=True) social_id = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) phone_number = serializers.CharField(allow_blank=True) country_code = serializers.CharField(allow_blank=True) token = serializers.CharField(read_only=True) first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) class Meta: model = User fields = ['login_type', 'social_id', 'email','phone_number', 'country_code','token','first_name','last_name', ] def validate(self,data): logger.debug(data) login_type = data['login_type'] social_id = data['social_id'] email = data['email'] phone_number= data['phone_number'] country_code = data['country_code'] #some validation logic here...... #Email Validation logic here ..... #Mobile Number Validation if phone_number.isdigit() == True: user_qs = User.objects.filter(phone_number__iexact = phone_number) if user_qs.exists(): raise APIException400({'success' : 'False','message' : 'User with this phone_number is already exists'}) else: if login_type in ['2','3','4','5','6']: if social_id: social_qs = User.objects.filter(social_id__iexact=social_id) if social_qs.exists(): raise APIException400({'success': 'False', 'message': 'User with this social_id is already exists. Please login.'}) return data return data … -
only '-' value appeared for all the data in my csv file
from django.contrib import admin from .models import NutritionModel from import_export.admin import ImportExportModelAdmin class NutritionModelAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] search_fields=['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] filter_horizontal=() list_filter=[] fieldsets=[] admin.site.register(NutritionModel,NutritionModelAdmin) from import_export import resources class NutritionModelResource(resources.ModelResource): class Meta: model = NutritionModel resource_class = NutritionModel #models.py from django.db import models class NutritionModel(models.Model): id=models.AutoField(primary_key=True) sl_no = models.CharField(null=True, blank=True,max_length=5, verbose_name="Sl no") sub_domain = models.CharField(null=True, blank=True,max_length=5,verbose_name="Sub-domain") indicators =models.CharField(null=True, blank=True,max_length=200,verbose_name="Indicators") national_indicator_reference =models.CharField(null=True, blank=True,max_length=10,verbose_name="National indicator reference") sector =models.CharField(null=True, blank=True,max_length=20,verbose_name="Sector") data_collab = models.CharField(null=True, blank=True,max_length=100,verbose_name="Ministry/ Agencies for data collaboration") variable_required =models.CharField(null=True, blank=True,max_length=200,verbose_name="Variable required") data_sources =models.CharField(null=True, blank=True,max_length=10,verbose_name="Data sources@") -
ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'
I am new to django framework. I tried to create a login authentication through twitter using tweepy. While saving the fetched data in my db, I am facing this issue for OAuth1Session. I have tweepy installed. I have also installed requests_oauthlib, but still doesn't able to resolve this error. from tweepy.auth import OAuthHandler #error called here (**ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'** ) from .models import Tweet import credentials def user_tweets(): auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET) auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) user_tweets = api.user_timeline(count=50) return user_tweets -
How can I add an instruction after an object creation in Django CreateView?
On my generic class based CreateView, I would like to perform an instruction which creates new objects from another model related to the current created object. Example: Collection is a model which is related to 3 differents Element objects. When I create a MyCollection object, which is related to a Collection and a User, 3 MyElement object must be created too and related to the newly created MyCollection object. One for each Element related to Collection. # models.py from django.contrib.auth.models import User from django.db import models class Collection(models.Model): # attributes and methods... class Element(models.Model): collection = models.ForeignKey(Collection, # more arguments...) # more attributes and methods class MyCollection(models.Model): user = models.ForeignKey(User, # more arguments...) collection = = models.ForeignKey(Collection, # more arguments...) # more attributes and methods def get_absolute_url(self): reverse(# some url with the object pk) class MyElement(models.Model): element = models.ForeignKey(Element, # more arguments...) my_collection = models.ForeignKey(MyCollection, # more arguments...) # more attributes and methods I'm using the generic CreateView from Django and after a little bit of research, I saw that it was possible to perform additional actions in the CreateView by overriding the get_success_url() method. In my example, I did something similar: # views.py from django.views.generic import CreateView from .utils …