Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting numpy image to PIL image giving strange result
Actually, I need to save PIL image to django that's why i am converting numpy image to pillow image but it's giving me the strange image. from cv2 import cv2 import numpy as np import urllib.request from PIL import Image url = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Deepika_Padukone_at_Tamasha_event.jpg/220px-Deepika_Padukone_at_Tamasha_event.jpg" resp = urllib.request.urlopen(url) img77 = np.asarray(bytearray(resp.read()), dtype="uint8") img77 = cv2.imdecode(img77, cv2.IMREAD_COLOR) ''' join image ''' im_h = cv2.hconcat([img77, img77]) ''' resize image ''' print('Original Dimensions : ',im_h.shape) width = 1108 #554 #1108 height = 584 #292 #584 dim = (width, height) resized = cv2.resize(im_h, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) ''' put similarity level ''' img1 = resized img2 = cv2.imread('percentage_images\\15.png') # it's percentage image(.png) rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) img2_fg = cv2.bitwise_and(img2,img2,mask = mask) dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst nadu = Image.fromarray(img1,"RGB") print(nadu) nadu.save("what.jpg") # Image.fromarray(img1).convert("RGB").save("what2.jpg") cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows() # cv2.imwrite('full_edit.jpg', img1) Image convert from this -> real image to this-> converted image I am new to Pillow so any help will be appreciated. Thanks Sir/Mam. -
Why is div inside of the other div?
I have the following django template code. The main-card-faq div is clearly not in the main-card div however it keeps getting rendered inside of the main-card div. Any idea what could be going on? {% extends 'base.html' %} {% block content %} <div class="main-card"> {% if heading_info %} {% for heading in heading_info %} {% include 'partials/_heading.html' %} {% endfor %} {% endif %} {% if welcome_info %} {% for welcome in welcome_info%} {% include 'partials/_welcome.html' %} {% endfor %} {% endif %} {% comment %} {% if skills_info %} {% for skill in skills_info%} {% include 'partials/_skills.html' %} {% endfor %} {% endif %} {% endcomment %} </div> <div class="main-card-faq"> {% include 'partials/_faq.html' %} </div> test {% endblock %} -
Django model returns None in AppConfig
I am trying to fetch values from mysql database using django model inside an appconfig subclass but I keep getting None. class myappConfig(AppConfig): name = 'myapp' def ready(self): from .models import myModel mydata = myModel.objects.values('A') Even though there is data in the mysql table corresponding to myModel, the value in mydata is None. What could be the reason for this ? -
Django User inheritance
I am building a food ordering website with Django. I want my users to register an account on my site, and they should sign in to actually order. I want to use the User class built in with Django, but that doesn't include necessary fields like address, confirmation ID, and phone number. If I build a custom User model, that doesn't have many good helper functions which I can use like auth.authenticate. I searched this topic, and I found that I could use AbstractUser. But when I inherited my CustomUser class from AbstractUser, some strange things began to happen. After some more research, I found out that changing the User model after applying my built-in migrations give some errors as there are some relationships or something. I deleted my database and created a new one. Now, I am extending my CustomUser class from the built-in User class. This works fine, only you can't do auth.authenticate checking with the, confirmation ID for instance. Also, it seems to create two models every time I create a new CustomUser, the other on in the Users under the auth tab. Can you tell me any good way to connect the User model with a … -
Change URL and content without refreshing django
I am fetching a json response from my django response by this url /inbox/<str:username> to get a json response of all the messages in the conversation with that user. The problem starts with the inbox page which holds the threads and chatbox on the same page like instagram which looks like this but as it can be seen that I want the url to be like with the username. Let's say when I click on thread with dummy I want the url to be like "inbox/dummy" but in this my url is "/inbox" which will not let me initiate the socket for messaging, my views.py that renders this inbox template is views for inbox thread_objs= Thread.objects.by_user(user=request.user) l=len(thread_objs) chat_objs=[] for i in range(l): chat_objs.append(list(thread_objs[i].chatmessage_set.all()).pop()) chat_objs_serialized=[] for i in range(l): chat_objs_serialized.append(json.dumps(ChatMessageSerializer(chat_objs[i]).data)) for i in range(l): print(chat_objs_serialized[i]) thread_objs_list=[] for i in range(l): thread_objs_list.append(json.dumps(ThreadSerializer(thread_objs[i]).data)) return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized}) now when I click a thread it's content should load on the right side of screen as with the javascript of inbox.html that is this page in this image. javascript of inbox <body> <div class='container'> <div class='row'> <div class="col-md-4" id ="Threadholder"> <ul id ="Threadbox"> {% for object in threads %} <li><a href=" ">{% if user != object.first %}{{ … -
how to save migration for dependency in django in git repo
According to the django documentation, I should only be running the makemigrations command on my local computer, and then when it comes time to production, I should be saving the migrations to the repo and then just running migrate with the migrations already made. This makes sense to me but I am unsure how to do this for the migrations that are created for any pip module that I use for the django site? in one of the migrations that I would save to the repo, there is a dependency on one of the migrations for a pip module but I have no clue how to save that migration to the repo since the migration exists under the site-packages folder and I get the feeling that I am not supposed to be manually moving migrations from that folder to my repo and placing it under a migrations folder for one of the apps that exists for my website's django? -
how to add a search field in graghql/django
I am working on this project: https://github.com/mirumee/saleor I added a column to the product model by doing: account_user = models.ForeignKey( Account_User, related_name="products", on_delete= settings.AUTH_USER_MODEL, ) However, after I run "npm run build-schema" and then type query { products(first: 10) { edges { cursor node { id name description slug account_user_id } } } Graghql says ""message": "Cannot query field "account_user_id" on type "Product".",". Do I miss any step? Do I need to modify the query to add this field? Thanks -
Django server crashes once deployed
The server builds successfully. Once Its built, and I go to view it, i gives me an application error. Still new to deploying via heroku and django, so if this is obvious please be helpful! It keeps saying module not found with 'locallibrary', where I do not have a module named local library. Here is the log 2020-09-29T02:20:16.043818+00:00 app[web.1]: worker.init_process() 2020-09-29T02:20:16.043818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-09-29T02:20:16.043818+00:00 app[web.1]: self.load_wsgi() 2020-09-29T02:20:16.043819+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-09-29T02:20:16.043822+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-09-29T02:20:16.043823+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-09-29T02:20:16.043823+00:00 app[web.1]: self.callable = self.load() 2020-09-29T02:20:16.043824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-09-29T02:20:16.043824+00:00 app[web.1]: return self.load_wsgiapp() 2020-09-29T02:20:16.043824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-09-29T02:20:16.043825+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-09-29T02:20:16.043825+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-09-29T02:20:16.043826+00:00 app[web.1]: mod = importlib.import_module(module) 2020-09-29T02:20:16.043826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-09-29T02:20:16.043826+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-09-29T02:20:16.043827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-09-29T02:20:16.043827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-09-29T02:20:16.043829+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, … -
Django dynamic url path from Pandas dataframe
I'm new to Django with some fluency in Python, primarily Pandas. I'm trying to build dynamic paths for my app, such that a user pressing a button will reference my pandas dataframe, either by index or some primary key, in order to have a unique page for each row in my dataset. More specifically I'm generating a random number to select a random row from my dataframe. I understand and have read the documentation for Django's URL dispatcher but I'm only aware of setting custom paths that can be referenced in the html by the user typing in their path and not necessarily an automated version of that. Essentially what I'm trying to accomplish is to achieve a similar result to https://www.imdb.com/title/tt0111161/ with "/title/" as my app name and "/tt0111161/" as the custom path from my primary key/index/random number of my dataframe row. I've tried various versions of this method. The views.py looks like this: def all(request, id): random_number = random.randint(0,100) row = df.iloc[random_number] id = random_number return render(request, "play/all.html", { "title": row['title'], "year": row['year'], }) The urls.py looks like this: urlpatterns = [ path("all/<int:id>/", views.all, name="all"), ] I just can't figure out how to make this functional. Is it … -
Django ORM queryset to table with one field as index, using a json response
I have a Django ORM table called Measurements as below: | pk | Length | Width | Height | Weight | Date | |----|--------|-------|--------|--------|------------| | 1 | 131 | 23 | 52 | 126 | 2019-12-01 | | 2 | 136 | 22 | 64 | 125 | 2019-12-02 | | 3 | 124 | 25 | 59 | 130 | 2019-12-03 | As can be observed, Length, Width, Height, Weight & Date are all fields. I want to send a json response such that it can be used to render a table like below: +-------------+------------+------------+------------+ | Measurement | 2019-12-01 | 2019-12-02 | 2019-12-03 | +-------------+------------+------------+------------+ | Length | 131 | 136 | 124 | +-------------+------------+------------+------------+ | Width | 23 | 22 | 25 | +-------------+------------+------------+------------+ | Height | 52 | 64 | 59 | +-------------+------------+------------+------------+ | Weight | 126 | 125 | 130 | +-------------+------------+------------+------------+ To do this I will have to return a list of 4 dictionaries where each dictionary in the list will have the following keys: Measurement, 2019-12-01, 2019-12-02, 2019-12-03. Like so: >>> dicts = [ ... { "Measurement": "Length", "2019-12-01": 131, "2019-12-02": 136,"2019-12-03": 124 }, ... { "Measurement": "Width", "2019-12-01": 23, "2019-12-02": 22,"2019-12-03": 25 }, … -
Cannot get the navbar toggler to be displayed
This is my code of a django template where I need to show a navbar toggler icon when the screen is smaller than small. But when the page displayed nothing happens. Here is the code running on a ec2 instance just to show how it is working. http://ec2-54-146-137-211.compute-1.amazonaws.com/ (this will only be up temporarily) {% load static %} <!DOCTYPE html> <html> <head> <!-- CSS only --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- styles.css --> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> {% block head %}{% endblock %} </head> <body> <div class="header header-darkmode"> <div class="container"> <div class="row row-header"> <div class="col-12 col-sm-6"> {% if user.is_staff %} <h1 class="display-4">Hello world :)</h1> <p class="lead">Bienvenido Javier Camacho.</p> {% else %} <h1 class="display-4">Hello world :)</h1> <p class="lead">Bienvenido al portafolio web de Javier Camacho.</p> {% endif %} </div> </div> </div> </p> </div> <nav class="navbar navbar-darkmode navbar-expand-sm sticky-top"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#Navbar"> <span class="navbar-toggler-icon"></span> </button> <div class="container"> <div class="collapse navbar-collapse" id="Navbar"> <ul class="navbar-nav mr-auto"> <li class="nav-item"><a class="nav-link" href="{% url 'inicio' %}"></span> Inicio</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'proyectos' %}"></span> Proyectos</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'cv' %}"></span> CV</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'contacto' %}"></span> Contacto</a></li> {% if user.is_staff %}<li … -
Display list in select option Django
I have been testing to display the list from my django into html select option but it didn't display separately. I think I need to assign option value id in select option but I dont know where to start, If any expert could help Im glad for the response and thanks in advance. views.py def passdata(request): idd = request.GET.get('id') datas = list(usertypes.objects.filter( permissions__user_id=request.GET['id'] ).values_list('usertype', flat=True)) user_list = {'result':datas} return JsonResponse(user_list) Javascript ajax <script type="text/javascript"> function modal (post_id) { $.ajax({ url: '/passdata/', data: { 'id': post_id }, success: function(response){ document.getElementById('selectvalue').innerHTML = response.result $("#editmodal").modal('show'); } }); } modal select_option <div class="card-content collapse show"> <div class="card-body"> <div class="form-group"> <select multiple="multiple" size="10" class="duallistbox"> <option value="1" id="selectvalue"></option> <option value="2">Sample</option> <option value="3">Accountant</option> <option value="4">User</option> </select> </div> </div> </div> -
How is data returned from form.clean_data() ? How does Django filter the input and on what basis is the dictionary created wrt keys and values?
Add a new task: def add(request): # Check if method is POST if request.method == "POST": # Take in the data the user submitted and save it as form form = NewTaskForm(request.POST) # Check if form data is valid (server-side) if form.is_valid(): # Isolate the task from the 'cleaned' version of form data task = form.cleaned_data["task"] # Add the new task to our list of tasks tasks.append(task) # Redirect user to list of tasks return HttpResponseRedirect(reverse("tasks:index")) I have a question about the data that is returned from form.cleaned_data , I read that it is a dictionary but what keys are used in that dictionary? In the code above, it is quite clear that data is being accessed from a key called "task" but where does Django look for these keys from since it is django which returned the dictionary and they are not keys the code writer defined. -
ModuleNotFoundError: No module named 'foodncups'
I get this error when I try to open the site that I hosted on pythonanywhre ModuleNotFoundError: No module named 'foodncups' here is my Django WSGI: # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/yazedraed20/mysite/mysite/settings.py' ## and your manage.py is is at '/home/yazedraed20/mysite/manage.py' path = '/home/yazedraed20/foodncups' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE","foodncups.project.settings") import django django.setup() # #os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Django fullstack: How do I display two videos that play simultaneously using only 1 controller?
I'm a complete beginner, so excuse me if this is something naive. I have this project that I'm working on for a job. I want to make two videos (the same lengths exactly) to display next to each other with only 1 controller (pause, play, forward, etc) to control both of them at the same time. How do I go about that? -
How can I iterate over submitted django forms in a formset?
I'm trying to make a questionnaire that will be dynamic. All questions' answers are only 1 to 5. On the webpage, all looks great but when the HTML form is submitted, even the loop finishes well but it seems like only one form is being submitted (3 displayed and filled in in total). When I try to iterate over submitted forms in the formset, I can access only the last item/form from the formset. I have tried to use the zip function too but with no success. my views.py def questionnaire(request, questionnaire_id): the_questionnaire = Questionnaire.objects.get(id=questionnaire_id) related_questions = QuestionnaireQuestion.objects.filter(questionnaire__id=questionnaire_id) formset = QuestionnaireAnswerFormSet() combined = zip(related_questions, formset) form = QuestionnaireQuestionForm() if request.method == 'POST': submited_formset = QuestionnaireQuestionFormSet(request.POST) if submited_formset.is_valid(): print(submited_formset) print("ok1") for form in submited_formset: print("ok2") if form.is_valid(): obj = QuestionnaireQuestionForm() obj.option_one = form.cleaned_data['option_one'] print("ok3") print(obj.option_one) # messages.success(request, 'Hotovo') # return HttpResponseRedirect('/questionnaires') else: return render(request, 'questionnaire_1.html', {'formset': formset}) context = { "the_questionnaire": the_questionnaire, "related_questions": related_questions, "formset": formset, "combined": combined, "the_form": form, } return render(request, 'questionnaire_1.html', context) template.html <form method="POST" style="text-align: center"> {% csrf_token %} {% for question in related_questions %} <div class="col-lg-12"> <h2>{{ question.question }}</h2> </div> <div class="col-lg-12"> <h2>{{ formset }}</h2> </div> {% if forloop.last %} <button type="submit" class="btn btn-info"> Submit </button> … -
Where do I apply my client certificate for mutual TLS in a Django environment?
My application needs to send a request to get some information from another server. This server has locked down its endpoints using Mutual TLS - meaning it inherently trusts no-one unless explicitly authorised. My application has been explicitly authorised to access this server/API and I have been issued with a client certificate to send with my requests. I have successfully hit the server endpoint via Postman - sending my client certificate with the request and getting a 200 back. I would now like to make the same request inside my Django/Ember application. My problem is I can't find documentation or a library that will let me send my client certificate. https://github.com/drGrove/mtls-cli looks promising but doesn't work with Windows. All other libraries seem to be for someone hosting the API that is locked down with mutual TLS - not the consumer of the API. Is Django the correct place to be adding this certificate or does it need to be added higher up, for example in AWS? -
Use Class Field Other than ID or Slug in URL
I want to access an object by an field other then ID or Slug for Django's DetailView, like so: http://example.com/product/name My model is like so: class Product (models.Model): name = models.CharField(max_length=50, help_text="Full name") View: class ProductDetail(DetailView): model = Product URLConf: urlpatterns = [ path('product/<name>', ProductDetail.as_view(), name='product-detail'), ] I'm not sure what should go in the URLConf. Note that my templates are working and I can access the object by ID as usual: http://example.com/product/1 -
Sending Email From My Server Causes 500 Error, But In Development Is Okay
I am sending emails from my Django website. In development this works fine, however when it's ran from my production server msg.send() causes it to crash. I don't know why as all related settings are the exact same on both development and server versions (other code such as db changes, but I've isolated this other code and it's not the issue). DEFAULT_FROM_EMAIL = '####@####.####' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '####@####.####' EMAIL_HOST_PASSWORD = '####' msg = EmailMessage(subject, body, '####@####.####', [to_email]) msg.send() Thank you. -
how to get sum of every objects by queryset (object by object )
i have no expernce with 'aggregation' and 'annotate' and talk with exemple better i have this object : mediasec = MediaSec.objects.filter(date__range=[primary1, primary2], degraycomany__in=degraycompsec) if i print it after convert it to list and loop will get this dict : {'id': 5, 'degraycomany_id': 5, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 25)} {'id': 8, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 9, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 10, 'degraycomany_id': 5, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 13, 'degraycomany_id': 5, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 28)} {'id': 7, 'degraycomany_id': 6, 'nomberhisas': 2, 'date': datetime.date(2020, 9, 27)} {'id': 11, 'degraycomany_id': 6, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 6, 'degraycomany_id': 7, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 27)} {'id': 12, 'degraycomany_id': 7, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 28)} {'id': 14, 'degraycomany_id': 7, 'nomberhisas': 3, 'date': datetime.date(2020, 9, 28)} {'id': 15, 'degraycomany_id': 8, 'nomberhisas': 1, 'date': datetime.date(2020, 9, 28)} so now i want to get sum of every degraycomany_id so i use this queryset: test1 = MediaSec.objects.filter(date__range=[primary1, primary2], degraycomany__in=degraycompsec).aggregate(Sum("nomberhisas")) the rusult come : {'nomberhisas__sum': 18} i want reslt like this : {'id': 13, 'degraycomany_id': 5, 'nomberhisas': 9, 'date': datetime.date(2020, 9, 28)} {'id': 11, 'degraycomany_id': 6, 'nomberhisas': 3, 'date': datetime.date(2020, 9, … -
How to apply multiple filters on a Django template when i use django-ckeditor without error?
i am using django-ckeditor as a app_contect field in models so How to apply multiple filters on a Django template , when i add multiple filters in html page it show error in my design my code in html page : <p class="card-text" id="font_control_for_all_pages">{{ android.app_contect|truncatechars:153|safe }}</p> this photo without ( |safe ) and this with (|safe) -
Can you pull from an API and create your own Tables with Django Rest Framework?
I am very new to Django and haven't had a lot of practice with it yet. I was reading and watching videos on their framework Django Rest Framework. I was wondering with the Model Serializer how could I use an existing API and copy that information into my own database. It is just a normal Json format and has a lot of information in it. The reason I am doing this is the project we want to get away from using a 3rd party database and create our own. If this framework isn't the way to go what other ways can I do this? Thanks for any help in advance. -
Newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin
I am trying to build a user login/signup page using Django. Everything works fine except when I try to register new users by clicking on the register button, the newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin. Please help. Here's my code: urls.py-login from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] urls.py-accounts from django.urls import path from . import views urlpatterns = [ path('', views.indexView, name = "home"), path('dashboard/', views.dashboardView, name = "dashboard"), # path('login/',), path('register/',views.registerView, name = "register_url"), # path('logout,'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def indexView(request): return render(request, 'index.html') def dashboardView(request): return render(request, 'dashboard.html') def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login_url') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form':form}) index.html <!DOCTYPE html> <html> <head> <title>Petrol Pump Management System</title> </head> <body> {% block content %} <h1>User Authentication</h1> {% endblock %} </body> </html> register.html {% extends 'index.html'%} {% block content %} <h1>Create new account</h1> <form method = "POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Register</button> </form> {% endblock %} -
Transferring Django project deployed on Heroku to new computer
I have recently purchased a new computer and from now on I will be working on that computer. However, I have a relatively big project on my older computer that id like to move all files and folders from the older computer to a new computer. I have different Github branches as well as the Heroku repositories set for this project. Now, what is m best option as I want to avoid cloning my own git repository? If I simply copy and paste my files and folder can that cause issues? -
upload image in django
#`this is my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #this is urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('laxmi.urls')), ] + static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT) #This is model class Services(models.Model): title = models.CharField(max_length=250) desc = models.TextField() img = models.ImageField(upload_to='img') def __str__(self): return self.title #This is views def index(request): why_choose_uss = why_choose_us.objects.all() servicess = Services.objects.all() return render(request, 'laxmi/index.html', {'servicess': servicess, 'why_choose_uss': why_choose_uss}) #This is template {% for services in servicess %} <div class="col mb-4"> <div class="card"> <img src="{{services.img.url}}"class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{services.title}}</h5> <p class="card-text">{{services.desc}}</p> <a href="#" class="btn btn-primary">Lern More</a> </div> </div> </div> {% endfor %} #this is image upload from admin pannel but its not shwoing in template enter image description here