Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery randomly fails silently when handling tasks
I have a Django project that uses Celery to run background tasks and scheduled tasks (via Celery Beat). It runs fine locally but has some intermittent problems in production. This is the difficult part, 50% of the time the task completes as expected but the other 50%, it 'fails' silently. The numerous scheduled tasks complete without issue. Version details django = "==2.2.4" celery = "==4.4.6" python_version = "3.6" Here's a simplified example of the code: models.py class Task(models.Model): is_actioned = models.BooleanField(default=False...) # Other fields... def create_lead(self): Lead.objects.create(....) def create_something_else(self): # Add M2M records, for example: lead.add(obj) def handle_task(self): self.create_lead() self.create_something_else() # Make various API calls def action(self): self.handle_task() self.is_actioned = True self.save() tasks.py @shared_task def action_task(task_id): tasks = Task.objects.get(id=task_id) task.action() views.py # Call the task action_task.delay(task.id) Procfile web: daphne -b 0.0.0.0 -p 5000 myproj.asgi:application worker: celery worker --app=myproj.celery -l debug beat: celery beat --app=myproj.celery -l info When viewing the logs a failed task does not appear to be received by the worker. The strange part is Celery seems to 'select' which methods to fail/skip. For example, Task.create_lead will be called successfully but Task.create_something_else will not be called. However, self.is_actioned = True will always run without fail. I would expect this … -
HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url:/index
I am using Django 2.2.10 I have written an authentication app, with view function that returns JSON data as ff: def foobar(request): data = { 'param1': "foo bar" } return JsonResponse(data) I am calling this function in the parent project as follows: def index(request): scheme_domain_port = request.build_absolute_uri()[:-1] myauth_login_links_url=f"{scheme_domain_port}{reverse('myauth:login_links')}" print(myauth_login_links_url) data = requests.get(myauth_login_links_url).json() print(data) When I navigate to https://localhost:8000myproj/index, I see that the correct URL is printed in the console, followed by multiple errors, culminating in the error shown in the title of this question: HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url:/index (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)'),)) How do I fix this issue? -
How do i use pagination pagination in django when i apply filters in class based view. the url always keeps changing how can i track the url
How do I use pagination in Django when I apply filters in a class-based view. the URL always keeps changing how can I track the URL to go to the next page. can anyone help me -
How to store one of three forms or formsets in Django?
It will remain the owner of the copyright application. The owner may again be private or joint or institutional. How can this problem be solved once? Thanks! -
Uable to get the product name from the model
I've create 3 models for the Order processing. However, I couldn't show the product name on template for every single order. Does my for loop logic or 'get' method go wrong? models.py: class Product(models.Model): product_name = models.CharField(max_length=200) price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) created = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.product_name class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.product_name}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user.username view.py: def user_info(request): orders = Order.objects.filter(user=request.user, ordered=True).order_by('-start_date') context = { 'orders': orders, } return render(request, 'home.html', context) home.html: {% for order_item in orders.items.all %} <p>{{ order_item.item.product_name }}</p> {% endfor %} -
Unable to create meeting with Zoom API (response code 200)
I'm using the zoomus(https://github.com/prschmid/zoomus/) Python module to create a Zoom meeting via the Zoom API. However, I did notice that when using client.meeting.create(), I'm getting an http response code of 200 (not 201) which I think means the response is successful but the meeting isn't created. The call I'm making in my django app: # create Zoom meeting client = ZoomClient('xxx', 'xxxx') zoom_format = Event.start_date.strftime("%Y-%m-%dT%H:%M:%SZ") zoom_meeting = client.meeting.create(topic="Meeting", type=2, start_time=str(zoom_format), duration=30, userId=str(updatedEvent.user.email), agenda="", host_id=str(updatedEvent.mentor_user.email)) print(zoom_meeting) The response I'm getting is a 200, but it needs to be 201 in order to actually create the meeting: { "endpoint": "https://api.zoom.us/v2/users/xxx/meetings", "response_headers": [ "Set-Cookie: zm_aid=""; Domain=.zoom.us; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/; Secure; HttpOnly" ], "date_time": "2020-07-28 06:52:33", "method": "GET", "request_body": "N/A", "response": { "page_size": 30, "total_records": 0, "next_page_token": "", "meetings": [ ] }, "request_headers": [ "accept-encoding: gzip, deflate", "accept: */*", "authorization: ******", "connection: close", "user-agent: python-requests/2.24.0" ], "request_params": [ "user_id: xxx" ], "http_status": "200" } Any ideas as to what I'm doing wrong? It looks like the only required information is the date and the userID which I did supply. Thanks for your time. -
I am making POST request from flutter app to Django-Rest user and getting null response
I'm a novice at this. I have been making POST requests from my flutter app to Django-Rest user and getting a null response on vendor name as copy pasted below. Other parts of the the json body are posting normally except for the user that the POST request is directed to. I want to be able to send the order from the flutter app to the particular user that posts the stock product. When I post I am able to send all the details such as name and number,but the vendor name gives that null response. I have tried googling but I don't understand what is wrong with the code this is the json response: { "vendor": null, "name": "Test", "number": "072345678", "address": "Linc street", "size": "3kgs", "note": "4th floor" }, `` The Post request in Flutter: Future<Order> createOrder(vendor, String name, String number, String address, String size, String note) async { final String apiUrl = 'http://10.0.2.2:8000/Order/'; final response = await http.post(apiUrl, body:{ vendor: vendor, "name": name, "number": number, "address": address, "size": size, "note": note }); if(response.statusCode == 201){ final String responseString = response.body; return orderFromJson(responseString); }else{ return null; } } and Order orderFromJson(String str) => Order.fromJson(json.decode(str)); String orderToJson(Order data) => … -
how do I break up long words in my Django project?
so I have a username on my site that's overflowing out of the content box as you can see here so I thought h1, h2, h3, h4, h5, h6 { color: #44444 overflow-wrap: break-word;}. would help but that it didn't the code for the profile page is as follows all CSS for the profile page works except for the overflow. if anyone could help me I would appreciate it :) -
Django application - singleton data
I have to configure my Django application. It has several fields, which can vary from time to time and have an impact on all models. It can be modified via Django settings file, but I wish it would be possible to change them in Django admin panel. Is it possible? I do not want to declare a model, which can have a lot of instances, cause it would be a hack. -
Django rest framework API with filter
Models.py Categories: class Category_product(models.Model): category_name = models.CharField(max_length=200, unique=True) def __str__(self): return self.category_name Products: class Warehouse(models.Model): category_product = models.ForeignKey( Category_product, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) condition = models.BooleanField(default=False) amount = models.IntegerField() barcode = models.BigIntegerField() f_price = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name urls.py path('products-list/', views.WarehouseList.as_view()), Views.py class WarehouseList(generics.ListCreateAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer I want to get products by exact category For example: I have product category { "id": 1 "category_name": "Electronics" } If I send GET request to api/products-list/?cat=1 I want to get products which have this category -
Store first name of user using foreign key on User model django
right now I'm working with a blogging system which I am making without using an admin site of django. So, I have to create a blog post models and views functions that store the blog data to database manually.In that I have used User login with custom user models and a foreign key for store logged user's first name in BlogData database from User model. My problem is that I cant directly connect to user's first name by views.Is there any way to do it. Here is my code, Models.py (BlogData) from django.db import models from login.models import User # Create your models here. class BlogData(models.Model): blogger_name = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blogger_name') publish_date = models.DateTimeField(auto_now=True) blog_title = models.TextField() blog_subtitle = models.TextField() blog_body = models.TextField() blog_baseimg = models.ImageField(upload_to='pics',null=True) def __str__(self): return self.blog_title Views.py from django.shortcuts import render from .models import languages,BlogData def submit_post(request): if request.method == 'POST': blg_tt = request.POST['blog_title'] blg_stt = request.POST['blog_subtitle'] blg_cnt = request.POST['blog_content'] blg_img = request.POST['blog_img'] data = BlogData.objects.create(blog_title=blg_tt,blog_subtitle=blg_stt,blog_body=blg_cnt,blog_baseimg=blg_img) data.save() return render(request,"index.html") Models.py (Custom User Model) from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager # Create your models here. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self,email,password,**kwargs): email = self.normalize_email(email=email) user = self.model(email=email) user.set_password(password) user.save(using = self._db) return user def create_user(self,email,password = … -
Django menu Tree foreach
This is my models in Django: from django.db import models # Create your models here. statusChoice = ((1, 'Show'), (2, 'Hide')) class newCatagory(models.Model): cat_name = models.CharField(max_length = 255) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank = True) created_at = models.DateTimeField(auto_now_add=True) status = models.SmallIntegerField(choices = statusChoice, null=True) def __str__(self): return "%s, --%s" % (self.parent, self.cat_name) class products(models.Model): pro_name = models.CharField(max_length = 255, null =True) sub_cat_id = models.ForeignKey(newCatagory, on_delete=models.CASCADE, null=True, blank = True) pro_image = models.ImageField(null = True) pro_price = models.FloatField(null = True) description = models.TextField(null = True) status = models.SmallIntegerField(choices = statusChoice, null=True) created_at = models.DateTimeField(auto_now_add=False, null=True) def __str__(self): return self.pro_name i am creating models like above. But i don't know how to show my catagory to my view. How can i do that This is my templates html: <li><a href="#">{{This is catagory}}</a> <ul class="sub-menu"> <li><a href="#">{{this is subcatagory}}</a></li> </ul> </li> I am trying to use for loop but don't know how to use, please help -
How to use placeholders outside django-CMS?
I'm trying to implement the documentation on django-cms on How to use placeholders outside the CMS It seems possible to define a field in a model app external to the CMS which will behave like the djangocms-text-ckeditor But I can't get this 'templatetag' to work {% extends 'base.html' %} {% load cms_tags %} {% block content %} <h1>Title page info</h1> {% render_placeholder object.short_text "640" %} {% endblock content %} Here my info.models.py from django.db import models from cms.models.fields import PlaceholderField class MsgDet(models.Model): title = models.CharField(max_length=255) short_text = PlaceholderField('content') I've create a small django-cms project following the django-cms tutorail using django CMS installer. The source code is on GitHub under OpenHBP/PlaceholderField. I've added a simple info app to the cms and I try to display "MsgDet.short_text" fields inside a "CKEditor like" plugin. A double-click on the CMS home page opens a CKeditor window. I would like to achieve the same result on my info page! I know this can be achieved by using RichTextField from ckeditor but I would like to use "PlaceHolderFiled" in order to have access to djangoCMS plugins: picture/image or file. Note that I've also tried with django-ckeditor-filebrowser-filer but the project seems deprecated and pdf upload does not … -
Serving Django and React from a single Docker container
I have build a web app using Django backend (Django REST Framework) and React Frontend. However, the two apps aren't separate, the Django backend is serving he React frontend directly through URL routing. For that reason, if I want to dockerize the app, I can't put the frontend and backend into separate containers. The reason I want to keep the two apps integrated like this is because one small part of the frontend is being served by Django because I want to use Django's easy-to-use user authentication models instead of doing all of that on the frontend. I know this is bad practice, but is it possible to get both the required dependencies for the frontend and backend and then run both in one docker container, and if so how would I go about doing it? (I have done research on this and have only found resources on serving Django and React from two separate containers). -
Django annotate + SUM how to get all entries
My models class Machine(models.Model): machineName = models.CharField(verbose_name="Machine Name", max_length=20, blank=False, null=False) class SalesReport(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE, null=False, blank=False) deviceDate = models.CharField(max_length=200, null=True, blank=True) serverDate = models.DateTimeField(auto_now_add=True) I have 3 machines, I wanted to get the total sales from each machines for the last 7 days. my query is from django.db.models import Sum, Value as V from django.db.models.functions import Coalesce SalesReport.objects.values("serverDate__date", "machine__machineName").annotate( ... sales=Coalesce(Sum("totalPrice"),V(0))).filter( ... serverDate__gte=week_start, ... serverDate__lte=week_end) Which gives the following result, [{'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__1', 'sales': 15.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__1', 'sales': 145.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__2', 'sales': 270.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__3', 'sales': 255.0}] What i am trying to get is [{'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__1', 'sales': 15.0}, {'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__2', 'sales': 0.0}, {'serverDate__date': datetime.date(2020, 7, 22), 'machine__machineName': 'machine__3', 'sales': 0.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__1', 'sales': 145.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__2', 'sales': 270.0}, {'serverDate__date': datetime.date(2020, 7, 28), 'machine__machineName': 'machine__3', 'sales': 255.0}] I am trying to do it with Coalesce, but i'm getting it wrong . *I'm using mysql as back end. a db specific query is also fine . -
How can I update a specific key on a HStoreField in django?
I have a Django model with a HStoreField and I'm trying to update a specific key on the data in this field. I'm trying not to load the model into memory as there's a fair bit of data and it would be for a lot of object instances. I have my Result object which has 'data' field and I'm trying to update an 'existingkey', I've tried: Result.objects.update(data__existingkey='new_value') But I just get FieldDoesNotExist: ResultsContainer has no field named 'data__existingkey' I thought this would work as Result.objects.filter(data__existingkey='value') works fine. Any suggestions would be appreciated many thanks -
Is Casbin a better choice to create CRUD Users in Django/Pymongo?
I'm using a MongoDb database and I would like to use PyCasbin to manage the permissions of every routing for each user,Is there a better plan than Casbin to create a CRUD dashboard? If not, how to create simple CRUD users with PyCasbin in Pymongo and Django? I pasted PyCasbin sample in mongoengine as below: # adapter.py import casbin from casbin import persist from mongoengine import Document from mongoengine import connect from mongoengine.fields import IntField, StringField class CasbinRule(Document): ''' CasbinRule model ''' __tablename__ = "casbin_rule" ptype = StringField(required=True, max_length=255) v0 = StringField(max_length=255) v1 = StringField(max_length=255) v2 = StringField(max_length=255) v3 = StringField(max_length=255) def __str__(self): text = self.ptype if self.v0: text = text+', '+self.v0 if self.v1: text = text+', '+self.v1 if self.v2: text = text+', '+self.v2 if self.v3: text = text+', '+self.v3 return text meta = { 'indexes': [ {'fields': ('ptype', 'v0', 'v1', 'v2'), 'unique': True} ] } def __repr__(self): return '<CasbinRule :"{}">'.format(str(self)) class Adapter(persist.Adapter): """the interface for Casbin adapters.""" def __init__(self,dbname,host): connect(db=dbname,host=host) def load_policy(self, model): ''' implementing add Interface for casbin \n load all policy rules from mongodb \n ''' lines = CasbinRule.objects() for line in lines: persist.load_policy_line(str(line),model) # c_middleware.py class CMiddleware: """ Cmiddleware. """ def __init__(self, get_response): self.get_response = get_response … -
How to handle django returning Nonetype has no len()
I'm getting this Nonetype error. I'm stuck at it all day. First i was getting MultiDictError after changing it to filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') It seems to work and now this error. views.py: def add(request): filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') return render(request, "add/add.html"),{ "entries":util.save_entry(filetitle,contentitle) } utills.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) add.html {% block body %} <h1>Create New Page</h1> <form action="encyclopedia:add" method="post"> {%csrf_token%} <input name="bob" type="text" placeholder="Enter the Markdown content " id="abz"> <textarea name="pop" rows="20" cols="25" value="content"></textarea> <input type="submit" value="submit" /> </form> {% endblock %} error: Internal Server Error: /add Traceback (most recent call last): File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/knox/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/knox/django/wiki/encyclopedia/views.py", line 44, in add "entries":util.save_entry(filetitle,contentitle) File "/home/knox/django/wiki/encyclopedia/util.py", line 28, in save_entry default_storage.save(filename, ContentFile(content)) File "/home/knox/.local/lib/python3.8/site-packages/django/core/files/base.py", line 128, in __init__ self.size = len(content) TypeError: object of type 'NoneType' has no len() I tried several things but none of them seems … -
rendering different buttons dynamically in the same page based on different unique conditions django
I am working on an education project that needs to get different buttons to display based on a certain status and a unit code tied to it. In my HTML view, it has multiple education topics for the user to click on "Start" to learn on the particular topic and it would change to "Continue" after they have started. The "Start" would have a "Completed" status tied to it, and for "Continue" it has a "Progressing" status. Each education topics have their own unique unit code such as "UTLP1", "UTLP2", "FXUCP1". Each of it is a unique entity on their own, therefore both status and unique code must be true or false for it to change its state, as all of the records that the user-generated are stored under a single table. HTML view of it {% if check_lesson_lec_progress %} <input type="text" name="lesson_topic_uc" value="UTLP1" hidden/> <button type="submit" class="btn btn-outline-salmon w-25" name="lesson_form_submit" value="progressing_uc_ut">Continue</button> {% else %} <input type="text" name="lesson_topic_uc" value="UTLP1" hidden/> <button type="submit" class="btn btn-outline-salmon w-25" name="lesson_form_submit" value="start_uc_ut">Start</button> {% endif %} Things that I have tried: I tried working with for loops within the template itself, however, when I loop through the records in my table "Lesson_Record" it will return the … -
django caching with pagination in django rest framework
i have a simple api with a simple caching mechanism for testing and learning caching in django, views.py class PlaceListApi(APIView): """ for getting all places """ pagination_class = PaginationWithoutCount() def get(self, request): place_type = "tourist" place_type_fa = "گردشگری" try: # self.pagination_class.page_size =2 query = (Q(place_type=place_type) | Q(place_type_fa=place_type_fa) | Q(place_type_en=place_type)) cache_key = "placeslist_cache" page = cache.get(cache_key) if page is None: print("no cache found for this view get") data = Places.objects.filter(query).only('id', 'name', 'picture') page = self.pagination_class.paginate_queryset(data, request) serialized_page = CityPlacesSerializers(page, many=True) cache.set(cache_key, serialized_page, 60 * 15) return self.pagination_class.get_paginated_data(serialized_page.data) print("after drf") return self.pagination_class.get_paginated_data(page.data) CityPlacesSerializers: class CityPlacesSerializers(ModelSerializer): # placethumbnail = serializers.ImageField(source = "picture") class Meta: model = Places fields = ('id', 'picture', 'name') and PaginationWithoutCount: class PaginationWithoutCount(PageNumberPagination): def get_paginated_data(self, data, error=None): return self.get_paginated_response(data, error) def get_paginated_response(self, data, error=None): return Response(OrderedDict([ ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data), ('error', error) ])) when i first start server with runserver command, there is no problem and everything work as expected, but when i kill the server and restart it, server raise below exception: 'PaginationWithoutCount' object has no attribute 'page' and this comes from else part where **if page is None: ** is False, what is the problem? because of the exception text i think it is not from … -
Creating a webform using Django that queries my own API, how can I protect it?
I am creating a website where there is no user authentication, anyone can use this website. However, there is a form on this website that users will fill out and submit, it will then query an API in Django and return the data. I am very new at Django, so my understanding is if I program it like a normal form, then anyone can go to Developer Console in their browser and monitor the network traffic and see my API request and therefore can just use the API link themselves without needing to use my website at all. This API is to populate data for my own website only, is there anyway I can protect this? In other words, just allow my website to be able to use this api and deny/reject any other request from any other domain? -
how to add button value to django form field when button pressed
i have a django form with fields name, mobile and token. In html form i have buttons of number and i need to add the value of the button to the django forms token field when the number button is clicked. -
Django Import Export, how to import specific sheet in excel?
What is the correct way to import specific sheet of excel by using Django-Import-Export Module?? or if possible. all the sheets in a workbook one by one... I referred their documentation and it was not much helpful https://django-import-export.readthedocs.io/en/latest/ the same way I would like to export data into multiple sheets in one workbook... how do achieve it?? -
__init__() takes 1 positional argument but 2 were given django email activation
please help so solve my problem, when i open the activation link in email, then it will show init() takes 1 positional argument but 2 were given, help this is my signup views def signup(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) profile = profile_form.save(commit=False) user.is_active = False user.save() profile.save() uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link=reverse('activate', kwargs={ 'uidb64': uidb64, 'token': token_generator.make_token(user)}) activate_url = 'http://'+domain+link email_body = 'Hallo '+user.username + 'Tolong gunakan link ini untuk verifikasi akun anda\n' +activate_url email_subject = 'Aktivasi Akun Anda' email = EmailMessage( email_subject, email_body, 'noreply@kantorkecamatanbintanutara.com', [profile.email], ) email.send(fail_silently=False) return redirect('/pengurusan/signin') else: return render(request, 'pengurusan/register.html', { 'user_form': user_form, 'profile_form': profile_form }) this is my verification view class VerificationView(View): def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) if not token_generator.check_token(self, user, token): return redirect('pengurusan/signup'+'?message'+'User already activated') if user.is_active: return redirect('pengurusan/signin') user.is_active = True user.save() messages.success(request, 'Account activated successfully') return redirect('pengurusan/signup') except Exception as ex: pass return redirect('pengurusan/signin') this is my utils.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() -
how to upload profile image to user_auth seperately using OnetoOneField() in python django?
CAMROID |--accounts_app | |--admin.py | |--models.py | |--urls.py | |--views.py | |--camroid_app | |--admin.py | |--models.py | |--urls.py | |--views.py | |--camroid_project | |--settings.py | |--urls.py | |--media | |--ProfileImg | |--static | |--css | |--js | |--fonts | |--images | |--templates |--base.html |--category.html |--index.html |--myspace.html |--register.html I have a sign up form from where a user can register and his details is uploaded to user_auth table and in addition to that there is another model UserProfile which contains profile_img = Imagefield() has a OnetoOneField relation to user_auth table and a user can only upload his profile image when he sign in. So a user is not uploading image while he register and can only upload profile image from myspace.html. accounts_app handles all accounts related functionality like register and sign in and camroid_app handles the actual content of the site [index.html, myspace.html] here is myspace.html page. As you can see i'm using two seperate form one for uploading profile pic and another for updating details of user form for updating details will be an easy task but for uploading profile pic while working with OnetoOneField is where i need help. As i don't know how it works. I have already …