Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import model from another project
I have 2 Django projects with their Postgres databases. And they run on two different servers. They are models in each project which is usable by both projects. How can I import the model of Project1 in Project2? Regards, Gegham -
why do I get this Uncaught Typeerror error?
I have js code to update the cart, it works when the cart is on the same page as the add to cart button, but when the cart is on a different page it I got Uncaught Typeerror: cannot read property 'innerHTML' of null error. -
How to create multiple types of users using OneToOne field in Django?
I want to create 2 types of users - Customer and Company. I've already created a custom user shown below. These are their model files - class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, is_staff=False, is_superuser=False, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', is_staff) extra_fields.setdefault('is_superuser', is_superuser) return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username=None contact = models.CharField(max_length=100) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['password'] objects = UserManager() class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(_('email address') class Company(models.Model): """User model.""" user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField(max_length=100) company_email = models.EmailField(_('email address'), unique=True) I'm stuck at creating the serializer file. Most of the other answers use forms for creating multiple types of users, but I just want to create an API. Can anyone help me to create the serializer file for this? class UserListSerializer(serializers.ModelSerializer): class Meta: model = User … -
Upload, read an excel and save values in DB using Python and Django framework
How to save values to database after reading all the Excel data Is there any way By Defining a template to accept in excel -
Heroku not accepting Django app ! [remote rejected] main -> main (pre-receive hook declined)
I got the ! [remote rejected] main -> main (pre-receive hook declined) My app was made in Django and I put Django==3.2.5 Jinja2==2.11.2 in my requirements.txt file; the build is Python. In the error message it also said: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz I don't understand what this means. Isn't Heroku the host you are supposed to use with Django apps? I didn't use any other apps. I also use some Javascript, is that a problem? Please help; I really have no idea how to make this work. -
How to pass all value from one page to another page efficiently/elegantly in django
Well I am working on a project where there were multiple pages, now in django usually capture individual values and then pass it to next page via context parameter. For example if we want to go from page1 to page2, I would do something like this. from django.shortcuts import render def page1(request): value1 = request.session["value1"] value2 = request.session["value2"] context = {"value1":value1,"value2":value2} return render(request, "page2.html", context) Now this solution is working, but as the project grows number of variable is increasing day by day and in each page we have to capture the values and pass it to next page. And in the last page we are storing in the database. Is there any elegant way to pass the entire dataset or entire request to the next page so that and then the next page till the last page. In the last view will get the individual values and save it in database. Hope I am able to express my issue. Note:- There might be a scenario where the variable passed by page1 will be displayed in page2 HTML file (using jinja). -
Cannot connect to amqp://guest:**@127.0.0.1:5672//:
I want to create a progress bar for one of my functions. I call this function in views. I research and find that I should use Celery to make a progress bar. (I am doing some download processes and the user should track it) I found a tutorial and try to do the same but I get an error: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061] When target machine actively rejects n connection failed. I am developing this app in localhost and I am using sqlite for db. Where is my mistake and what should I do? settings.py ... CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = '127.0.0.1' functions.py class myFunction(): def __init__(self, user, password, url, port, db_password, username): .... @shared_task(bind=True) def send_download(self): progress_recorder = ProgressRecorder(self) for in_file in glob.glob(self.location + "\*\*.xyz"): try: i = 0 progress_recorder.set_progress(i+1, len(array), f'On iteration {i}') with open(in_file) as f: if os.path.getsize(in_file) > 0: ... function... time.sleep(0.02) i = i + 1 except: pass .... views.py ... task = (functions.myFunction(setup.username, setup.password, setup.url, setup.port, setup.db_password, username=request.user.username)) -
Multiple different foreign objects as "resources"
So say I have a model, Agenda: class Agenda(models.Model): ... resource_comments = models.Field... class ResourceComment(models.Model): comment = models.TextField() resource = models.ForeignKey... | GenericRelation Say I wanted resource_comment to be one or more of several other models, like.. Restaurant, PetrolStation, CarPark with a comment. So in a meeting agenda we might want to talk about a particular restaurant and a couple of petrol stations nearby. Whatever, it's a usecase. How would I go about this? Should I have a separate field for each..? That doesn't feel quite right... like I don't want class Agenda(models.Model): ... restaurants = models.... parking_lots = models.. petrol_stations = models.. ... I suppose I could have a model like... class Resource(models.Model): resource_id = Int resource_model = String # (e.g. Restaurant) comment = String # (a comment pertaining to resource from having the agenda meeting) Kind of also feels off as I then have to manually get the objects.. Like get restaurants_in_agenda(self): ids = self.filter(resource_model="Restaurant").value_list('ids') return Restaurant.objects.filter(id__in=ids) Or, is this OK? Another solution would be to make the Agenda the generic model, but I kind of don't want this field on all the business models... because.. what do I do then with the resource comment? class Agenda(models.Model): attendants … -
Django Model not recognising model fields using Serialiser Class Generic Views
I am trying to get a list of templates from a Django model, but I always get an error. Below is the error whenever I attempt to retrieve the list of job templates. I get this error because it doesn't recognise the field template_name. AttributeError: Got AttributeError when attempting to get a value for field template_name on serializer ListJobTemplateSerializer. | The serializer field might be named incorrectly and not match any attribute or key on the Job instance. | Original exception text was: 'Job' object has no attribute 'template_name'. Job Model: class Job (Dates, ID): name = models.CharField(max_length=255, validators=[name_validation]) is_remote = models.BooleanField(default=False) company = models.ForeignKey(to="companies.company", related_name="%(class)s", on_delete=models.CASCADE) Template Model: class JobTemplate(Dates, ID): template_name = models.CharField(max_length=255) jobs = models.ForeignKey(to="jobs.Job", related_name="%(class)s", on_delete=models.CASCADE) objects = BulkUpdateOrCreateQuerySet.as_manager() class Meta: db_table = 'job_template' def __str__(self): return name class ListJobTemplateSerializer(serializers.ModelSerializer): """List all templates of a job.""" job_title = serializers.CharField(source="name") class Meta: model = JobTemplate fields = ["id", "job_title", "template_name"] -
Django Form make calculations
Hi, a im new in Django. My first application is a simulator for bank loan, just for learn, not professional. I have created in models.py a class named EntradasMaisAlimentos with the following struture: class EntradasMaisAlimentos(models.Model): valor = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0.00) divisao = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0) carencia = models.PositiveIntegerField(default=0) taxa = models.DecimalField(max_digits=7, decimal_places=2, blank=False,default=0.0) Than i write in forms.py: from django import forms from .models import class simulaForm(forms.ModelForm): class Meta: model = EntradasMaisAlimentos fields='__all__' The form is rendered for: from django.shortcuts import render from django.http import HttpResponse from PronafMaisAlimentos.forms import simulaForm def index(request): dadossimulacao=simulaForm() dados={ 'dadossimulacao': dadossimulacao } return render(request, 'index.html', dados) Please, dont think it is a silly question, but how i can get the values inserted in form input by the user and make some calculations and than show the results in a new template named results.html? -
Data Exploration in django
I am new to django and just started building a database of some data I have. The next step would be to create a GUI that allows the user to explore the data from the database models. I was doing some research online and came across pivottable.js https://github.com/nicolaskruchten/pivottable , which allows the integration of pivot tables and charts, which seems like a decent solution, instead of building the GUI from scratch! How can Integrate it in my django project? -
why use put method if I can use post
how exactly http methods work. the both view function do the same thing django code: //post method def create1_post(request): if request.method=="POST": any_model=AnyModel(title="example") any_model.save() //put method def create2_post(request): if request.method=="PUT": any_model=AnyModel(title="example") any_model.save() I read a lot about http methods ,But all I learned is PUT method is for update or create resource and POST method is for create resource Now I am confused . if I can edit and create models with python why I need to use put or any other http methods -
Save different instances on different get request in ajax
I am building a simple blog app and I made a view to save the instance or update the instance in model field. So, I am getting request.GET of button But It was working only when clicks on that particular class. so, I made a another elif statement to get another button But it is not working second not first. What I am trying to do ? :- I am trying to update the instance in model on different button click, like first button will update "First" in model and second button will update "Second" in model. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=1000) recommend_name = models.CharField(max_length=1000) views.py def save_instance(request, user_id): profile = get_object_or_404(Profile, user=user_id) if request.GET.get('submit') == 'first': profile.recommend_name = "First" profile.save() return redirect('home') elif request.GET.get('submit_2') == "second": profile.recommend_name = "Second" profile.save() return redirect('home') template.html <form method="GET" class="myForm" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="idForm{{user.id}}"> <button type='submit' name="First">Save First</button> </span> </form> <form method="GET" class="second_form" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="second_form{{user.id}}"> <button type='submit_2' name="second">Save First</button> </span> </form> <script> document.addEventListener('DOMContentLoaded', function() { window.addEventListener('load', function() { $('.unpro').submit(function(e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: {'submit': 'first'}, dataType: 'json', method: … -
Class based views in Django
I am new to Django and I am finding it difficult to understand the nuances of class-based views. How can I go about understanding the class-based views with ease. If there are any good resources that would help me with the basic understanding of class-based views please share them. Thank you!! -
How to choose Heroku dyno type and quantity
I have an app that is currently just using the free dyno tier but needs an upgrade. My app has several clock process jobs scheduled all day long, making API calls, sorting through and manipulating data, and last month I went past my allotted hours. I've read through all the documentation and understand the concept of dyno 'containers'. But I guess I don't really understand how much each dyno can handle and how many/ what types I should use to ensure the quality of my site's performance and all the jobs get completed. Any suggestions, tips, experiences would be great. Thanks! -
Django template inheritance is not working inside the folder file. How to do?
I am extending base.html inside the folder file. My root file name is base.html and I want to extend base.html inside the folder file. base.html(mainfile) -credential(foldername) --login.html(filename) I am trying like this {% extends '././base.html' %} {% block login %} {% endblock %} -
Django Javascript append options
In my class in models.py I have a field: names = models.TextField(max_length=40, choices=sektor, default="Adam", verbose_name="Name") sektor = ( ("Adam", "Adam"), ("Tom", "Tom"), ) When I change an option in my page, I run the following script <script type="text/javascript"> var endpoint = '/call_jquery_sektor/' var sektor = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ sektor = data.sektor //loop $(sektor).each(function(i) { $("#id_names").append("<option>" + sektor[i] + "</option>") //append options }) }, error: function(error_data){ console.log("error") console.log(error_data) } }) </script> I get all data, writen as two elements of each tuple, in one row. I would like to clear all previous options and when I run script I would get list of all names, each name single time and only 1 in 1 row. I get: Adam, Adam, Tom, Tom I would like to get: Adam Tom -
Django, how upload file into newly created folder
I'm Trying upload file into folder, but folder created as soon as take request from client -
Django Heroku Application Error (Need Help)
I have been looking for this answer for over days and have not found the right one yet so finally decided to make a question. My code successfully deployed on the heroku but I got this Application Error. When I run the cmd heroku logs --tail, it said H10 code error. I looked for the solution on google and mostly it said that have an issue in the Profile file. But my Procfile is ok. When I deployed it said, remote: -----> Discovering process types remote: Procfile declares types -> web like this. Here is my Procfile: web: gunicorn advamedservice.wsgi And I saw people say that the name in the Procfile should be the same as the project name and also in the wsgi file. So I look for it and the name is the same nothing wrong. I really need this to work perfectly fine on the internet. So please help me. -
ValidationError "value must be a decimal number"
I have a model class FunderProgramMember(models.Model): buyer = models.IntegerField() supplier = models.IntegerField() discount_rate = models.DecimalField(max_digits=3, decimal_places=2) In my serializer I am trying to get the discount field: discount_rate = FunderProgramMember.objects.values('discount_rate').get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer) Even if I replace my filter "get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer)" with pk=2 I still receive the following validation error: ["“{'discount_rate': Decimal('0.25')}” value must be a decimal number."] It appears to get a decimal value. How do I fix this error? -
HTML & CSS - label position and size changes when click on edit
I have 4 labels and one save/update button depends on when user want to edit or save it functionality is working fine but the button and labels moves when user click on edit and also i want it to be of same equal label size .I have tried out but i'm not getting the expected one.I dont know where im going wrong all i just edited and changed the container size. When i removed the save/update button the label didnt moved it sticked to the same position but the lable size differs.I'm using django as backend but I haven't specified anything for the frontend.it just completely html css n js. without button when user saves when user edits html: <div class="container-l" id='firstcontainer'> <div class="container-fluid"> <div class="fade-in"> <div class="card"> <div class="card-header">User's Details <span class="badge badge-info mfs-2"></span> <div class="card-header-actions"><a href="#" target="_blank" class="card-header-action"> <small class="text-muted"></small></a></div> </div> <div class="card-body"> <br> <div class="container-md" id='firstcontainer'> <form action=" " method="POST" autocomplete="off"> {% csrf_token %} <!-- <div class="container-md"> --> <!-- <h4 id='text' align='center'>User Details </h4> --> <div class="row"> <div class="row mb-3"> <div class="col" id='c1'> <small> Email address</small></div> <div class="col" id='c2'><small> Username</small></div> <div class="col" id='c3'><small> Select Format</small></div> <div class="col" id='c4'><small>Select Timezone</small></div> </div> </div> <!-- <div class="container-md"> --> <!-- <div … -
Cannot integrate 'ckeditor_wiris' plugin into django-ckeditor in custom toolbar configuration
I am using django to make a science related blog site where I am using django-ckeditor as the richtext editor. I encountered the following problem: I am trying to integrate the 'ckeditor_wiris' external plugin in custom toolbar. Other external plugins - 'Codesnipet' and 'Symbol' are working fine but 'ckeditor_wiris' is not visible on the toolbar. CKEDITOR_CONFIGS = { 'default': { 'height':'250px', 'width':'100%', 'tabSpaces': 4, 'toolbar': 'Custom', 'toolbar_Custom': [ ['Smiley', 'CodeSnippet', 'Symbol', 'ckeditor_wiris'], ['Bold', 'Italic', 'Underline', 'RemoveFormat', 'Blockquote'], ['TextColor', 'BGColor'], ['Link', 'Unlink'], ['NumberedList', 'BulletedList'], ['Maximize'] ], 'extraPlugins': ','.join(['codesnippet', 'symbol', 'ckeditor_wiris' ]), } } WIRIS plugin not visible on toolbar Though if I use the 'full' toolbar instead of 'custom' then 'ckeditor_wiris' is visible on the toolbar. What can I do to make it visible on the toolbar in custom settings? -
How to solve TypeError at admin page?
I am pretty new to Django and I was just following along witht the tutorial. I worked on adding a leads page, and coudn't load the admin page after adding the leads page. I am getting a message like this TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\urls\resolvers.py, line 460, in _populate Python Executable: C:\Users\Dell\Desktop\prog\programa\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\Dell\\Desktop\\prog', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Dell\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\\Users\\Dell\\Desktop\\prog\\programa', 'C:\\Users\\Dell\\Desktop\\prog\\programa\\lib\\site-packages'] -
how to get the path of any folder i want when i select them in django
I want the user to be able to get the path of any directory so that my code can handle the dicom images in that directory. is there any way? I tried using tkinter but its window is always showing out before I get on my web. enter image description here -
Django makemessages fails both with django-admin and manage.py
I have a fresh Django project with no third-party apps installed. I'm trying to create a multilingual setup, with from django.utils.translation import gettext_lazy as _ in my Python files and {% translate %} in my templates. When I try to extract the messages, I get an error. (venv) d:\dev\py\filfak\src>py manage.py makemessages -l es processing locale es CommandError: errors happened while running msgmerge msgmerge: unrecognized option `--previous' Try `(null) --help' for more information. Somebody has an idea why does this happen? And, more important, how to solve it? If it helps somehow, I'm using Python 3.9.6 and Django 3.2.8 on Windows.