Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to environment variables in Heroku?
I've been stuck on this for ages and I can't find a solution. I've set up environment variables in the ~/.zshrc file and exported them correctly. Now when I try these commands for heroku setup it works for the email address but when I enter it for the password it removes the '!' at the end of my password. input: heroku config:set EMAIL_HOST_USER="myemail@gmail.com" heroku config:set EMAIL_HOST_PASSWORD="mypassword!" output: Setting EMAIL_HOST_PASSWORD and restarting ⬢ <app-name>... done, v45 EMAIL_HOST_PASSWORD: mypassword Can anyone explain why this may be happening? I have also tried, heroku connfig:add .... but the exclamation mark is also removed.. -
Method not allowed in django when i clicked the register form?
Method Not Allowed (GET): /customerregister/register Method Not Allowed: /customerregister/register [28/Jan/2022 09:29:50] "GET /customerregister/register HTTP/1.1" 405 -
How to write unit test for url shortener app using pytest?
<https://github.com/coderaki17/url_shortener_app/tree/master > I have attached my git repo above kindly help me out to write pytest for my code . -
Customize Django FilterSet: Create custom filter
I have a document table (django-tables2) and a FilterSet (django-filter) to filter it. That works fine in general. I want to create a custom ModelChoiceFilter (or ChoiceFilter) to display the elements in a two level hierarchy (a tree with parent nodes and one level of children): + Category 1 + Subcategory 1.1 + Subcategory 1.2 + Category 2 + Subcategory 2.1 + Subcategory 2.2 There is no need to expand and collapse the tree, i just want to show them ordered by category and rendered a little differently if they are first or second level. There are never more than two levels present and each top level component has at least one child. My current FilterSet looks like this: class DocumentFilter(FilterSet): title_name = CharFilter(lookup_expr='icontains') place_name = CharFilter(lookup_expr='icontains') source_type = ModelChoiceFilter(queryset=SourceType.objects.all().order_by('type_name')) doc_start_date = DateFromToRangeFilter() class Meta: model = Document fields = ['title_name', 'source_type', 'place_name', 'doc_start_date'] My model for the SourceType is as follows: class SourceType(models.Model): type_name = models.CharField(verbose_name="archivalienart", max_length=50,) parent_type = models.ForeignKey('self', verbose_name="übergeordnete Archivalienart", on_delete=models.CASCADE, null=True, blank=True, related_name="child_type",) The filter form template is as follows: {% load bootstrap4 %} <form action="{{ request.path }}" method="get" class="form form-inline"> <i class="fas fa-filter"></i>&nbsp; {% bootstrap_form filter.form layout='inline' form_group_class='my-small-form' %} &nbsp; {% bootstrap_button '<i class="fas fa-filter"></i>' … -
Django Page error takes no argument when click on link to it
I have been struggling with one of my pages in django. Basically I a making a graph (nodes and edges) where you can add remove nodes through forms. I have a graph model (GraphDetail) which requires nodes, and I am building the node form (GraphCreateNode) that adds nodes to the graph. However the link does not work. It says that GraphCreateNode does not take any arguments. Now CreateGraphNode needs the id of the graph it is going to be added to, whether that is sent via the url or stored and accessed in session I do not have a preference. Right now I am trying via the url. And as said I get an error, and I cannot see where I need to fix it, which is why I am asking all of you. Error Message: TypeError at /graphs/graph/74921f18-ed5f-4759-9f0c-699a51af4307/graph_add_node/ GraphCreateNode() takes no arguments So I looked around here to see what I could find: What is a NoReverseMatch error, and how do I fix it? was quite informative but not quite enough. Then I found TypeError: CraiglistScraper() takes no arguments, whilst it was about Selinum it mentioned something about a constructor. My class does not have a constructur, but does … -
Custom button in Class based UpdateView django
Problem: My UpdateView looks the same as my CreateView. I would like to change the submit button from "Check" to "Update". Here are my views in the views.py file: class CapsUnifCreateView(CreateView): template_name = 'capsules/uniformity_form.html' model = models.Uniformity fields = ( 'caps_name', 'mass_1_caps_empty', 'mass_20_caps_full', 'mass_max1', 'mass_min1', ) class CapsUnifUpdateView(UpdateView): fields = ( 'caps_name', 'mass_1_caps_empty', 'mass_20_caps_full', 'mass_max1', 'mass_min1', ) model = models.Uniformity Note, that I do not use a separate template for the UpdateView. Something like {% if CreateView %} Check {% else %} Update {% endif %} in the html file would be nice, but I don't know how to implement it. Thanks in advance! -
CSRF verification failed. Request aborted. only for login page
I am creating a To-Do application as my first project in django. Everything works fine when I run on local server but when I deploy it to heroku, CSRF token is not working on login page only. The app is deployed here. Issue: If we try any random or existing user on the login page, it shows CSRF verification failed BUT if we open /register endpoint i.e. Register a user on the app, it creates user and logs in to that user correctly at them time. Whole app features like adding a new task, editing a task, deleting a task works fine until I logout that user. When I come back to the login page again, I am not able to login with any user account. I've tried a lot of different methods like services in Procfile, environment variables for SECRET_KEY, providing meta tag in the main.html for csrf token using content={{ csrf_token }} but no luck. Codes: settings.py # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DEBUG', False) ALLOWED_HOSTS = [ '.herokuapp.com', '127.0.0.1:8000' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', …