Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: render multiple sections
I was struggling to come up with a more correct title for this question, so if anyone has a suggestion after I describe my problem I'll gladly update it. I'm using Django to create my pages(with python in backend). One of such pages has 4 tabs in it. Some tabs require longer backend processing, but I don't want the page to wait for each tab, instead I want each tab to be displayed as soon as it is ready. So far I used rest api for each tab and then created the whole tab in js. But I like using Django templates much better. Is there a way to have to it so that I can still create each tab in Django templates? <div class="tab-content"> <div id="tab1" class="tab-pane fade in active"> {% include 'my_project/tab1.html' %} </div> <div id="tab2" class="tab-pane fade"> {% include 'my_project/tab2.html' %} </div> <div id="tab3" class="tab-pane fade"> {% include 'my_project/tab3.html'%} </div> <div id="tab4" class="tab-pane fade"> {% include 'my_project/tab4.html'%} </div> I have single URL, I want this URL to invoke 4 backend views handler to render each of the tab htmls. -
Django Fullcalendar modal
I'm building fullcalendar that will manage events in my django app. The problem that I'm facing here is that modal is opened on dayClick event, but when fields are filled and submit button is clicked nothinh happens (modal is not closed and event is not added, when I opend the modal for the second time then the data is already filled with what I've previously typed and new event is added). I'm using this js code: var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: [ {% for event in events %} { title: "{{ event.patient }}", start: '{{ event.start|date:"Y-m-d h:m" }}', end: '{{ event.end|date:"Y-m-d h:m" }}', type: "{{ event.type }}", notes: "{{ event.notes }}", id: '{{ event.id }}', }, {% endfor %} ], selectable: true, selectHelper: true, editable: true, eventLimit: true, dayClick: function (start, end, allDay) { $("#modal-visit").modal("show"); var title = document.getElementById("patient").value; var start = document.getElementById("start").value; var end = document.getElementById("end").value; var type = document.getElementById("type").value; var notes = document.getElementById("desc").value; $.ajax({ type: "GET", url: '/add_event', data: {'title': title, 'start': start, 'end': end, 'type': type, 'notes': notes}, success: function (data) { $('#calendar').fullCalendar('renderEvent', {'title': title, 'start': start, 'end': end, 'type': type, 'notes': notes}); alert("Added Successfully"); }, failure: … -
Django models design for booking system
I have started recently some playing with Django and databases to get more familiar with this. I have some understanding o the subject, but I am unsure of one design choice I've made and I'd appreciate any comments/suggestions on that. My idea is to write simple app that will allow to book conference venues. Those can be either hotels or some stand alone conference rooms. In the hotel there is a chance that there are also rooms for sleeping and might also be restaurant/catering capability on-site. Moreover, one hotel or conference facility can have multiple conference rooms of different sizes. My current models design is following: class Service(models.Model): Name = models.CharField(max_length = 255) Address = models.CharField(max_length = 255) City = models.CharField(max_length = 100) PostalCode = models.CharField(max_length = 10) Country = models.CharField(max_length = 100) TelephoneNumber = models.CharField(max_length = 20) Website = models.CharField(max_length = 100) Email = models.CharField(max_length = 100) Description = models.TextField() def __str__(self): return self.Name class Catering(Service): MaxMeals = models.IntegerField() class Venue(Service): Catering = models.ForeignKey(Catering, on_delete = models.SET_NULL, blank = True, null = True) ProvidesSleeping = models.BooleanField() class RoomT(models.Model): Venue = models.ForeignKey(Venue, on_delete = models.CASCADE) OccupancyLimit = models.IntegerField() class HotelRoom(RoomT): RoomType = models.IntegerField() class ConferenceRoom(RoomT): HasProjector = models.BooleanField() I am … -
Pass value from loop to HTML - Django
My algorithm compares uploaded document with other documents and writes to output report like 'x part of uploaded document found in y document' and so on. Now I want to pass these reports to my HTML template but don't know how can assign value in for loop to some variable. Here is some part of my code: views.py: for each_file in files: other_docs = open(each_file, 'r') other_docs_words = other_docs.read().lower().split() for i in range(len(other_docs_words) - 4): for j in range(len(other_docs_words)+1): if(j-i == 5): each_five_others = other_docs_words[i:j] for original_each_five in iterate(): if(original_each_five == each_five_others): found_count += 1 # This is the part that I want to output on HTML page. report.write('{} part of document found in {} document. \n'.format( original_each_five, each_file)) else: pass else: pass -
Use python requests to login and upload a file on a django site. csrf token error
I have a django website where login in is required to upload a file. The file is part of a model form field. Both login (auth) and file upload work well when running straight from the browser. However when using python requests, only login works and upload fails with a crsf error. Below are code samples. forms.py class DatabaseUploadForm(forms.ModelForm): class Meta: model = Profile fields = ["dbfile"] upload.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Upload Database</legend> {{ p_form}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> login_and_upload_script.py user = "user1" password="passwrd1" url_login='http://127.0.0.1:8000/users/login/' url_upload='http://127.0.0.1:8000/users/upload/' client = requests.session() client.get(url_login) csrftoken = client.cookies['csrftoken'] files={'dbfile':('files.db', open('file.db', 'rb'))} login_data = {'username':user,'password':password, 'csrfmiddlewaretoken':csrftoken, 'next': url_upload} r1=client.post(url_login,data=login_data) print(r1.status_code) print('\n=================================================================\nLogged In......\nConti') client.get(url_upload) csrftoken2 = client.cookies['csrftoken'] files={'dbfile':('MARKSDB.db', open('MARKSDB.db', 'rb')), 'csrfmiddlewaretoken':csrftoken2} r=requests.post(url_upload, files = files, headers=dict(Referer=url_upload)) print(r.status_code) print(r.text) print('\n=================================================================\nDone') The output 200 ================================================================= Logged In...... Continue 403 <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; … -
Django select a random image
I'm trying to select a random image from a given directory. I have found Random_Image on GitHub and I'm trying to use that. Here's a snippet of the instructions: Snippet of Instructions I'm relatively new to Django so this might seem like a silly question, but what am I doing wrong here? When I run the code below I get the following error: FileNotFoundError at / [WinError 3] The system cannot find the path specified: 'app_pickfeel/static/app_pickfeel/app_pickfeel/images/9.jpg' Random_Image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # template tags 'app_pickfeel.templatetags.random_Image' ] MEDIA_ROOT = 'app_pickfeel/static/app_pickfeel/' RANDOM_IMAGE_DIR = '/images/' RANDOM_IMAGE_EXTENSIONS = ['.jpg','.jpeg','.png','.gif'] MEDIA_URL = '/images/' img src <img src="{{ MEDIA_URL}}{% random_image "app_pickfeel/images/" %}"> Images are located in the directory: Pickfeel/app_pickfeel/static/aoo_pickfeel/images Any help would be greatly appreciated. -
How to use an object from outer scope in Django API handler
TL;DR: I run a Django server with a TCP socket connection. I need to inject the TCP connection instance to the REST api handlers, in order to make actions. I can't figure out HOW to share memory between the Django and my other code. I am working on a REST Django server. In urls.py i defined do_something api handler: urlpatterns = [ path('admin/', admin.site.urls), path('something/', do_something) ] in manage.py: To simplify, I used name instead of tcp_connection and its logic. name = None @api_view(["GET"]) def do_something(request): print("name", name) # prints None. Expected {"value": "lala"} return Response(None, status.HTTP_200_OK) def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') global name name = { "value": "lala" } execute_from_command_line(sys.argv) if __name__ == '__main__': print(f'Initiating') main() Thoughts As I am new to python, that might be silly. It looks like it's running in another process and therefor no shared memory. If thats correct, how can i inject the object instance the handler needs? Thanks! -
Do not allow the user administrator without deleting in django
Good evening dear ... I am inexperienced in django, I wanted to have a way to prevent the admin user from deleting himself in the admin.py file, how should the code be to prevent this? I thank you in advance for your helpful attention. -
GraphQL Mutation in Graphene for Object with Foreign Key Relation
I'm building a simple CRUD interface with Python, GraphQL (graphene-django) and Django. The CREATE mutation for an Object (Ingredient) that includes Foreign Key relations to another Object (Category) won't work. I want to give GraphQL the id of the CategoryObject and not a whole category instance. Then in the backend it should draw the relation to the Category object. In the Django model the Ingredient Object contains an instance of the Foreign key Category Object (see code below). Is the whole Category Object needed here to draw the relation and to use Ingredient.objects.select_related('category').all()? The create mutation expects IngredientInput that includes all properties and an integer field for the foreign key relation. So the graphQL mutation itself currently works as I want it to. My question is similar if not the same as this one but these answers don't help me. models.py: class Category(models.Model): name = models.CharField(max_length=50, unique=True) notes = models.TextField() class Meta: verbose_name = u"Category" verbose_name_plural = u"Categories" ordering = ("id",) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: verbose_name = u"Ingredient" verbose_name_plural = u"Ingredients" ordering = ("id",) def __str__(self): return self.name schema.py: class CategoryType(DjangoObjectType): class Meta: model = Category … -
Does a Django Application that uses REST framework need a model?
I built an application that uses REST apis to inject information into a huge already existing database for a company. The application is a web form that the user fills out. My application then serializes the user's responses into a json that it uses to send post requests to the existent db. My Django app also is connected to a SQL Server db where it is saving the responses of the user into the fields that I created in my models.py. Is there a better way to do this? It seems like I'm saving all the information twice! A waste of space. -
Tutorial Django Documentation part 1. Requests and responses
I'm going through the django documentation tutorial and i've hit a wall pretty early. The rundown is i'm trying to set up a simple server with django then dev a polls taking app. I've followed the steps in detail (as far as I can tell) and i'm unable to complete the last part. Opening the link bellow to see a print out of the polls/views.py code. Any help will be appreciated by this confused newbie. Thank you much. I'm unable to access the link provided to check if my code is working.this is the link This is my current tree; mysite ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── settings.cpython-37.pyc │ ├── urls.cpython-37.pyc │ └── wsgi.cpython-37.pyc ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py This is my polls/urls.py; from django.conf.urls import url from . import views urlspatterns = [ path('', views.index, name='index'), ] This error comes up when I run it; Traceback (most recent call last): File "/Users/trevorhegarty/my_code/code.acad/tutorialDJ/mysite/polls/urls.py", line 2, in <module> from . import views ImportError: attempted relative import with no known parent package This is mysite/urls.py; from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] Which throws this at … -
save() method in forms.py unable to save the foreignkey in Django
i am trying to save the current user in forms.py using save() method can you please help me to solve this problem here is my models.py models.py class Warden(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) firstName = models.CharField(max_length=30,null=True) lastName = models.CharField(max_length=30,null=True) email = models.EmailField(null=True) phone_number = models.CharField(max_length=12 ,null=True) hostel_name=models.CharField(max_length=20,null=True) profile_image = models.ImageField(default="logo-2.png",upload_to='users/', null=True, blank=True ) def __str__(self): return self.email class HostelStaff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) firstName = models.CharField(max_length=30,null=True) lastName = models.CharField(max_length=30,null=True) email = models.EmailField(null=True) phone_number = models.CharField(max_length=12 ,null=True) hostel_name=models.CharField(max_length=100) #this is forignkey in which i want to save logged user warden = models.ForeignKey(Warden, on_delete=models.CASCADE) profile_image = models.ImageField(default="logo-2.png",upload_to='users/', null=True, blank=True ) def __str__(self): return self.firstName + ' ' + self.lastName this is my forms.py wher i overide save method forms.py class StaffSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('username',) def save(self): user = super().save(commit=False) user.is_hostelstaff = True user.save() return user def __init__(self, *args, **kwargs): super(StaffSignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['placeholder'] = ' username' self.fields['password1'].widget.attrs['placeholder'] = ' password' self.fields['password2'].widget.attrs['placeholder'] = ' confirm password' self.helper = FormHelper() self.helper.form_show_labels = False for fieldname in ['username','password1', 'password2']: self.fields[fieldname].help_text = None class StaffSignUpTwo(forms.ModelForm): class Meta: model = HostelStaff fields = ('firstName', 'lastName','email', 'phone_number', 'hostel_name',) def __init__(self, user, *args, **kwargs): super(StaffSignUpTwo, self).__init__(*args, **kwargs) self.fields['firstName'].widget.attrs['placeholder'] = ' first name' … -
Django. What is wrong ith this regex
I have a form for which the relevant model is keyed on a UUID models.py class FoodDiaryItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... urls.py urlpatterns = [ url(r'food-diary-entry/', views.food_diary_entry, name='food-diary-entry'), url(r'food-diary-entry/(?P<id>[0-9A-Fa-f-]+)', views.food_diary_entry, name='food-diary-entry'), ... views.py def food_diary_entry(request, id=None): print('food_diary_entry') if id: food_diary_item, created = FoodDiaryItem.objects.get_or_create(id=id) else: food_diary_item = FoodDiaryItem() ... As it stands, this code runs and the calls the function food_diary_entry in views.py However, if I comment out the first line of the urlpatterns list, it will not enter "views.py* suggesting it does not match the UUID portion of the regex. What is wrong here? -
Using 'or' operator in views.py django
i want to print different items from a different query sets on a same page but i get error or sometimes first if runs while other don't.... def product_detail(request, id): wt = womentrouser.objects.filter(post_id=id)[0] ws = womenshirt.objects.filter(post_id=id)[0] mt = mentrouser.objects.filter(post_id=id)[0] na = newarrival.objects.filter(post_id=id)[0] eq = equipment.objects.filter(post_id=id)[0] if(wt==True): print("this is wt", wt) return render(request, "mart/view-product.html", {'t': wt}) if(ws==True): print("this is ws", ws) return render(request, "mart/view-product.html", {'t': ws}) All i am doing is that if an item from wt is clicked mart/view-product.html prints that item and when any item from ws is clicked then it is printed.....can i do this in django like this? -
Adding an item to many to many after creation in django
Recently I've been trying to do something with this. Think of the family as a facebook group. class Family(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owned_families') users = models.ManyToManyField(User, related_name='families', blank=True) let's assume we have this a family object called fm, for illustration purpose. My problem is, The owner is one of the users right? I mean, When someone creates a family, He's now the owner right? he owns it but he's still a user listed in it's users list. Now, when I create a new family fm , I want to add the fm.owner to fm.users. Let's talk about what I've tried. post_save signal doesn't work with m2m. X m2m_changed happens when the field is changed, not created. X Overriding save method, lemme illustrate what I tried to acheive. ? def save(self, *args, **kwargs): old = self.pk super(Family, self).save(*args, **kwargs) if old is None: print('This actually shows up') self.users.add(self.owner) Basically, this saves the pk each time, First time a family is created, Before calling super..... it has no .pk so I'm counting on this to check if it had no pk (On creation). The problem is self.users.add(self.owner) doesn't work. I've tried to clone the object as whole and … -
django "Invalid pk \"1\" - object does not exist." whether id exist
class ReturnItemsSerializer(serializers.ModelSerializer): returns = serializers.PrimaryKeyRelatedField(queryset=ReturnItems.objects.all()) returnreasons = serializers.PrimaryKeyRelatedField(queryset=ReturnReasons.objects.all()) class Meta: model = ReturnItems fields = [ "id", "updated_at", "returns", "returnreasons" ] depth = 1 class ReturnItems(models.Model): updated_at = models.CharField(max_length=256, null=True, blank=True) returns = models.ForeignKey(Returns,on_delete=models.CASCADE, related_name='returnitems', null=True, blank=True) returnreasons = models.ForeignKey(ReturnReasons,on_delete=models.CASCADE, related_name='returnitems', null=True, blank=True) { "returnreasons": 1, "returns": 1 } { "returns": [ "Invalid pk \"1\" - object does not exist." ], "returnreasons": [ "Invalid pk \"1\" - object does not exist." ] } Hi, here i am trying to create data in django using swagger post method. Sharing above how i am sending the data. There is id with 1 in both returnreasons and returns model but, stil it is giving me response like object does not exist. Please have a look Where i am missing. -
I am unable to migrate in my django project
I have connected my django project with mysql database and i have configured all my settings(settings.py), but when migrate ,it shows the error.enter image description here -
How to change default admin search from Pages - Wagtail
By default wagtail admin searches Pages. I would like to change the default search. I believe I need to use the 'current' param in wagtailadmin_tags, but I am unsure how to do this. The wagtail docs state on https://docs.wagtail.io/en/v2.8/reference/hooks.html#construct-main-menu: A template tag, search_other is provided by the wagtailadmin_tags template module. This tag takes a single, optional parameter, current, which allows you to specify the name of the search option currently active. If the parameter is not given, the hook defaults to a reverse lookup of the page’s URL for comparison against the url parameter. However I am stuck with how to get started on this. -
Djoser user_list setting AllowAny not working
I have created login Api using Djoser for authentication. I want to get the list of users using a GET api call (/api/auth/users/ endpoint) but I get an error saying "detail": "Authentication credentials were not provided." I have added djoser settings in setting.py file like this DJOSER={ 'user': ['djoser.permissions.AllowAny'], 'user_list': ['djoser.permissions.AllowAny'], 'SERIALIZERS':{ 'user_create':'restapi_subserv.serializers.UserCreateSerializer', 'user':'restapi_subserv.serializers.UserCreateSerializer', } } But Still, I get the error. Am I missing something? Please let me know if you need any more details. -
Heroku how to update git remotes after project rename
I already renamed my project to PROJECT_NAME on Heroku and should I update project git remotes, This is Heroku guide: $ git remote rm heroku $ heroku git:remote -a PROJECT_NAME But when I run the first command, I'm getting this error: fatal: No such remote: heroku -
ModuleNotFoundError: No module named 'oscar.apps.dashboard.partnersoscar' in Django Oscar
I am setting up Oscar Django and getting the following error ModuleNotFoundError: No module named 'oscar.apps.dashboard.partnersoscar' in Django Oscar. -
How should I do when conf folder doesn't have global_setteings.py
When I launch a Django project in a local server, It doesn't work with the errors below, and then, I checked the directory of conf(/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf) and found that global_settings.py doesn't exist in that directory. in that case, how should I do? do I have to make the global_settings.py my self in there with this code? or will I be able to solve another way? Would you mind telling me how should I solve this problem? Thank you in advance. error code Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 11, in <module> from django.conf import settings File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 17, in <module> from django.conf import global_settings ImportError: cannot import name 'global_settings' from 'django.conf' (/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Python Console import sys; ... ...print(sys.path) ['/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/third_party/thriftpy', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages', '/Users/apple/GoogleDrive/project_django'] -
Is this a correct class-based-django-view?
In my project i have a page that displays a form where the User inputs some irrelevant(for the moment project name) and a host/ip-address. When he hits the scan button he makes a post request. In the current moment i get that ip address and im trying to 'banner-grab' the running services on that ip/host and render the results to the page. In the code below i got that working but as im litteraly using django for the first time i think that my aproach is really bad cause all of my code( for grabbing the banner etc ) is in the POST function in my class-based-view.So question is can i do this in a better way? Maybe write that bannerGrab() function somewere else and, if form is valid just call the function in the POST method... class NewProject(View): # Reusable across functions form_class = ProjectData template_name = 'projectRelated/create_project.html' ports = [20, 21, 22, 23, 80, 3306] def get(self, request): # redundant to use it like this # form = ProjectData() form = self.form_class context = { 'form': form # this is a context variable that i can use in my html page. like this <h3> {{ context.var }} </h3> … -
Three.js modal popup on model click
I'm trying to add onclick event to my model displayed using THREE.js. Here is how I'm loading the model. var ww = 600; wh = 400; function init(){ var three = THREE; renderer = new THREE.WebGLRenderer({canvas : document.getElementById('scene')}); renderer.setSize(ww,wh); renderer.setClearColor( 0xffffff, 1 ); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(50,ww/wh, 0.1, 10000 ); camera.position.set(0,0,500); scene.add(camera); controls = new THREE.OrbitControls (camera, renderer.domElement); controls.minAzimuthAngle = -1; // radians controls.maxAzimuthAngle = 1; // radians controls.minPolarAngle = 1.5; // radians controls.maxPolarAngle = 1.5; // radians //Add a light in the scene const skyColor = 0x00000 // light blue const groundColor = 0xFFFFFF; // brownish orange const intensity = 1; const light = new THREE.HemisphereLight(skyColor, groundColor, intensity); scene.add( light ); //Load the obj file loadOBJ(); } var loadOBJ = function(){ //Manager from ThreeJs to track a loader and its status var manager = new THREE.LoadingManager(); //Loader for Obj from Three.js var loader = new THREE.OBJLoader( manager ); //Launch loading of the obj file, addBananaInScene is the callback when it's ready loader.load( "static/pictures/3D/jaw.obj", addModelInScene); }; var addModelInScene = function(object){ model = object; //Move the banana in the scene model.rotation.x = Math.PI; model.scale.x = 2000; model.scale.y = 2000; model.scale.z = 2000; scene.add(model); render(); }; var render … -
Django User profile model form edit for current user
I have searched a lot on this and all the questions and answers provided are never clear and fit for purpose, maybe I'm going at it the wrong way. I have just recently started Python and Django, so know very little about it. I am creating a website and have done the basic authentication using Django and even added the facebook authentication using social-django. That part all works fine. Now I am moving to profile information and how to update it after you sign up to website. I have the below UserProfile in models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.TextField() last_name = models.TextField() email_address = models.EmailField() phone_number = models.TextField() In forms.py a testing form: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name','last_name','email_address'] Then in views.py I have a function: def myprofile(request): if request.method == 'POST': form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() user_profile = UserProfile.objects.get(user=request.user) if request.method == 'GET': user_profile = UserProfile.objects.get(user=request.user) form = UserProfileForm(instance=user_profile) return render(request, 'pandp/myprofile.html', {'user_profile' : user_profile, 'form' : form}) And finally myprofile.html: <div class="profile-details"> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> </div> I was struggling from the start to actually only load UserProfile of the logged …