Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Postgres - How come my production database is working, even though not listed in settings.py - Django?
I configured my database in Heroku several months ago so don't remember exact steps I took. I'm using the Heroku-Postgres add-on: https://devcenter.heroku.com/articles/heroku-postgresql I have a DATABASE_PASS listed as a config var in Heroku. And I have a config var for DATABASE_URL In my settings.py file I only have the following as it relates to my database - Why is my app still working in production on Heroku if DATABASES variable is referring to localhost only?: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_dev', 'USER': 'postgres', 'PASSWORD': os.environ.get('DATABASE_PASS'), 'HOST': 'localhost', 'PORT': '5410', } } The Heroku-Postgres documentation states the following: The value of your app’s DATABASE_URL config var might change at any time. You should not rely on this value either inside or outside your Heroku app. Am I doing something wrong? Should I not rely on DATABASE_URL as a config var? -
object filtering in template django
I have 2 class of model post and comment for loops in my template like this I have a for loop like this {% for post in posts %} {% endfor %} and I want to make filter like this Comment.objects.filter(post=post.id) in my for loop and get some value how to write it properly? -
How to Implement Multiple User Types with Django?
I want to create a Django model like user_types = (("Agent", "Agent"), ("Branch", "Branch"), ("Company", "Company")) class User(models.Model): email = models.EmailField(db_index=True, unique=True) username = models.CharField(db_index=True, max_length=255, unique=True) user_type = models.CharField(max_length=100, choices=user_types, blank=False) and if user define user_type to store these field data there should come some extra field like: if user_type is Agent then: agent_code agent_name if user_type is Branch then: Branch_code Branch_name Branch_Id if user_type is Company then: Company_code Company_name Company_Id Is there any good way to handle this model? -
I want to detect the user's computer language so that I can translate the page according to it
I want the user to enter the website to see the text translated in his computer's language and this is what I am trying to do but when I change my computer language into Spanish, nothing changes def index(request): lang = get_language() translation.activate(lang) return render(request, 'index.html') -
How can I hide Vue code in a non SPA Django and Vue project?
I am working on a Django web app and have used Vue components inside it. Everything is fine but my only concern is that I don’t want the source code to be visible in production . I don’t want to go by the full SPA route as it will take a lot of time and effort. Can I make the code less human readable ? See if i view it in the browser then it’s completely readable and I would not like it this way in production Please help me here !! Thanks in Advance -
How do I link a User with a django model as soon as the User is created?
I am new to Django and my question is how do I link a Django User with the Climber model that I created as soon as the user is registered? So far, I can register a new User with Django's builtin user registration form. But when I go into my admin page I see that I have to create a new Climber manually and select which User I want it to link to. Thank you in advance! class Climber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] highest_grade = models.CharField(max_length=3, choices=grades, default='v0') team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) climbs_completed = models.ManyToManyField(Climb, blank=True) def __str__(self): return self.user.username # for each climbs_completed, sum up the points def total_score(self): pass -
How to access sum of reverse foreign key single field using template filter in django?
Suppose I have 2 models Customer & Account. Models class Account(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE, blank=True,null=True,related_name='account') desc = models.CharField(max_length=100) paid = models.IntegerField(default=0) received = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Customer(models.Model): name = models.CharField(max_length=30,unique=True) contact = models.CharField(max_length=10) I want to access Sum of received & Sum of paid field in template Customer View def show_customer(request,id=None): customer = Customer.objects.filter(user=request.user) return render(request,'customer/show_customer.html',{'customer':customer}) show_customer.html <html> {% for cust in customer %} {{cust.name}} {{cust.contact}} **Here I want sum of paid & sum of receive for current customer** </html> -
getting the value of request.GET in python
I tried to get the data in request.GET data however this gives me an empty values or None when printing. class SchoolMixin(ProfileTypeRequiredMixin, MultiplePermissionsRequiredMixin): profile_type = 'manager' permissions = { 'any': ('school.admin, ) } def init_vars(self, request, *args, **kwargs): self.schools = self.request.user.manager.school self.vals(request) def vals(self, request): if not request.GET: if self.schools.school_set.exists(): school = self.schools.school_set.all()[0].pk else: school = None data = { 'school': school, } else: data = request.GET self.filter_form = forms.FilterForm( data=data, prefix='FILTER', school_manager=request.user.manager, user=request.user ) self.filter_form.is_valid() self.school = self.filter_form.cleaned_data['school'] def get_context_data(self, **kwargs): data = super(SchoolMixin, self).get_context_data(**kwargs) data['filter_form'] = self.filter_form return data class FilterForm(forms.Form): school = forms.ModelChoiceField( label=_('School'), required=False, queryset=School.objects.none(), empty_label=_('School'), widget=forms.Select(attrs={'class': 'form-control'}) ) .... def __init__(self, *args, **kwargs): self.school_manager = kwargs.pop('manager') self.user = kwargs.pop('user', None) super(FilterForm, self).__init__(*args, **kwargs) url(r'^school/$', views.ExportView.as_view(), name='export'), I tried on older branch and I get the value of request.GET, I use the self.request.GET but still I get an empty or None. Thanks -
Creating a model in Django whose field has multiple other fields inside it
I'm quite new to Django and would like to clear a noob doubt. Say I have a post request to a model 'Scans' in django. The json data for the same looks like [{"id":1, "results":{"low": 3, "medium": 6, "high": 7}, "machine": "Windows", "report": "yes"] How should the model look like? I can't figure out what field type I should give to "results". -
Adding products to cart not working properly
I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Green and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Small), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? It's also worth noting that when I'm adding the same item with same variations from my single product page, then it's working fine. I think this bug is occurring because of the way my views is written. I tried to solve it myself, but I'm getting lost. Can anyone please help me out? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) item_variations = … -
Catch 401 exception in django
I'm trying to catch exception via try-catch in Django for unauthorized users i.e status code of 401. I tried: try: result = Users_Details.objects.get(auth_token=auth_token) result.password = password result.save() except Users_Details.DoesNotExist as e: error = {"status": "failure", "reason": str(e)} return JsonResponse(error, status=status.HTTP_401_UNAUTHORIZED) But it's not working. what am I doing wrong here ? -
Django Jinja2 how to convert things like {% load tawkto_tags %}?
How do I make the jump with Jinja to load things like my tags at the top of the html? {% load tawkto_tags %} I am using django-jinja with Cookiecutter. Is changing to Jinja really worth the speed??? Thanks! -
form validation errors in django
Every time I'm facing field validation error for datetime field in django. Actually I didn't know how this field works. Here is my model. and also I'm using crispy forms enter image description here class Customer(TimeStampWithCreatorMixin): check_in = models.DateTimeField(_("Check In"), auto_now=False, auto_now_add=False) and here is my forms.py code class CustomerCreateForm(forms.ModelForm): class Meta: model = Customer exclude = ('updated_by',) widgets = { 'check_in': forms.TextInput(attrs={ 'class': "form-control datetimepicker-input", 'id': "check_in", 'data-toggle': "datetimepicker", 'data-target': "#check_in", 'autocomplete': 'off', }) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('check_in', css_class='form-group col-md-6 mb-0'), ) ....... Submit('submit', 'Add Customer') ) I'm also using https://tempusdominus.github.io/bootstrap-4/ for date and time picker. -
Enabling SSO across several domains that consume the same service based backend
The most obvious solution here will allow session based authentication which is considered a bad practice in Django shomehow. So I have worked out a simple way to play the token in a cookie and then try to read it from the cookie if it is absent in the headers (like in the case of moving between 2 different domains that consume our API). The request returns the following data in the 'Cookies' sections under 'Network' However, under 'Application' I cannot see the cookie at all This is the code I have written middleware.py class WhiteLabelSessionMiddleware(MiddlewareMixin): def process_request(self, request): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if cookie_token: print(cookie_token) if cookie_token and not request_token: # must be assigned by reference request.request.META['HTTP_AUTHORIZATION'] = cookie_token def process_response(self, request, response): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if not cookie_token and request_token: response.set_cookie(settings.WHITE_LABEL_COOKIE_NAME, request_token, max_age=settings.SESSION_COOKIE_AGE, expires=settings.SESSION_COOKIE_AGE, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE) return response settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.WhiteLabelSessionMiddleware', 'core.middleware.TimezoneMiddleware', 'core.middleware.LastSeenMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'referrals.middleware.ReferralMiddleWare', 'audit_log.middleware.UserLoggingMiddleware', 'axes.middleware.AxesMiddleware', ] WHITE_LABEL_COOKIE_NAME = 'nex_token' SESSION_COOKIE_AGE = 60 * 60 * 24 * 30 * 12 _COOKIE_EXPIRES = datetime.datetime.utcnow() + \ datetime.timedelta(seconds=SESSION_COOKIE_AGE) SESSION_COOKIE_EXPIRES = \ datetime.datetime.strftime(_COOKIE_EXPIRES, "%a, %d-%b-%Y %H:%M:%S GMT") SESSION_COOKIE_DOMAIN = '.n.exchange' … -
Database Engine for PyODBC
So django currenty only provide 4 backend database engine which is : 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' If I use MySQL, all I have to do is just fill the Engine with 'django.db.backends.mysql'. But now, because my main Database is DB2, I'm having some issues to connect it with pyodbc. A help would be appreciate. Thanks! DATABASES = { 'default': { 'ENGINE': '', #some pyodbc backend database 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Field 'id' expected a number but got 'on'
I am doing a project included in Django Documentation.When i enter URL-http://localhost:8000/polls/1/vote/ i get the Error at below line, ` selected_choice = question.choice_set.get(pk=request.POST['choice']) -
I want to restrict the user from adding the duplicate value in 'type' field
class Device(models.Model): # name of the table type = models.CharField(max_length=100, blank=False) price = models.IntegerField() choices = ( ('AVAILABLE', 'Item ready to be purchased'), ('SOLD', 'Item Sold'), ('RESTOCKING', 'Item restocking in few days') ) status = models.CharField(max_length=10, choices=choices, default="Sold") # Available, Sold, Restocking issue = models.CharField(max_length=100, default='No Issue') -
Alter or override Device model from Django-push-notifications
I just started using Django-Push-Notifications but I find it concerning that the built in "Device" model uses the standard USER_AUTH table for its user field. I have my own custom user table and would like to change the 'user' foreign key in the "Device" table to point to my custom user table. In addition, I would like to add a couple fields to the "Device" table. How can I override or add fields to the Django-Push-Notifications "Device" model? -
Adding the row to another table after clicking "Add New Row" button
I'm an apprentice in Django, javascript, and HTML. I am developing a website that actually helps in filling shift handover(If a company works in shifts, then the associates in the current shift should handover the shift to next person by explaining pending tasks to be completed, scheduled tasks/activities in his/her shift.. etc). During this, I have encountered a problem. I had written 6 HTML files for 6 tables separately. And I had written Add new row, edit, save, and delete functionalities for 6 tables using one jquery script. Now I need to include all 6 tables in one HTML file and should link that one jquery script such that all functionalities(add, delete, edit and save) should work individually for 6 tables. But here if I click on add new row button on one table, the row is getting added on another table. Kindly help on this. -
What if I return None in django views and handle it in middleware?
We always return HttpResponse in Django views, but now I want to do this pack stuff in middleware. That is, I can return a dict (or something else) or raise an error in view, and my middleware will detect it: If it returns a dict (body), the middleware will pack dict like {error: None, code: 0, body: bodydict} and use JSON.dumps to get a string as response content (with code 0 for example); If it raise an error, the middleware will stringify the error and pack it like {error: "Some Error", code: 500, body: []} If the view returns None, the middleware will pack as {error: None, code: 0, body: None} But the problem is, django will detect the return of view. If it returns None, it will log an Error: The view xxxView didn't return an HttpResponse object. It returned None instead. Now I want to remove this log. What should I do? -
How do I create a method in django models that returns the sum of a field in that same model?
I'm new to Django and I have two models set up like this currently. I want to calculate, in the Climber model, that returns the total points that climber has earned by accessing the climbs_completed field. How can I go about doing this? In other words, how do I sum up the points for each Climb in climbs_completed? Is there a better way to do this besides writing a method? Thank you in advance! class Climb(models.Model): name = models.CharField(max_length=20, default='') grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] grade = models.CharField(max_length=3, choices=grades, default='v-1') weeks = [(i,i)for i in range(1,13)] week = models.IntegerField(choices=weeks, default=0) points = models.IntegerField(default=0) def __str__(self): return self.name class Climber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] highest_grade = models.CharField(max_length=3, choices=grades, default='v0') team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) climbs_completed = models.ManyToManyField(Climb, blank=True) def __str__(self): return self.user.username # for each climbs_completed, sum up the points def total_score(self): pass -
ModuleNotFoundError: No module named 'encodings' after broken pipenv Django install in Win 10?
So I'm very much out of my element here, I attempted to search this but none of the other questions appeared to be quite similar to the situation with mine (either that or I'm too unfamiliar to parse out the necessary info). I tried to install Django with a 32 bit Python 3.8 install (Windows 10) and something went wrong along the way, it wasn't appearing to run correctly after installing in pipenv and so I uninstalled python through the provided windows uninstaller within the control panel. I downloaded and installed the 64 bit python 3.8 installer and ran throught the install. I installed pipenv with: python -m pip install pipenv which appeared to work fine. I then proceeded to run: pipenv install This appeared to work as well, and then I activated the pipenv environment with "pipenv shell". It seemed okay, a new shell was opened and it looks like it IS inside of the virtual environment, but when I ran "pip freeze" to confirm everything was fine, I got the following return instead of a blank line as I would expect to be returned from a fresh environment: Is there some sort of issue with the path here? … -
Django Dynamic Forms with add and delete button. Python/Django
i am new to Django, and i am working in a project, i got a question, in my app i want to show up a form to populate the database called patients, this form is based in a model, and this model is linked with a foreign key to another model Relatives(Family), i would like to create a Dynamic Form where i could add as many members as i want, for example, I am filling a patients info, so when getting to the relatives section it would appear a form for adding one family member but what about if i want to add another member, i've seen there are Django Form Sets, but they dont seem to have any methods to add add or delete buttons, so what approach should i take, any solutions or recommendations? Thanks! -
How do I communicate with a websocket within a Django API GET request?
I'm trying to get a response from a websocket server (implemented with websockets and asyncio) from within a Django REST API method. Something of the following structure: Django App (This does not work, but illustrates the idea) class AnAPI(views.APIView): async def get(self, request): try: timeout = 5 try: ws_conn = await asyncio.wait_for(websockets.connect(WS_STRING), timeout) except ConnectionTimeoutError as e: <.....> await ws_conn.send(...) response = await ws_conn.recv() ws_conn.close() return Response(...) except Exception as e: print(e) return Response(...) WS Server ws_server = websockets.serve(...) asyncio.get_event_loop().run_until_complete(ws_server) asyncio.get_event_loop().run_forever() Apparently, this makes the Django GET method return a <class 'coroutine'> AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` Any pointers would be much appreciated! -
Django ORM pass model method value in aggregate
This is my models: class Bill(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_bill' ) flat_rent = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) gas_bill = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) # Also i have many such decimalField here that calculated in get_total =========================================== def get_total(self): total = self.flat_rent + self.gas_bill return total I am trying to pass this get_total mehtod value here: user_wise = User.objects.filter( id=request.user.id ).aggregate( get_total=Sum('user_bill__get_total') ) in my case, i have to query everything from user with related_name, that is why i am aggregate the model method here. Can anyone help how can i pass this get_total method in aggrigate? I dont want to pass like this. Bill.objects.get(user__id=request.user.id).get_total Can anyone help to achieve this? Thanks for your help