Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any other way to access primary key in Django other than from the url.py
I want to be able to access the Primary key(pk) for the objects of a given class , but the condition is I cant take it from the url.py I know of the method of passing pk through urls.py , which is: path('url/<int:primarykey>',views.function, name='function') but in my case I cant use it So I wanted to know if there is any other way to access it Thank you! -
get() returned more than one -- it returned 2
Error: MultipleObjectsReturned at /fill/3e730d3858fbca620b1376f72e06473b227e5658/ get() returned more than one survey_participant -- it returned 2! Request Method: GET Request URL: *secret url cant share* Django Version: 1.8.4 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one survey_participant -- it returned 2! Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in get, line 338 Python Executable: /usr/local/bin/uwsgi Python Version: 2.7.3 Python Path: ['.', '', '/usr/local/lib/python2.7/dist-packages/distribute-0.7.3-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/pymodules/python2.7'] Server time: Sat, 6 Feb 2021 23:47:07 +0530 survey/views.py: This is where the error is occurring, in line get_or_none. I'm getting two objects here. def fill(request, link): fp = get_or_none(survey_participant, link__exact=link) if not fp: return render(request, 'survey/fill.html', {'errormessage': constants.SURVEY_LINK_INVALID_TEXT}) What should I do now? -
Flask send_file() equivalent in Django
do you know what is the Django equivalent command for the below Flask command: return send_file("output_file.json") -
Heroku app "Not Found. The requested resource was not found on this server."
What a dread.. works perfectly fine on my local server. I included all requirements inside the pipfile and removed the requirements.txt file. Looks like the application works now (was getting an application error before). BUT NOW stuck on "Not Found. The requested resource was not found on this server" (line 24 in the Heroku log below). Additionally, my url's /admin/ shows a "Server Error(500)". Please see below - Heroku log, pipfile, Procfile, and settings.py: Procfile web: gunicorn myquiz.wsgi --log-file - Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] djangorestframework = "==3.12.2" django-nested-admin = "==3.3.3" asgiref = "==3.3.1" click = "==7.1.2" dj-database-url = "==0.5.0" django-cors-headers = "==3.7.0" django-heroku = "==0.3.1" gunicorn = "==20.0.4" itsdangerous = "==1.1.0" psycopg2 = "==2.7.7" python-decouple = "==3.4" python-monkey-business = "==1.0.0" pytz = "==2021.1" six = "==1.15.0" sqlparse = "==0.4.1" whitenoise = "==5.2.0" Django = "==3.1.6" Flask = "==1.1.2" Jinja2 = "==2.11.3" MarkupSafe = "==1.1.1" Werkzeug = "==1.0.1" [requires] python_version = "3.7" Settings.py import os import django_heroku import dj_database_url from decouple import config # 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 … -
Updating Django cached template after updating instance
I have a Django template that contains a button for the number of likes on an object and, the number of likes for each object. {% if request.user in object.likes.all %} <button class="like-btn is-liked" type="button"> Like </button> {% else %} <button class="like-btn not-liked" type="button"> Like </button> {% endif %} {% cache "post-likes" post.id %} <span class="number-of-likes"> 43 </span> {% endcache %} Now I also want to cache the part of whether a user has liked a post or not using: {% cache "post-liked" post.id request.user.id %} <button class="like-btn is-liked" type="button"> Like </button> {% else %} <button class="like-btn not-liked" type="button"> Like </button> {% endif %} How can I update these cached segments after a user likes a post? Should I do it in my view? -
Bootstrap Why don't columns align horizontally
I want to make these columns at the end of the file Horizontally alligned but for some reason it alligns the columns vertically🤔? Im using reactjs btwexample image render() { return ( <Container className="Home"> {this.state.assets.map(asset => <AssetEntry asset={asset} />)} </Container> ) } } function AssetEntry(props: { asset: Asset }) { return ( <Row className="cashflow-entry"> <Col> <span>Name: {props.asset.name};</span> </Col> <Col> <span>Value: {props.asset.value};</span> </Col> <Col> <span>Interest: {props.asset.interest};</span> </Col> <Col> <span>Taxable: {props.asset.taxable ? "Yes" : "No"};</span> </Col> </Row> ) } -
Django web server redirecting to https://true/
I'm trying to add locally SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_HOST = True SECURE_SSL_REDIRECT = True but then my django responses become different. when I go to http://127.0.0.1:8000/ it redirects to https://true/ then i tried deleting those lines, and re-run my django app and it is still redirects to true/ please help! i dont know whats wrong. -
Django. How to connect svg icon from svg array
I need help with connecting SVG icons from the SVG array. I have an svg array icons.svg, in simple projects, to connect a svg icon I used <img src="img/icons/icons.svg#bitcoin" class="svg-blockchain-dims" alt="blockchain"/>, in django i do the same thing, using {% static 'main/img/icons/icons.svg#bitcoin' %}, but it is not working. All styles, simple images works, but svg icons connected with this method, no. -
how can I save multiple data in many-to-many relationship come from checkbox input?
I created a checkbox field by using ManyToManyField. this method has worked when I create the object on the admin page and it returns back all objects have choices but I have no idea how can I create multiple objects with a checkbox with many-to-many relationship and How I save it? you can see the following code: models.py AMENITIES = [ ("Electricity", "Electricity"), ("Water", "Water"), ("Gas", "Gas"), ("Elevator", "Elevator"), ("Maids Room", "Maids Room"), ("Garden", "Garden"), ("Air Condition", "Air Condition"), ("Pool", "Pool"), ] class myChoices(models.Model): choice = models.CharField(max_length=154, unique=True, choices=AMENITIES) def __str__(self): return self.choice class Store(models.Model): amenities = models.ManyToManyField(myChoices) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=255) price = models.DecimalField(max_digits=100, decimal_places=2) bathroom = models.PositiveSmallIntegerField(default=0) bedroom = models.PositiveSmallIntegerField(default=0) furnished = models.CharField(max_length=100, choices=FURNISHED, default=FURNISHED[0][0]) ad_type = models.CharField(max_length=100, choices=ADTYPE, default=ADTYPE[0][0]) area = models.DecimalField(max_digits=100, decimal_places=3) level = models.PositiveIntegerField(default=1) detail = models.TextField(max_length=1000) image = models.ImageField(upload_to='media/', default='images/image_cover.jpg', blank=False) date = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=20, null=True) product_type = models.CharField(max_length=15, blank=False, default="Home") def __str__(self): return self.title forms.py AMENITIES = [ ("Electricity", "Electricity"), ("Water", "Water"), ("Gas", "Gas"), ("Elevator", "Elevator"), ("Maids Room", "Maids Room"), ("Garden", "Garden"), ("Air Condition", "Air Condition"), ("Pool", "Pool"), ] class StoreForm(forms.ModelForm): price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'price...'})) title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'title...'})) amenities = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=AMENITIES) area = forms.FloatField(label='Area(m2)', … -
Unable to show the data in django-mapbox-location-field Django
I hope you all great! I'm trying this module https://github.com/simon-the-shark/django-mapbox-location-field and I'm so confused about how can I add a field in my registration form below using this module. {% extends "base.html" %} {% block content %} <h1>Create Auction</h1> <div class="wrapper"> <form action="{% url 'auctions:create' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if error_message %}<p class="error"><strong>{{ error_message }}</strong></p>{% endif %} <span>Enter title:</span> <span class="required_field" >*</span> <br> <input class="textbox" type="text" name="title"> <br> <br> <span>Enter description:</span> <br> <input class="description_box" type="text" name="description"> <br> <br> <span>Upload picture:</span> <br> <input class="textbox" type="file" accept="image/*" name="image"> <br> <br> <span>Enter minimum value:</span> <span class="required_field" >*</span> <br> <input class="textbox" type="text" name="min_value"> <br> <br> <input type="submit" class="submit_button" name="submit_button" value="Create"> </form> </div> {% endblock %} I tried to add this in my form but it won't work, nothing shows! <form method="post"> {% csrf_token %} {{form}} <input type="submit" value="submit"> </form> {{ form.media }} Many thanks! -
Problem with showing images in django admin
I am going through the tutorial and I was wondering about something: I have an app called projects with a model: class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='/img') The images are in app/static/img. I can see them on the website: <img class="card-img-top" src="{% static project.image %}"> But when I go into admin, after clicking on the project object it crashes with Exception [WinError 3] The system cannot find the path specified: '/img' Official Django tutorial actually says that you need to put static files into app/static/app, but when I put them into projects/static/projects/img they are no longer on the website and the admin still crashes. I also put the files into projects/static/projects/ and now the admin works, but the website doesn't show the pictures and the dropdown menu in admin also doesn't actually show the images, so I guess nothing has access to these images anymore. My settings are STATIC_URL = '/static/' Is there a document where it clearly says what should be in the settings and where should the static files go? I am super confused about this. -
Not able to store data in mongodb
Function in views.py: def addevent(request): client = MongoClient('localhost', 27017) db_handle = client['event'] col = db_handle['library_event'] if request.method == 'POST': form = Addeventform(data=request.POST) if form.is_valid(): add_event=models.Event(name=form.cleaned_data['name'], venue=form.cleaned_data['venue'], time=form.cleaned_data['time'], organiser = form.cleaned_data['organiser']) collection.insert_one(dictionary) col.update_one({'name':add_event.name},{'venue': add_event.venue },{'time': add_event.time},{'organiser':add_event.organiser}) add_event.save(using='mongo') return render(request,'templates/index.html') settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'book', 'USER': 'root', 'PASSWORD': 'jaswanth', 'HOST': '127.0.0.1', 'PORT': '3306', }, 'mongo': { 'ENGINE': 'djongo', 'NAME': 'event', } } After running python manage.py runserver, I got : Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: library.Admins.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. System check identified 1 issue (0 silenced). You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): library. Run 'python manage.py migrate' to apply them. February 07, 2021 - 00:41:38 Django version 3.0.5, using settings 'lms.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. After running python manage.py migrate, I got this error "django.db.utils.OperationalError: (1050, "Table 'library_event' already exists")" . The data which I enter is not getting stored in Mongodb database on localhost. Please help me out … -
nginx does not serve static files from django admin
I have already tried all solutions presented here and elesewhere, and although my problem seems to be common, I still cannot resolve it. I have django admin panel and nginx serving it. When I load the page I get it raw without css or js. If I inspect the page I see following errors: Refused to apply style from 'http://localhost:8000/static/admin/css/dashboard.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. localhost/:1 Refused to apply style from 'http://localhost:8000/static/admin/css/nav_sidebar.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. localhost/:9 GET http://localhost:8000/static/admin/js/nav_sidebar.js net::ERR_ABORTED 404 (Not Found) In django settings I have: STATIC_ROOT = 'static' I also ran python manage.py collectstatic I see that files are endeed in the static folder. nginx server config looks like that: worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /home; location @backend { proxy_pass http://admin-panel:8000; } location / { try_files $uri $uri/ @backend; } location /static/ { alias /home/static/; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } … -
django/react - How does including a redirect inside my URL for password-reset work?
I created a microservice to reset a users password when they can't remember it. Here is my flow: User sends post message to my django backend requesting a password reset via my frontend react form. If the user is in my db, then a token and uidb64 get generated. An email arrives in their inbox directing them to a link where they can create a new password. The url is holding token and uidb64 data to verify authentication/password rest. Once link in email is clicked and verified for correct token/uid credentials. [Here is where I'm confused ->] It, being the link, ideally redirects the user to my frontend react form that allows them to create a new password. This is the part of my flow I'm confused. Currently the URL redirects them to the standard drf page, as expected to. But how can I achieve this link to redirect them to my react-frontend post credential verification, token and uid. I've addred a redirect link in the URL, but it's empty because I'm not sure what to put in it/not sure how to get my view, PasswordTokenCheckAPI() to redirect From react, the new password form is then submitted to my django … -
Django create role-specific profile object based on defined roles in UserProfile model
I have general user profile model which has several roles - Client, Translator and Editor. I'm using a one-to-one relation with the extended user model I've created in accounts app and I'm using Django post_save signal to automatically create a profile instance related to the user which works just fine. Now here is the problem: I need to have role-specific profile model like client profile, translator profile, etc. and again I'm trying to use Django post_save signal to create a {role} profile object related to the main UserProfile model and I'm getting the error below: Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/user/add/ Django Version: 3.1.6 Python Version: 3.9.1 Installed Applications: ['modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'ckeditor', 'ckeditor_uploader', 'crispy_forms', 'crispy_bootstrap5', 'accounts.apps.AccountsConfig', 'profiles.apps.ProfilesConfig', 'clients.apps.ClientsConfig', 'translators.apps.TranslatorsConfig', 'editors.apps.EditorsConfig', 'managers.apps.ManagersConfig', 'orders.apps.OrdersConfig', 'checkout.apps.CheckoutConfig', 'blog.apps.BlogConfig', 'website.apps.WebsiteConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\Django\tct\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Django\tct\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django\tct\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Django\tct\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Django\tct\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, … -
how to make this application that generates Tournament Brackets
Design an application that generates Tournament Brackets. N Number of teams can register for a tournament. Only X number of teams can be finalists. The number of levels of the tournament is L >= 2 Each bracket can contain X number of teams only. To progress to the next level a team should be in the Top 5. 100 < N < 3000 20 < X < 30 L>1 -
django project getting error on gunicorn but running perfectly on using manage.py runserver
My django project is working perfectly on using manage.py runserver. But when I am running it using gunicorn mysite.wsgi then it is giving errors my wsgi.py import os from django.core.wsgi import get_wsgi_application import socketio from myapp.websocketserver import sio import eventlet os.environ["DJANGO_SETTINGS_MODULE"]="mysite.settings" django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) eventlet.wsgi.server(eventlet.listen(('', 8000)), application) Now these are some errors I am getting with gunicorn on running=> gunicorn mysite.wsgi django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. then I run=> gunicorn --env DJANGO_SETTINGS_MODULE=mysite.settings backend.wsgi raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. then I added this code in settings.py import django django.setup() now I ran=> gunicorn --env DJANGO_SETTINGS_MODULE=mysite.settings backend.wsgi then I am getting this error: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My settings.py has SECRET_KEY variable. And I am not getting any solution for this. When my project is working fine with runserver then what is problem with gunicron. How to resolve these error -
Django: iterate over all objects fills all the memory
I have a Django (3.1.5) project with a postgresql database with the model I show below. The problem is that I'm not able to iterate over all objects. When I try to iterate my memory gets full until the process needs to be killed. How does Article.objects.all() iterate over objects? Does it first load all objects in memory? I'm using a simple for to iterate: for art in Article.objects.all(): print(art) break The model: class ArticleManager(models.Manager): def search(self, search_text): search_vector = \ SearchVector( 'title', weight='A',config='portuguese' ) + \ SearchVector( 'author_name', weight='A',config='portuguese' ) + \ SearchVector( 'description', weight='B',config='portuguese' ) + \ SearchVector( 'body', weight='C',config='portuguese' ) search_query = SearchQuery( search_text, config='portuguese' ) search_rank = SearchRank(search_vector, search_query) qs = ( self.get_queryset() .filter(search_vector=search_query) .annotate(rank=search_rank) .order_by('-rank') ) return qs class Article(models.Model): title = models.CharField(max_length = 250) description = models.TextField() body = models.TextField() url = models.URLField(unique = True,max_length = 500) url_basename = models.URLField(max_length = 500,blank=True,null = True) authors = models.ManyToManyField('accounts.Author',related_name = 'autores') author_name = models.TextField(blank=True,null = True) jornal = models.ForeignKey(Jornal,on_delete=models.CASCADE,related_name = 'jornal') mongo_id = models.CharField(max_length = 30,unique = True) publish_date = models.DateTimeField() creation_date = models.DateTimeField(default=datetime.now, blank=True) exclusive = models.BooleanField(blank=True,null = True) tags = TaggableManager() entidades = models.TextField() search_vector = SearchVectorField(null=True) def __str__(self): return self.title class Meta: ordering … -
Ge the coordinates latitude, longitude from the user using Django
What I have: I have a registration form using default forms in Django. I want to add a new field or fields to get the current location, even by pressing "Get current location" or by typing the address. Is there any up to date modules, because I tried some of them has many problems and errors. I'm using the latest python and Django version. Many thanks for you! -
How to import and instantiate classes imported from dll using ironpython?
I have DLLs from a project implemented in C#, but i want to create a python (django) solution based on that project. For that purpose I'm using ironpython to import and load the DLLs and I'm creating a handler to handle them. The DLL import and setup is running properly and so I can use the provided classes and methods defined in that project. The problem is that now i need to convert an object of an imported class to another imported class: C# code snippet: DownloadProvider downloadProvider = null; ConnectionConfiguration configuration = downloadProvider.Configuration; ConfigurationMode configurationMode = configuration.Modes.Find("IE"); ConfigurationPcInterface pcInterface = configurationMode.PcInterfaces.Find("My Interface", 1); IConfiguration targetConfiguration = pcInterface.TargetInterfaces[0]; Python code: import Connection as CONN import Download as DL downloadProvider = self.instance.DeviceItems[1].GetService[DL.DownloadProvider]() print(downloadProvider) # Download.DownloadProvider # initiate connection configuration = downloadProvider.Configuration print(configuration) # Connection.ConnectionConfiguration # get the device interface configurationMode = configuration.Modes.Find("IE") print(configurationMode) # Connection.ConfigurationMode # get the interface pcInterface = configurationMode.PcInterfaces.Find("My Interface", 1) print(pcInterface) # Connection.ConfigurationPcInterface targetConfiguration = pcInterface.TargetInterfaces[0] print(targetConfiguration) # Connection.ConfigurationTargetInterface Now targetConfiguration, when printed, returns "Connection.ConfigurationTargetInterface". When i print the types of these variables they all print "<class 'CLR.CLR Metatype'>" But my problem is on the last line of the C# snippet, where i need targetConfiguration to be … -
when i try to add multiple language in django nothing changed when i change language
when i try to add multiple language in django nothing changed when i change language i added two language but when i press on arabic nothing changed in html i mean why urls.py : from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _ from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path from django.views.i18n import set_language from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('set_language', views.set_language, name='set_language'), path('il8n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls),] urlpatterns += i18n_patterns( path('', views.home_page, name='home_page'), path('test', views.test, name='test'), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py : from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LLOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('ar', _('Arabic')), ('en', _('English')), ) views.py : def set_language(request): if requset.method == 'POST': cur_language = translation.get_language() lasturl= requset.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang return HttpResponseRedirect("/"+lang) html page form : <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code … -
Django Framework got Server Error 500 when DEBUG to False
I am using Django framework for project. I am rendering the HTML templet def index(request): print(" --- check fine?") # for print debug trees = Tree.objects.all() print(trees) return render(request, "index.html", {'trees': trees}) --- check fine? <QuerySet [<Tree: Tree object (8)>, <Tree: Tree object (10)>, <Tree: Tree object (11)>, <Tree: Tree object (12)>]> [06/Feb/2021 17:28:44] "GET / HTTP/1.1" 500 145 these are my urls. urlpatterns = [ path("", views.index, name="index"), path('about/', views.about , name='about'), path('contact/', views.contact , name='contact'), path('upload/', views.upload_file , name='upload'), ] DEBUG = False I am getting above error. when I set my DEBUG = True every thing works fine means show index.html and shows even data too. setting DEBUG = False make difficult to find an error. index.html contains below code which fetches data. {% for tree in trees %} <article class="col-lg-3 col-md-4 col-sm-6 col-12 tm-gallery-item"> <figure> <img src="{{tree.image.url}}" alt="Image" class="img-fluid tm-gallery-img" /> <figcaption> <h4 class="tm-gallery-title">{{tree.name}}</h4> <p class="tm-gallery-description">{{tree.desc}}</p> <!-- <p class="tm-gallery-price"></p> --> </figcaption> </figure> </article> {% endfor %} -
Deploying a django rest framework api that uses react for the frontend
I am currently working on a project that that has a react frontend from which I fetch information from the rest framework api and then display it. It is the first time I deploy something like this and I have found it very confusing to understand what is the best way to deploy this. What I Have Tried I tried deploying on heroku without really knowing what I was doing and then the following happened. My react app shows perfectly on heroku without any problems, but when the fetch funcitons are called there was an error that said connection refused. Then I realized that my django server had to be running in my computer in order to react o be able to fetch the information. I thought that the django server would also get deployed but apparently I have to deploy separately I guess. I have been searching for a while and I found something about nginx, digital ocean and docker but I didn't understand what would I have to do in this case. Anyone knows what should do I do in this case? -
Password changing view is not working correctly
So I'm trying to see if user matches their old password, if they don't then it will give a message saying "Your old password in incorrect" but if they match their old password then it should check if user matched new and confirmed password correctly, if they did not then it should give a message saying "Your new passwords do not match", But even when I match the old password correctly it always says "Your old password is incorrect" even if it is correct. views.py @login_required def userchange(request): if request.method == 'POST': # user = User.objects.get(username=request.user.username, password=request.POST['Old password']) if User.objects.filter(username=request.user.username, password=request.POST['Old password']).exists(): if request.POST['New password1'] == request.POST['New password2']: User.objects.update_or_create(username=request.user.username, password=request.POST['New password2']) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} <input type="password" placeholder="Old password" name="Old password"> <input type="password" placeholder="New password" name="New password1"> <input type="password" placeholder="Confirm password" name="New password1"> <button type="submit">Change password</button> </form> -
What could be the problem of django run error
My Django project used to work well the day before but it was not working when I run the next day. The following is the error I am getting. I didn't change anything and yet it did not work. When I run my project, the following error occurs. The project name is 'carpooling' and the the database user is 'Jigme'. I think the last line points the error towards the database which I didn't change anything. Please help me. Your help will be appreciated. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1044, "Access denied for user 'jigme'@'%' to database 'carpooling'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner …