Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my specific css code changes not being reflected on my browser?
So, I have a specific css code for my badge message notification that is not being updated when I mess with it. The rest of my css, form styles.css are working. When I edit them, the changes are reflected. Even when I move my badge css code over to styles.css the changes are still not reflected. They are indeed showing up when I inspect element, but not being reflected in the browser. I tried emptying the cache, doing a hard reload, etc. but nothing seems to be working. I am guessing there is something overriding my badge code? When I first made it, I had 0 problems editing it. I must of added something in the meantime. My badge should be showing up as white instead of red, and it should be far higher than it is, but it's not moving and it's still the same color as when I originally made it. base.html/header <link rel="stylesheet" href="{% static 'css/notification.css' %}" type="text/css" class = "notification"/> base.html/badge <a class= text-danger href="{% url 'dating_app:conversations' user.id %}" type="text/css" class="notification"> <span>Inbox</span> <span class="badge">{% unread_messages request.user %}</span> </a> notification.css .notification { text-decoration: none; padding:50; position: relative; display: inline-block; } .notification .badge { position: absolute; top: 50px; … -
Heroku django app crashing (H10) after page acess
well, my app is working fine locally but it's crashing after trying to access on Heroku. I'm using keras (and tensorflow) on it and maybe that's the reason, requirements are ok, and the building show no problems. If it helps, here is my log... 020-05-13T22:08:18.257805+00:00 app[web.1]: np_resource = np.dtype([("resource", np.ubyte, 1)]) 2020-05-13T22:08:18.780008+00:00 app[web.1]: System check identified no issues (0 silenced). 2020-05-13T22:08:18.997067+00:00 app[web.1]: May 13, 2020 - 22:08:18 2020-05-13T22:08:18.997196+00:00 app[web.1]: Django version 3.0.6, using settings 'bens.settings' 2020-05-13T22:08:18.997197+00:00 app[web.1]: Starting development server at http://127.0.0.1:8000/ 2020-05-13T22:08:18.997198+00:00 app[web.1]: Quit the server with CONTROL-C. 2020-05-13T22:11:08.154538+00:00 heroku[web.1]: State changed from starting to crashed 2020-05-14T00:10:44.353952+00:00 app[api]: Starting process with command `python manage.py` by user 2020-05-14T00:11:11.348754+00:00 heroku[run.7381]: State changed from starting to up 2020-05-14T00:11:11.703430+00:00 heroku[run.7381]: State changed from up to complete 2020-05-14T00:12:23.470671+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=brec.herokuapp.com request_id=43829cd6-5114-4236-9f6f-563be3bdb200 fwd="177.135.10.100" dyno= connect= service= status=503 bytes= protocol=http 2020-05-14T00:12:23.325313+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=brec.herokuapp.com request_id=ea292b42-6010-47bd-b527-6019af8f60d1 fwd="177.135.10.100" dyno= connect= service= status=503 bytes= protocol=http 2020-05-14T00:12:25.948768+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=brec.herokuapp.com request_id=2759d82e-f504-4b57-885d-56e6578c178f fwd="177.135.10.100" dyno= connect= service= status=503 bytes= protocol=http 2020-05-14T00:12:44.661605+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=brec.herokuapp.com request_id=01e5d982-a071-4472-aade-da2c80b3ae0a fwd="177.135.10.100" dyno= connect= service= status=503 bytes= protocol=http 2020-05-14T00:12:45.611089+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=brec.herokuapp.com … -
Python script on Django shell not seeing import if import not set as global?
I have searched the stackoverflow and wasn't able to find this. I have noticed something I can not wrap my head around. When run as normal python script import works ok, but when run from Django shell it behaves weird, needs to set import as global to be seen. You can reproduce it like this. Make a file test.py in folder with manage.py. Code you can test with is this. This doesn't work, code of test.py: #!/usr/bin/env python3 import chardet class LoadList(): def __init__(self): self.email_list_path = '/home/omer/test.csv' @staticmethod def check_file_encoding(file_to_check): encoding = chardet.detect(open(file_to_check, "rb").read()) return encoding def get_encoding(self): return self.check_file_encoding(self.email_list_path)['encoding'] print(LoadList().get_encoding()) This works ok when chardet set as global inside test.py file: #!/usr/bin/env python3 import chardet class LoadList(): def __init__(self): self.email_list_path = '/home/omer/test.csv' @staticmethod def check_file_encoding(file_to_check): global chardet encoding = chardet.detect(open(file_to_check, "rb").read()) return encoding def get_encoding(self): return self.check_file_encoding(self.email_list_path)['encoding'] print(LoadList().get_encoding()) First run is without global chardet and you can see the error. Second run is with global chardet set and you can see it works ok. What is going on and can someone explain this to me? Why it isn't seen until set as global? -
Why are my css changes not being reflected in my browser?
So I am noticing that my css changes are not being reflected. I did a hard-reload and cleared the cache but still nothing. Like I can literally delete the css file and my badge which I'm trying to edit is still there... it only goes away once I take it off of base.html directly. So what is going on here? I have a static folder in my app, with a css folder and then my css/notification file. I tried doing collectstatic through terminal but that doesn't do anything. Also, I already have my load static tag in my html. And, my css file is indeed loading when I go to inspect element and the changes are showing up within that file but they are not showing up within my browser. Any idea what's going on here? Nothing I do seems to be working! ps: Changing STATICFILES_DIR to STATICFILES_DIRS doesn't do anything. settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ "/DatingAppCustom/dating_app/static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'dating_app/media') settings.py/installed_apps 'django.contrib.staticfiles' urls project urlpatterns = [ path('admin/', admin.site.urls), path('', include('dating_app.urls', namespace= 'dating_app')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Need Advise on Wich language i should use to build my app
I'am planning to build an application and webside wich will include user accounts , soundfiles , and exchange of thoose files between accounts. -
Apply django Channels for my existing application
I have a django application (Request and response type) that is used from different places at a same time. Currently i have that with 3sec refresh to maintain the consistency with delay. I would like to change the existing application to channels centeric application using redis. I am having hard time understanding to convert it. It is patient exam rooms application in a clinic. The room view can be opened from different places and can trigger a event. I would like a little help to start. Thank you. -
Should I Leave Django Allauth As-Is Or Make The Changes I've Suggested
Im using Django Allauth and have a number of questions. (a) When a user registers they are instantly logged in and a confirmation email is sent to their inbox. I am wondering if this is best practice? Should the user instead be signed out after registration and only allowed to sign in using the link in their email? I am also wondering about password change. The password change functionality that comes with Allauth simply asks the user to enter their old password then enter a new one twice. My two questions for this are (b) is this good practice or should I make my users request a new password via email, and (c) should I force logout my users after a password change and make them login using their new credentials? (d) And lastly, if a user has forgotten their password they can request a new one sent to them via email. I could imagine this could easily be abused as you do not need to be signed in to do this (a person or bot continually enter a users email address sending them thousands of password reset links). Is there a way to add a limit on a persons … -
How do we show the result of calculation on Front End done based on the user input in Django?
I am working on a Django Project, where a student will write his/her course name in a form and click on Calculate button and the system will use the Fuzzy Logic to calculate the performance of students based on the details of that specific course and then show the result of that calculation below the Calculate Button. What I have done so far are below. views.py: from django.shortcuts import render, redirect from django.contrib import messages from .forms import PerformanceCalculatorForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Subject, Detail from .fuzzy_logic_algo import fuzz_algo def performanceCalculator(request): if request.method == 'POST': performance_form = PerformanceCalculatorForm(request.POST) if performance_form.is_valid(): sub = performance_form.cleaned_data.get('subject') skype = Details.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance') internal_course = Details.objects.filter(subject__subject=sub, user__username=User.username).get('internal_course_marks') prg_lab = Details.objects.filter(subject__subject=sub, user__username=User.username).get('programming_lab_activity') mid_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('mid_term_marks') final_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('final_term_marks') result = fuzz_algo(skype, internal_course, prg_lab, mid_marks, final_marks) context = { 'result': result, } return render(request, 'users/performance_calculator.html', context) else: performance_form = PerformanceCalculatorForm() return render(request, 'users/performance_calculator.html', {'performance_form': performance_form}) models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Subject(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100) def __str__(self): return '{} ({})'.format(self.subject, self.user.username) class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.OneToOneField(Subject, on_delete=models.CASCADE) skype_session_attendance = models.FloatField() internal_course_marks = models.FloatField() … -
Do I need to migrate to PostgreSQL from SQLite for Heroku deployment?
Pretty much just as the title describes. It doesn't exactly say on the offical website and i've seen conflicting info in other guides. I have another post where I'm running into difficulties and thought this could be related but better off as it's own question. -
Django LDAP with OpenWisp Django-IPAM
I'm trying to setup OpenWisp Django-IPAM with WebUI authentication via LDAP. We have an OpenLDAP server within our network and I am looking to use a simple LDAP lookup to check for a valid user object for login. I see that the API's generics.py file has an authentication_classes section, which then contains SessionAuthentication and BasicAuthentication. Is this the same mechanism that handles the authentication for the Web UI? Is there a way to configure OpenWisp Django-IPAM to use something like Django-Auth-LDAP for authentication when logging into the web interface? -
Setting a field in model before saving the value Django
I have an object with date_posted field which is basically the day object was created using auto_now_add = True. In my form, I have a drop-down list with values. And I intend to add the value to an expiry field which is also aa DateTime object. Currently, in my view, I have: post = form.save(False) e = int(request.POST['expiry']) post.expiry = post.date_posted + datetime.timedelta(days=e) post.save() however, I am getting this error: post.expiry = post.date_posted + datetime.timedelta(days=e) TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta' I assume it's because my object hasn't been saved to the database yet. How can I add 'days' to the expiry field got from my form? I have printed the e value and it is correctly received btw. And I do not want to add date_posted now in save() method since it may cause issues with the automatic timezone set in Django -
New sessionid in every request
I am creating my django react app. I would like to make authentication via Cookie just like in Django oscar documentation. But when i send my post request i get a new session id with every request. I am using axios with credentials. Its my base.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oscar.apps.basket.middleware.BasketMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ "https://example.com", "https://sub.example.com", "http://127.0.0.1:8000", "http://localhost:3000", "http://localhost:8000", "http://127.0.0.1:9000", "127.0.0.1" ] And this is my Post requests import axios from "axios" import Bar from './Bar'; import BasketItem from './BasketItem' import "../css/basket.min.css" const session = axios.create({ withCredentials: true }); const configAxios = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Credentials': true, }, }; const Basket = props => { const [countries, setCountries] = useState([]); const [load, setLoad] = useState(false); const [error, setError] = useState(''); const [array, setArray] = useState([]); useEffect(() => { const data = { url: "http://127.0.0.1:8000/api/products/22/", quantity: 1, } session.post('http://127.0.0.1:8000/api/basket/add-product/',data) .then(res =>{ console.log(res.data) console.log("Cookies are ", document.cookie) }) session.post('http://127.0.0.1:8000/api/basket/add-product/',data) .then(res =>{ console.log(res.data) console.log("Cookies are ", document.cookie) })},[]) And this is results of my requests So if you can see sessionid values are different instead of being the same and its provide to 401 error. -
Is there a python library that allows me to display snippets of code in my django views [closed]
I want to be able to produce a nice output with syntax coloring. -
Editing columns and sending data to database from views.py Django
my problem is that I can't make query directly in my views.py. I am writing app that allows user to take the test. But problem is that when I send filled form from the test page to my views.py and call form.save(), the query is not made in the exact moment, so I can't edit this query in the next lines of code. Is there any way that I could get around this? Some kind of form.send? Below is my code views.py: if form is valid: form.save() #i send data to DB choiceIndex = Choice.objects.latest('id').id choice = Choice.objects.get(pk=choiceIndex) choice.user = Users.objects.get(name=username) choice.save() #i want to edit column made earlier return redirect("detail", question_id) models.py: class Choice(models.Model): user = models.ForeignKey(Users, null=True, on_delete=models.CASCADE) question = models.ForeignKey(Questions, null=True, on_delete=models.CASCADE) answer = models.CharField(null=True,max_length=50) -
How to use permission based functions in react frontend with Django Rest API?
I use Django Rest Framework with React on the frontend. I use Token Athentication and everything works fine. I now want to implement some permission based functions in my React frontend. More specifically, I want the author of a post to be able to edit the post, but all other users not. How can I achieve this? My idea is that I add an is_viewing_own_story as a boolean to the user model in the django backend. When the author now clicks on the post, redux updates this state to 'true' and the buttons for deleting and updating stories appear (if is_viewing_own_story=true show buttons else show nothing). I'm not sure if this is the smartest way or if there is a best practice? If there is anything to read about, or any git hub repo to inform im happy to study that. -
Django CRUD for models with one too many relationships
Lets say I have the following models: class Challenge(models.Model): pass class Round(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) index = models.IntegerField() description = models.CharField(max_length=100) In this use case. Each challenge has a variable amount of rounds. I want to create CRUD forms for these models. I am unsure what would be the best way to accomplish this feature since the amount of rounds for each challenge would be variable. All similar posts I found were from over five years ago so I was wondering what would be the best way to implement this. -
How can I call an ajax script to html
I am learning to create a like button on django but when finished with the code I found an error that the like/unlike button doesnt work, I have checked my entire code and everything looks fine except when I am calling ajax to the html script. I think the error is there but I dont know how to properly call it. If there is other error please let me know. imagelist.html <p><a class="like-btn" data-href="{{ image.get_api_like_url }}" data-likes="{{ image.likes.count }}" href="{{ image.get_like_url }}"> {{image.likes.count }} Like</a></p> <script src="https://ajax.gogleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addlike = likeCount + 1 var removelike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method:"GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> views.py def imagelist(request): images = Post.objects.all() context2 = {"images": images} return render(request, 'imagelist.html', context2) class PostLikeToggle(RedirectView): def get_redirect_url(slef, *args, **kwargs): slug = self.kwargs.get("slug") print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_redirect_url() user = self.request.user if user.is_authenticated(): if … -
Django Rest Filter / There are 4 objects in each hour. Show only 1 property from every hour
Now the serializer displays CoinCosts prices for a certain period of time. How to show only 1 item from every hour? 4 items are currently showing. thank Now i have this response: [ { "symbol": "MNST", "crr": "65", "costs": [ { "price": "0.2900", "timestamp": "2020-04-06T23:17:31.490075Z" }, { "price": "0.2900", "timestamp": "2020-04-06T23:20:43.310277Z" }, { "price": "0.2900", "timestamp": "2020-04-06T23:25:12.759489Z" }, { "price": "0.2900", "timestamp": "2020-04-06T23:28:12.759489Z" }, } ] but i need: [ { "symbol": "MNST", "crr": "65", "costs": [ { "price": "0.2900", "timestamp": "2020-04-06T23:17:31.490075Z" }, } ] Every hour in Timestamp only 1 element from Datebase. My code now: serializers.py class CoinCostsSerializer(serializers.ModelSerializer): class Meta: fields = ('price', 'timestamp') model = CoinCosts class CoinSerializer(serializers.ModelSerializer): class Meta: fields = ('symbol', 'crr', 'costs') model = Coins costs = CoinCostsSerializer(source='filtered_coincosts', many=True) filters.py class DateTimeRangeFilter(filters.IsoDateTimeFromToRangeFilter): def filter(self, qs, value): if value: if value.start is not None and value.stop is not None: self.lookup_expr = 'range' value = (value.start, value.stop) elif value.start is not None: self.lookup_expr = 'gte' value = value.start elif value.stop is not None: self.lookup_expr = 'lte' value = value.stop filter_query = {'timestamp__' + self.lookup_expr: value} return qs.prefetch_related(Prefetch('coincosts_set', to_attr='filtered_coincosts', queryset=CoinCosts.objects.filter(**filter_query) ) ) else: return qs.prefetch_related(Prefetch('coincosts_set', to_attr='filtered_coincosts', queryset=CoinCosts.objects.all() ) ) views.py class CoinCostFilterSet(filters.FilterSet): timestamp = DateTimeRangeFilter() class Meta: … -
python django : Got AttributeError when attempting to get a value for field `username` on serializer `PerformerSerializer`
Hi fellow programmers, I am getting the following error when I try to visit my url can you please point out the mistake in my code. Is there any error in my serializer or view. I will be gateful if you find that. Got AttributeError when attempting to get a value for field username on serializer PerformerSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. models.py class Song(models.Model): user = models.OneToOneField(UserModel, on_delete=models.CASCADE) name = models.CharField(_("Name"), max_length=50) song = models.FileField(_("Song"), upload_to=None, max_length=100) ##genre = MultiSelectField(choices=MY_CHOICES) song_image = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) likes = models.IntegerField(_("Likes"),default=0) views = models.IntegerField(_("Views"),default=0) performer = models.ManyToManyField(UserModel,verbose_name=_("Performed By"),related_name='artist_in_song') serializers.py class PerformerSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = Song fields = ('username',) class UserSerializer(serializers.ModelSerializer): #id = serializers.ReadOnlyField(source='user.id') class Meta: model = User fields = ('id',) class SongSerializer(serializers.ModelSerializer): performer = PerformerSerializer(many=True, read_only= True) user= UserSerializer(many=False, read_only= True) class Meta: model = Song fields = ('user','performer','id','name','song','song_image','likes','views') read_only_fields = ('likes','views') views.py class SongCreateView(generics.ListCreateAPIView): queryset = Song.objects.all() serializer_class = SongSerializer permission_classes = [IsAuthenticated] Thank You. -
Get Data from Choice field in Django rest framework
I have searched and tried out all solutions provided for this question in similar problem but they're not working for me. I am getting the following error when trying to get data from an endpoint Got AttributeError when attempting to get a value for field hotel_type on serializer HotelDetailSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Hotels instance. Original exception text was: 'Hotels' object has no attribute 'get_hotel_Type_display'. This is my model field truncated for clarity class Hotels(models.Model): HOTEL_TYPE = ( ('hotel', "Hotel"), ('apartment', "Apartment"), ('villa', "Villa"), hotel_Type = models.CharField( max_length=20, choices=HOTEL_TYPE, default='hotel', null=True, blank=True @property def hotel_type(self): return self.get_hotel_Type_display() This is my serializer class also truncated for clarity class HotelDetailSerializer(serializers.ModelSerializer): hotel_type = serializers.Field(source='hotel_type.hotel_Type') class Meta: model = Hotels fields = ("hotel_type" ) This is the apiview class HotelDetailAPIView(RetrieveAPIView): """Display details of a single hotel""" queryset = Hotels.objects.all() serializer_class = HotelDetailSerializer permission_classes = () lookup_field = 'slug' Could anyone kindly assist me figure out why this is not working? Thanks -
Django-Rest - Create x number of m2m objects upon creation of parent object
I have two models: class Client(models.Model): name = models.CharField(max_length=500) userassigned = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) property = models.ManyToManyField('Property', blank=True) def __str__(self): return self.name class Property(models.Model): address = models.CharField(max_length=500, blank = True) I have a form on my UI that allows the user to create a new Client object, and also select the number of Properties the Client has. How would I go about creating "x" number of Property instances with a POST method and immediately assign these new Property objects to the ManyToMany field of the new Client object? I will also need to set the userassigned field to the current user submitting the form. I would assume both the "x" number and current user would need to be sent through a URL parameter? Can I access both through the request? Thanks in advance!! -
How to use allow only POST in Django REST API Viewset
I went through the django rest framework documentation on Viewsets and dont seem to understand how to allow only POST requests on the browser API. Viewset class EmailViewSet(viewsets.ModelViewSet): queryset = models.Email.objects.all() serializer_class = serializers.EmailSerializer Model class Email(models.Model): email = models.EmailField(max_length=50,unique=True) def __str__(self): return str(self.email) Serializer class EmailSerializer(serializers.ModelSerializer): class Meta: model = models.Email fields = ["email"] -
Heroku Application Error When Deploying Django Website
While using Heroku something went wrong and now I cannot get pass the Application Error screen. I tried to do Rollback to v1 and attempt to restart everything. That probably ended up making the situation more confusing. I thought I had set up my environmental variables incorrectly. And tried an alternative method. Maybe they are still set up incorrectly. I have tried looking at my build output and Googling code=H10. I am trying to use a Postgres database. Whenever I do git push heroku master, I always see the line remote: -----> Installing SQLite3. I don't know if that is a problem. I tried googling how to stop SQLite3 being installed but got no where. .bash_profile I don't use asterisk (*) in my real version. But I didn't want to share confidential information. export AWS_ACCESS_KEY_ID="**I***ZPP***6YLUHDLX" export AWS_SECRET_ACCESS_KEY="*****0NFI***cn***jHRZ5ron13d23**j6LCz***" export AWS_STORAGE_BUCKET_NAME = "rosspython******" export SECRET_KEY="*************ab021*b742*70**dbf**4b***a**17**709" #export DEBUG_VALUE="True" export EMAIL_USER="ross***************@gmail.com" export EMAIL_PASS="**********" settings.py """ Django settings for django_project3 project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
Django define URL using post request hidden value in UpdateView
I have an UpdateView, and want to redirect to an URL using a parameter based on POST request value, that is sending in this method. For eg. ('clients:client_list', number_id) It should be, the destination of the post function after define is_valid(). Number_id is that I used in the ListView of the main foreing key model, and in my template it's a hidden input. -
Can someone help me out how to solve this error (django)?
Actually I am working on my project. But when I run python manage.py run server It produces this error. Please help me out . conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?