Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: type object 'x' has no attribute 'view'
i'm doing a project and I'm trying to incorporate the spotify API with it. Anyhow, i'm receiveing this error and really don't know how to get past it. Thanks in advanced, here is the code from views.py: from django.shortcuts import render from .credentials import REDIRECT_URI, CLIENT_SECRET, CLIENT_ID from rest_framework.views import APIView from requests import Request, post from rest_framework import status from rest_framework.response import Response class AuthURL(APIView): def get(self, request, format=None): scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing' url = Request('GET', 'https://accounts.spotify.com/authorize', params={ 'scope': scopes, 'response-type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID }).prepare().url return Response({'url': url}, status=status.HTTP_200_OK) Here's the code of urls.py: from django.urls import path from .views import AuthURL urlpatterns = [ path('get-auth-url', AuthURL.view()), ] -
Can I override default CharField to ChoiceFoeld in a ModelForm?
I have a (horrible) database table that will be imported from a huge spreadsheet. The data in the fields is for human consumption and is full of "special cases" so its all stored as text. Going forwards, I'd like to impose a bit of discipline on what users are allowed to put into some of the fields. It's easy enough with custom form validators in most cases. However, there are a couple of fields for which the human interface ought to be a ChoiceField. Can I override the default form field type (CharField)? (To clarify, the model field is not and cannot be constrained by choices, because the historical data must be stored. I only want to constrain future additions to the table through the create view). class HorribleTable( models.Model): ... foo = models.CharField( max_length=16, blank=True, ... ) ... class AddHorribleTableEntryForm( models.Model) class Meta: model = HorribleTable fields = '__all__' # or a list if it helps FOO_CHOICES = (('square', 'Square'), ('rect', 'Rectangular'), ('circle', 'Circular') ) ...? -
React GET request from Django API is not working and how to solve this?
I am trying to build django-react application. I used netlify for react deployment and herokuapp for django api deployment. My api endpoint is working perfectly but my react can't fetch them from the actual endpoint. In localhost it fetch from my actual api [ http://cylindercommerce.herokuapp.com/api/products/ ] but in production it is trying to fetch from it's own url then end point [https://modest-knuth-50c56b.netlify.app/api/products] this one but it should fetch from [http://cylindercommerce.herokuapp.com/api/products/] this endpoint. I didn't change any code. so what is the problem here check the screenshot here -
How can I customize image properties in ckeditor using django
I want when I click on upload images I am directed directly to select images rather than being shown image properties box. Kindly help -
How do I update the records stored in my db using an html form as input?
I am very new to django and I have made an app that displays a different timetable for different user. I am stuck at this point where I can delete the records stored in my db but I am unable to update them through my html form. Is there a way to do this? Here are my files, models.py from pickle import TRUE from django.db import models from datetime import date from django.conf import settings class Timetable(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default = "", on_delete=models.CASCADE) subject = models.CharField(max_length=100) room_no= models.IntegerField() date = models.DateField(default=date.today) time = models.TimeField() semester = models.TextField() day = models.CharField(max_length=10, default="") views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required from .models import Timetable # Create your views here. def register(request): if request.method=='POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created, you are now able to login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def tt(request): if request.user.is_authenticated: tt = Timetable.objects.filter(user=request.user).order_by('day') return render(request, 'users/time_table.html', {'tt': tt}) else: return render(request, 'homepage/home.html') @login_required def tt_add(request): return render(request, 'users/tt_add.html') @login_required def newPage(request): user=request.user sem = request.POST.get("semester") sub = request.POST.get("subject") room_no = … -
Conditional query in django [closed]
Am worried that it may cause any problem, as am using conditional querying paramters. Here is my query: data = Project.objects.filter(user=user if user.role == 1 else user.staff_to_id) In this, staff_to_idis just a self reference to a user to represents that this is a staff. So if Role == 1 then Projects will be fetched using "user" and when Role == 2 or something else it will Project will be fetched using "user.staff_to_id" Is this a bad practice ? -
Revisions not creating in TestCase ( Django, django-reversion, tests)
Trying to cover with tests django-reversion functionality for my model, but versions are not created in test db, in manual creation from admin interface everything works fine. Model: @reversion.register() class RuleSet(ModeratedBase, AdminUrlMixin): """Ruleset of a given type of contest related to the contest""" name = models.CharField( max_length=64, help_text="Short name of the ruleset.", unique=True ) rules = models.JSONField( default=dict, help_text="Base rules dict for Ruleset", blank=True, null=True, ) default_for = models.ManyToManyField( "ci_contest.ContestType", help_text="Field specifies content types ruleset is default for", related_name="default_ruleset", null=True, blank=True, ) def __str__(self): return self.name def get_versions(self): return Version.objects.get_for_object(self) Test: class RulesetTestCase(TestCase): fixtures = ["core-defaults", "gamer-defaults", "ledger-defaults", "contest-defaults"] def setUp(self): call_command("createinitialrevisions") self.ruleset = RuleSetFactory() def test_ruleset_get_versions(self): self.assertFalse(self.ruleset.get_versions().exists()) self.ruleset.rules = str(fake.pydict()) self.ruleset.save() print(self.ruleset.get_versions()) self.assertTrue(self.ruleset.get_versions().exists()) Print Output: <VersionQuerySet []> -
I get an error when installing django with pipenv
I am trying to install django=4.0.1 on my mac with pipenv. (1) my python: /usr/bin/python3 (3.7.3) (2) my pipenv version: version 2022.1.8 (3) I just updated 'pip' But I get a message below [pipenv.exceptions.InstallError]: ERROR: Could not find a version that satisfies the requirement django==4.0.1 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, … -
Django python manage.py runserver is giving an error [closed]
I haven't been running my django project, which runs smoothly, for a month now. Now python manage.py i get these errors when i run runserver. What should I do? enter image description here -
Problem to transfer data from Django template to vue.js app
I am trying to make Django and Vue talk. I installed Vue-Cli with Vue3. Vue app is well displayed into the Django template, but I can't transfer data (Django data but also a simple string for testing) to the vue app. App.vue <template> <h1>{{ msg }} world</h1> </template> <script> export default { name: 'App', props: { msg: { type: String, default: 'test' } } } </script> <style scoped> </style> main.js import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app') This code shows "test world", instead of "Hello world". Thank you in advance for your help. -
How to add an image along with a post in Django from the admin panel so it'll show in my templates
I created a model for the post, I don't have issues with the body(blog post)but with the images how should I do it such that it'll reflect at the template class Post(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank=True) posted_by = models.CharField(max_length=50, default=False) image1 = models.ImageField(upload_to='images/', default=False) image2 = models.ImageField(upload_to='images/', default=False) image3 = models.ImageField(upload_to='images/', default=False) def __str__(self): return str(self.title) -
Object of type Response is not JSON serializable in rest framework
I'm trying to call one method response into another method in Django rest framework. views.py: @api_view(['GET','POST']) def GetCurrentRunningActivityForAudit(request, UserID): if request.method == 'GET': print("current running activity--userid--", UserID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set = cursor.fetchall() data = [] for row in result_set: TaskId=row[0] TaskName = row[1] Source = row[2] SID = row[3] type = row[4] data.append({ "TaskId": TaskId, "TaskName":TaskName,"Source":Source, "SID":SID, "type":type, "IsActive":GetCurrentSubTaskSTatus(TaskId)}) return Response(data[0]) return Response(data) I'm passing this method response to the above method response i.e.,. GetCurrentRunningActivityForAudit but it's show as Object of type Response is not JSON serializable def GetCurrentSubTaskSTatus(taskid): cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentTaskStatus] @taskid=%s',(taskid,)) result_set = cursor.fetchall() for row in result_set: IsActive =row[0] return Response({"IsActive":IsActive}) -
Why does bitbucket pipeline not find tests that run inside local docker container?
I have a repo that holds two applications, a django one, and a react one. I'm trying to integrate tests into the pipeline for the django application, currently, the message I'm getting in the pipeline is: python backend/manage.py test + python backend/manage.py $SECRET_KEY System check identified no issues (0 silenced). --------------------------------------------------------------- Ran 0 $SECRET_KEYS in 0.000s However, running the same command in my local docker container finds 11 tests to run. I'm not sure why they aren't being found in the pipeline My folder structure is like this backend/ - ... - app/ -- tests/ - manage.py frontend/ - ... bitbucket-pipelines.yml and my pipelines file: image: python:3.8 pipelines: default: - parallel: - step: name: Test caches: - pip script: - pip install -r requirements.txt - python backend/manage.py test -
Django custom editable email template with variable and saving db by users
I have started to learn 3 month ago django and I am newbie. I couldn't find thing anywhere that I want to do. I want to make custom email template form to editable and savable to db but at the same time user can use variable when create email template. How could I do that ? Thank you. enter image description here -
how to generate random passwords that change every 24 hours in Django
I'm trying to create a Django application in which only people with a pin number can enter. Is there a way in Django to generate a random pin every 24 hours and make this pin appear in the admin panel. -
How to fix "ERROR: Command errored out with exit status 1:" when I try to install web3
When I try to install web3, there is a error. How can I fix? enter image description here Thanks everybody for the support! -
Disabling and reassigning a new django token
I am planning to use "RestFrame TokenAuthentication" for django API requests. I want to give the Bearer Token to my client for accessing the API. The token needs to be disabled based on payment module. On a succesful payment, i needs to create a new token programatically and give it to the client. Is it possible to deactivate and renew with a new token when necessary ? Is it the best practice to use "RestFrame TokenAuthentication" for such a scenario ? -
Django: Create a Model from parsing a different model's field
I have a model A with several fields. One of the fields ("results") is a a dict-like string in my database (which is hardly readable for a human being). Can I create a separate Model that would basically parse that "results" field into its own fields, so I can have a separate table with fields corresponding to the keys and values from my "results" field from model A? Final goal is to make a Results table that shows all the information in a pretty and easy-to-read manner. class ModelA(models.Model): language = models.CharField(max_length=30) date = models.DateTimeField() results = models.CharField(max_length=255) This is how "results" field looks in my database (I cannot change this format): OrderedDict([('Name', 'Bob'), ('Phone', '1234567890'), ('born', '01.01.1990')]) I want to create something like this: class Results(models.Model): name = model.Charfield(max_length=100) phone= model.IntegerField() born = model.DateTimeField() What is the best way to do this? How do I take the info from the "results" field from ModelA and "put" it into the Results model? -
WSGIRequest is not callable 'blockchain project'
I'm working on a blockchain project, but I had a problem that I could not solve myself, and here I share all the details of the project. Mining a new block def mine_block(request): if request.method == 'GET': previous_block = blockchain.get_last_block() previous_nonce = previous_block['nonce'] nonce = blockchain.proof_of_work(previous_nonce) previous_hash = blockchain.hash(previous_block) blockchain.add_transaction(sender = root_node, receiver = node_address, amount = 1.15, time=str(datetime.datetime.now())) block = blockchain.create_block(nonce, previous_hash) response = render(request({'message': 'Congratulations, you just mined a block!', 'index': block['index'], 'timestamp': block['timestamp'], 'nonce': block['nonce'], 'previous_hash': block['previous_hash'], 'transactions': block['transactions']})) return render(JsonResponse(response)) ``` # Getting the full Blockchain ``` def get_chain(request): if request.method == 'GET': response = render(request({'chain': blockchain.chain, 'length': len(blockchain.chain)})) return render(request,JsonResponse(response)) Checking if the Blockchain is valid def is_valid(request): if request.method == 'GET': is_valid = blockchain.is_chain_valid(blockchain.chain) if is_valid: response = render(request({'message': 'All good. The Blockchain is valid.'})) else: response = render(request({'message': 'Houston, we have a problem. The Blockchain is not valid.'})) return render(request,JsonResponse(response)) Adding a new transaction to the Blockchain @csrf_exempt def add_transaction(request): #New if request.method == 'POST': received_json = json.loads(request.body) transaction_keys = ['sender', 'receiver', 'amount','time'] if not all(key in received_json for key in transaction_keys): return 'Some elements of the transaction are missing', HttpResponse(request(status=400)) index = blockchain.add_transaction(received_json['sender'], received_json['receiver'], received_json['amount'],received_json['time']) response = render(request({'message': f'This transaction will be … -
Fetch datetime from one model and post it as a day in another model AP
Need to fetch the Date entered in the below timesheet class api model and export it under another class model api as a day #Model for Date time picking class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date=models.DateField() Hours=models.TimeField(null=True) def str(self): return self.id #model for import date time as day class Days(models.Model): day_of_date= models.ForeignKey(Timesheet, related_name='date', on_delete=CASCADE) def str(self): return self.date #view for the model class DaywiseViewSet(viewsets.ModelViewSet): queryset=models.Days.objects.extra(where=["EXTRACT(day FROM day_of_date) <= %s"], params=[day_name]) serializer_class = serializers.Daysserializers throwing an error as "django.db.utils.ProgrammingError: can't adapt type '_localized_day'". Need help on creating a day wise report table using inputed date in a model. -
django settings.ABSOLUTE_URL_OVERRIDES requires the whole url to work
I'm maintaining a mezzanine/django application that has a couple of calls of get_absolute_url(). The always fail unless I put the following into my settings.py: ABSOLUTE_URL_OVERRIDES = { 'page_types.basicpage': lambda o: "http://<myHostName>:<myPort>/%s" % o.slug, 'page_types.registerdescpage': lambda o: "http://<myHostName>:<myPort>/%s" % o.slug, 'page_types.uutinen': lambda o: "http://<myHostName>:<myPort>/uutinen/%s" % o.slug, } According to django documentation this should also work ABSOLUTE_URL_OVERRIDES = { 'page_types.basicpage': lambda o: "/%s" % o.slug, 'page_types.registerdescpage': lambda o: "/%s" % o.slug, 'page_types.uutinen': lambda o: "/uutinen/%s" % o.slug, } But it doesn't. How can I get rid of myHostName and myPort in the settings file ? I'm currently working with django 2.2, python 3.7 and Mezzanine 5.0.0, but I've met this same issue with django 1.8, Mezzanine 4.x and python 2.7 -
Django-admin: show multi select field for JSONField
I have a model with a field channel (JSONField). I'm strong an array of string in db with channel. By default, a JSONField is shown as a textarea in django-admin. My goal is to somehow make channel a multi-select field that later converts to like this ["APP", "WEB"]. models.py @dataclass class ChannelTypes: WEB: str = 'WEB' APP: str = 'APP' class DiscountRule(models.Model): ... channel = models.JSONField(null=False, blank=False, default=list(astuple(ChannelTypes()))) My Approach: In forms.py, add custom fields (boolean) that only show up in admin form and are not stored in db. Something like this: class RuleAdminForm(forms.ModelForm): WEB = forms.BooleanField(required=False) APP = forms.BooleanField(required=False) Similarly, admin.py will populate the custom fields like this: def get_form(self, request, obj=None, *args, **kwargs): form = super(BaseDiscountRuleAdmin, self).get_form(request, *args, **kwargs) for i in obj.channel: form.base_fields[i].initial = True return form But this causes a problem that the custom field value persists after updating 1-2 times due to using base_fields[field_name].initial. Ideas for goal: Multi select option 1 -
How to save image inside a specific folder(folder name should be id)-DRF
I want to save image inside folder name same as id. Id is a automatic primary key.I tried that when i give post request i got none as a id. how can i achieve this???? models.py def upload_to(instance, filename): return 'organization/{instance}/logo/{filename}'.format(filename=filename, instance=instance.pk) class Organization(models.Model): code = models.CharField(max_length=25, null=False, unique=True) name = models.CharField(max_length=100, null=False) location = models.ForeignKey(Location, on_delete=models.RESTRICT) logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True) I know i cant take id before saving into db. there is any possible to do rename when i gave post request?? I got confused over this. Any help appreciable,... -
Select Objects related in third table
Say I have the models class A(models.Model): class B(models.Model): class C(models.model): b = models.ForeignKey(B) class D(models.Model): c = models.ForeignKey(C) a = models.ForeignKey(A) What would a ORM query look like to select all Bs that are related to C's that are related to a specific A through table D? -
I keep getting this error when deleting posts and comments on my django project TypeError: __str__ returned non-string (type User)
I keep getting this error when deleting posts and comments on my django project TypeError at /admin/blog/comment/ __str__ returned non-string (type User) Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/comment/ Django Version: 2.2.1 Exception Type: TypeError Exception Value: __str__ returned non-string (type User) Exception Location: /home/martin/.local/lib/python3.8/site-packages/django/contrib/admin/utils.py in format_callback, line 126 Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/martin/django-blog', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/martin/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] This is error from konsole no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj) TypeError: __str__ returned non-string (type User) [28/Jan/2022 09:46:12] "POST /admin/blog/comment/ HTTP/1.1" 500 135782