Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I remove the None or set the good status for a celery task?
Hello when I launch a celery task I got that for instance : [2021-09-22 22:11:26,878: INFO/ForkPoolWorker-7] Task Todos.celery.launchalert[886eb5a6-66cf-4759-a208-7245aca9882b] succeeded in 26.386354280999512s: None If the task is ok or have errors I got None and succeeded ... How can I do to either remove that either show the right logs ? Thank you very much ! -
Django Migration Modify Inherited Default
I have a model class in Django Parent with a subclass Child. Parent has a boolean field foo which defaults to True that Child inherited. I'd like to migrate my Child class so that All new Child objects have a default of False for the foo field All existing Child objects have the foo field set to False How can I achieve this in Django? -
Can I extend my Django project with FastAPI without changing the django app?
I have developed a Django e-commerce platform and then realized that I need to use FastAPI with it in order for my website to accept payments from the square payment system. I have looked through their documentation about how to do it, and they use fast API. However, I have no experience using Fast API at all. Is there a way for me to set up this fast API functionality without changing my Django project (so that it runs "together" with my Django app)? Or maybe there is another way which you would recommend me to use? -
Django static file problem. Clicking on the files downloads
sorry for my bad english. My index.html file cannot find the files in the static folder. When I view the page source, I click on the css file and I get different errors from time to time. Sometimes I get 404 error when I click on css link. Sometimes when I click on the css file, it downloads the file. Settings.py: import os from pathlib import Path DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates/")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Urls.py: from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path from django.urls.conf import include from django.conf.urls.static import static urlpatterns = [ path('', include("home.urls"), name="anasayfa"), … -
Django is not populating correctly an specific form using a Queryset
I have created two models Leads and Deals, and I have coded some logic such that if you click a button the Lead becomes a Deal, so what I want it is that a new form is presented to the user but that form already contains the information from the Leads model. @login_required def close_lead(request): if request.method == 'POST': deal_form = DealForm(request.POST) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, 'Error updating your Form') else: id = request.GET.get('project_id', '') obj = get_object_or_404(Leads, project_id=id) print(obj.expected_revenue) form = NewDealForm(request.POST or None, instance=obj) return render(request, "account/close_lead.html", {'form':form}) I have done some debug and printed to the console the queryset and the information is fine, so the queryset is no the problem, the problem is that the NewForm doesn't prepopulate the new values. models.py (only 2 models shown) class Leads(models.Model): CHOICES = ( ('Illumination Studies','Illumination Studies'), ('Training','Training'), ('Survey Design','Survey Design'), ('Software License','Software License') ) STATUS = (('Open','Open'), ('Closed','Closed'), ('Canceled', 'Canceled') ) project_id = models.BigAutoField(primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent") created_at = models.DateTimeField(auto_now_add=True) point_of_contact = models.ForeignKey(Client, on_delete=models.CASCADE) expected_revenue = MoneyField(max_digits=14, … -
Django Combine Many Unrelated Models on Related Foreign Key
I have 3 models T, E, Q such that: class E(Model): name_e = CharField() class T(Model): name_t = CharField() e = ForeignKey(E) class Q(Model): name_q = CharField() e = ForeignKey(E) I also have Serializers for each: class ESerializer(ModelSerializer): class Meta: model = E fields = '__all__' class TSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' class QSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' For one E row there can be many T and Q rows. I can make a query such that t = T.objects.filter(e__id=1).all() serialized_t = TSerializer(t, many=True).data And the output of serialized_t will look something like: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}} ] My question is how could I combine it so that I can include Q in the query above to create an output for the T query which would also include all Q's where e_id=1 and hence it would look something like this: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]} ] I don't mind if this can be done in-query itself, or if it involves some appending to the SerializedT object, as long as … -
How do I use queryset.upgrade in a Django Admin action?
I have a Django Admin action which updates values (including foreignkeys) in a model. The code is: def staff_reset(self, request, queryset): updated=queryset.update(regstatus='registered', medicalform__medform_status='required', staffmonitoringform__monitoring_status = 'required', staffreleaseform__release_status ='required', staffethics__ethics_status = 'required', staffethics__i_agree=False) self.message_user(request, ngettext( '%d staff registration was successfully reset.', '%d staff registrations were successfully reset.', updated, ) % updated, messages.SUCCESS) staff_reset.short_description="Reset Staff Registrations" But I get an error message saying "Order has no field named 'medicalform__medform_status'". Any ideas on if I can use the queryset.update() with foreignkeys? Thanks in advance. -
How read files with load_workbook in heroku
My application is reading a file from my computer and this works fine in localhost mode. But in heroku I need to find and read this file, but it is not working: def carregaGeneroEspecie(self): wb = load_workbook(filename='/pages/setup/2021-02-12 All-DungBeetle-species_FVZ-Collection.xlsx') sheet2 = wb['Sheet1'] return sheet2 Is it possible to read xlsx files in heroku? How to find it? -
Issues with deployment on heroku from Django
I am needing help with deploying my Django app to heroku. My Django project works locally, but when I deploy to Heroku, the app crashes and cant load the index/home page. I'm not quite sure what the issue is with the GET request. here are the heroku logs --tail: 2021-09-22T20:25:16.636085+00:00 heroku[web.1]: Starting process with command `gunicorn solarsystem.wsgi` 2021-09-22T20:25:17.678063+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-09-22T20:25:17.678545+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Listening at: http://0.0.0.0:34748 (4) 2021-09-22T20:25:17.678598+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Using worker: sync 2021-09-22T20:25:17.681856+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [INFO] Booting worker with pid: 7 2021-09-22T20:25:17.685446+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [ERROR] Exception in worker process 2021-09-22T20:25:17.685447+00:00 app[web.1]: Traceback (most recent call last): 2021-09-22T20:25:17.685455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-09-22T20:25:17.685455+00:00 app[web.1]: worker.init_process() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-09-22T20:25:17.685456+00:00 app[web.1]: self.load_wsgi() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-09-22T20:25:17.685457+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-09-22T20:25:17.685457+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-09-22T20:25:17.685458+00:00 app[web.1]: self.callable = self.load() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-09-22T20:25:17.685458+00:00 app[web.1]: return self.load_wsgiapp() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-09-22T20:25:17.685459+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-09-22T20:25:17.685459+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-09-22T20:25:17.685460+00:00 app[web.1]: … -
How to redirect to object returned by Ajax autocomplete in django?
I'm fetching objects from the database by using Ajax autocomplete on a common search input field. I would now like to make the rendered results clickable and redirect to the page of the object. // jQuery autocomplete search $(function () { $('#header-search-bar').autocomplete({ // data to be passed from backend source: '/autocomplete/', // length of search string minLength: 3, // redirect to pollers select: function(event, ui) { location.href="poller/" + ui.item.poller_id; } }) }) // Django view / backend query to database def autocomplete(request): if 'term' in request.GET: qs = Poller.objects.filter(poller_text__icontains=request.GET.get('term')) pollers = list() for poller in qs: pollers.append(poller.poller) return JsonResponse(pollers, safe=False) else: pass // Model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_text =models.CharField(min_length=250) // Redirect url to single Poller path('poller/<uuid:poller_id>/', render_single_poller, name='single_poller'), So the desired url for a redirect would be poller/poller_id/ The above jQuery approach renders the poller_text of each object but doesn't redirect to it. So how can I additionally "build" the required url and redirect to it as I don't know how to append more to the list than poller_text. Right now it returns http://127.0.0.1:8000/pollboard/poller/undefined -
How do I use a related name field in a Q object
I am building a search screen, and one of the query choices is to search by "string". So I am trying to get all instances of a string in a primary model AND any instances of the same string in a related model - but - I only want the related instances that exist with the string. For example - one could search for the word "Tiger" in the Program title field, library field, remarks field and also in the Segment Author field, title field, library field etc... So that being said - here's the models. class Program(models.Model): air_date = models.DateField(default="0000/00/00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) title = models.CharField(max_length=190) library = models.CharField(max_length=190, blank=True) remarks = models.TextField(null=True,blank=True) class Segment(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', ) title = models.CharField(max_length=190, blank=True) author = models.CharField(max_length=64,null=True,blank=True) voice = models.CharField(max_length=64,null=True,blank=True) library = models.CharField(max_length=190) summary = models.TextField() My Q object for Program looks like this... q_words = [] q_words = query.split() query_prog_title_array = reduce(or_,[Q(title__icontains=w) for w in q_words]) query_prog_library_array = reduce(or_,[Q(library__icontains=w) for w in q_words]) query_prog_remarks_array = reduce(or_,[Q(remarks__icontains=w) for w in q_words]) program_results = Program.objects.filter( query_prog_title_array | query_prog_library_array | query_prog_remarks_array).order_by('id').distinct() My Q object for Segment looks like this... q_words = [] q_words = query.split() query_title_array = … -
Django Rest Framework Image/File upload
I'm aiming at having images uploaded via and endpoint unto which i've looked at most of the previous questions and answers but i haven't suceeded on having this work. Besides the django rest framework I'm using drf-flex-fields and versatileimagefield packages Below is my code: Post model; class Post(models.Model) content = models.TextField() image = models.ManyToManyField(PostImage, related_name='posts_images') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( "profiles.Profile", on_delete=models.CASCADE, null=True, related_name='posts') -
React Pagination Factory and Django API Pagination
My goal is to paginate the results for react-bootstrap-table2's pagination with a Django api. My problem is that the table is taking data from a results array from the api endpoint. Thus leading me to set the state with the data within the results. The api currently limits an offset of 100 per request. Instead I would need the count, next endpoint, and prev if applicable. How can I get the next bit of data from the offset? Another issue related, when I query without adding .results on setMealDashboard(data) I get undefined and it's expecting an array, despite adding results.id to the columns. How can I get around this so it's all in my mealDashboardData state? Pagination Const: const pagination = paginationFactory({ sizePerPage: 50, showTotal: true, }); My data: count: 600 next: "http://localhost:8000/api/meals/?limit=100&offset=100" previous: null results: [..... const [mealDashboardData, setMealDashboard] = useState([]); useEffect(() => { const getMealDashboard = async () => { try { const { data } = await fetchContext.authAxios.get( `/api/meals/` ); setMealDashboard(data.results); console.log(data); } catch (err) { console.log(err); } }; getMealDashboard(); }, [fetchContext]); My component: <ToolkitProvider bootstrap4 keyField="id" data={mealDashboardData} columns={columns} search > {(props) => ( <div> <div className="search float-right"> <SearchBar {...props.searchProps} /> <button type="button" className="btn" onClick={() => props.searchProps.onSearch('')} … -
how to run django project using docker
I am trying to create a docker container to run my django project. Following different other questions, I managed to obtain a successful build with docker. I have created a Dockerfile, docker-compose and I have created a local postgres database. and if I run the project from the entrypoint (chain of makemigration, migrate and runserver) the service can be reached. the problem is when I dockerize the project. my docker-compose.yml file is version: "3.9" services: db: restart: always image: postgres:12.0-alpine volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=signalcrossingrestapi - POSTGRES_USER=$POSTGRES_LOCAL_USER - POSTGRES_PASSWORD=$POSTGRES_LOCAL_PASSWORD env_file: - ./.env web: restart: always build: dockerfile: Dockerfile context: . volumes: - .:/code ports: - "8000:8000" depends_on: - db env_file: .env command: ./run.sh volumes: postgres_data: driver: local and the dockerfile is FROM python:3.8-slim # set up the psycopg2 RUN apt-get update && apt-get install -y libpq-dev gcc postgresql-client ENV PYTHONUNBUFFERED=1 ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" WORKDIR /code ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /code/ RUN pip install psycopg2==2.8.3 RUN pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt RUN apt-get autoremove -y gcc EXPOSE 8000 when I execute docker-compose up --build it is successful but when I open localhost:8000 I cannot reach … -
Using Git on DigitalOcean server: error: The following untracked working tree files would be overwritten by merge
I am using Django for my site on DigitalOcean. So, I had to delete the migration files for one of my apps (accounts) and run makemigrations again. I don't really recall when or why, but it has caused this error when I pull from origin: $ git pull origin master From https://github.com/... ... error: The following untracked working tree files would be overwritten by merge: accounts/migrations/0001_initial.py Please move or remove them before you merge. Aborting Locally, my accounts app has only one migration: accounts > migrations __init__.py 0001_initial.py When I run git status on the server, I get a lot of untracked files, and I can see two migrations related to my accounts app (even though locally I only have one migration file in the accounts/migrations) as well as other untracked files (not related to accounts app): On branch master Untracked files: (use "git add <file>..." to include in what will be committed) accounts/migrations/0001_initial.py accounts/migrations/0002_alter_user_id.py ... Given that I don't want to mess with the production database, I don't wish you to change the migration files on the server to replicate the local migration files unless this does not cause any problem for my server. So, how should I resolve … -
Django form doesn't save value in multiple choice fields
I'm using Django's ModelForm and for no reason my form doesn't save the value of multiple choice fields. This is my models.py: class CaptureVersion(models.Model): id_capture = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Nom Disseny") int_reference_number = models.CharField(max_length=15, unique=True, blank=True, null=True, verbose_name='IRN') capture_version_id_provider = models.ForeignKey(Provider, on_delete=models.CASCADE, db_column='id_provider', verbose_name='Proveïdor') associated_register = models.CharField(max_length=150, blank=True, null=True, verbose_name='Registre associat') start_date = models.DateField(blank=True, null=True, verbose_name='Data Alta') end_date = models.DateField(blank=True, null=True, verbose_name='Data Baixa') target_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Regions diana (Mb)') probe_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Sondes (Mb)') sections = models.ManyToManyField(Section, blank=True, verbose_name="Secció") responsibles = models.ManyToManyField(Responsible, blank=True, verbose_name="Responsable/s") class Meta: ordering = ['start_date'] db_table = 'capture_version' And my forms.py: class FormulariCaptura(ModelForm): class Meta: model = CaptureVersion fields = ("name", "int_reference_number", "capture_version_id_provider", "associated_register", "start_date", "end_date", "target_size", "probe_size", "sections", "responsibles",) The problem are the fields sections and responsibles which are foreign keys. When I select one of the values of the dropdown list in the form, there's no problem and the entry is saved with no apparent errors but the value in the table for that field is -. But if I do it in the admin, it works or if I edit the entry with UpdateView. This worked yesterday and I didn't change anything... My views.py: def … -
Django - link to url from different apps redirecting to the same links
I have three apps in the project which have different templates with different URLs but one I go the someone app template page then the links on this page are showing to other app URL whereas I have different apps with different URLs name When I changed the name of templates files of every app then working fine. Please give me a solution what is the problem getting with the same name file in a different app. Thanks Admin App urlpatterns = [ path('login', views.login, name='admin_login'), path('register', views.register, name='admin_register'), path('logout', views.logout, name='admin_logout'), path('dashboard', views.dashboard, name='admin_dashboard') ] templates ----pages ------login.html ------register.html Customer App urlpatterns = [ path('login', views.login, name='customer_login'), path('register', views.register, name='customer_register'), path('logout', views.logout, name='customer_logout'), path('dashboard', views.dashboard, name='customer_dashboard') ] templates ----pages ------login.html ------register.html When I changed to templates ----pages ------customer_login.html ------customer_register.html Then working but I can not find an issue why is giving this type of error whereas I have a different app with different vies, templates, URLs, and pathname where I'm redirecting. Thanks in advance -
Passing data from javascript to python view in Django using ajax and saving it to database
I have created review section where user enter their reviews and then it gets saved to database. My problem here is ajax section, what i want is that on click of submit button the data which is stored in JavaScript variable get passed to python view in Django using ajax and get updated to MySQl. Html code of review <section> <div class="modal hidden"> <button class="exit">&times;</button> <div class="reviewer-detail"> <img class="review_img" src="{% static 'Images/Farmer3.jpg' %}"> <p class="review_name">Name:<span class="rn">Abhiraj Yadav</span></p> </div> <textarea type="text" placeholder="Enetr your review..." class="review_input" ></textarea> <button class="review_submit">Submit</button> </div> </section> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> JavaScript side code const submitReview=document.querySelector(".review_submit") submitReview.addEventListener("click",function(e){ e.preventDefault() const input=inputReview.value; console.log(input) $.ajax({ url:'http://localhost:8000/FarmaHome/review', type:"GET", headers:{ 'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content') }, data:{'userInput':input}, success:function(){ alert(`Thankyou ${user_data.name}`); } }) }); url section from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('your-orders/', views.customerOrder), path('',include('django.contrib.auth.urls')), path('userlogin/', views.userLogin), path('register/', views.register), path('pesticide/',views.pesticide), path('fertilizers/',views.fertilizers), path('review/',views.review), ] Python view def review(request): mydb = mysql.connector.connect(host="localhost", user="root", password="windows10", database="farmaproduct") curr = mydb.cursor() sql = "select * from efarma_customer" curr.execute(sql) input = request.GET.get("userInput") try: curr.execute(f"update efarma_customer set review={input} where link_id={user_id}"); except: mydb.rollback() mydb.close() return render(request, 'efarma/home.html', {'input': input}) Any help would be appreciated thanks in advance. -
Is there any need of otp verification in Stripe while creating a charge?
I am integrating stripe with Django. It is working fine with the test cards. All payments are done successfully without otp verification. views.py code . . . data = request.POST #post request by form card = stripe.Token.create( card={ "number": data['card_no'], "exp_month": data['exp-date'][1:].split("/")[0], "exp_year": "20"+data['exp-date'][1:].split("/")[1], "cvc": data['cvv'], } ) customer=stripe.Customer.create( name = data['fn']+data['ln'], email = data['email'], source=card, address={ 'line1': '510 Townsend St', 'postal_code': '98140', 'city': 'San Francisco', 'state': 'CA', 'country': 'US', }, ) charge=stripe.Charge.create( amount=int(data['amount'])*100, currency='usd', customer=customer, description="testing", ) . . . Is this a right way of integrating stripe? PS: I am not using stripe form and stripe js/css for this, instead i am using a normal html form. -
Integrate the text editor in django blog site
Visit the site make account if you don't have an access on it. I hope you will inspired from this most beautiful text editor, I want to integrate this type of editor in my blog where users can write their articles, how can I integrate it? I use TinyMce editor right now but it has not a better experience.. Remember one thing also tell me that, if user will upload images where the images will save? -
how to add + button for foreign key , similar to django's admin
i'm trying to implement + button for foreign key select field , if the foreign key doesnt exist instead of going to another page just pop up a form page to add new entry for the foreign key , i've implemented but its full size and dont go to the previous page when i submit the form : this is what i tried class RelatedFieldWidgetCanAdd(widgets.Select): def __init__(self, related_model, related_url=None, *args, **kw): super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw) if not related_url: rel_to = related_model info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = 'admin:%s_%s_add' % info self.related_url = related_url def render(self, name, value, *args, **kwargs): self.related_url = reverse(self.related_url) output = [super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)] output.append('<a href="%s?_to_field=id&_popup=1" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \ (self.related_url, name)) output.append('<img src="%sadmin/img/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.STATIC_URL, 'Add Another')) return mark_safe(''.join(output)) class BookingVisitorForm(forms.ModelForm): visitor = forms.ModelChoiceField( queryset=Vistor.objects.all().order_by('-pk'),empty_label='--------', widget=RelatedFieldWidgetCanAdd(Vistor,related_url='') ) class Meta: model = BookingVisitor fields = ['visitor','reason'] python 3 django 3.2 is there something i did wrong ? or isnt there a better way to achieve it , but when i added a new visitor it should being selected in the foreign key drop down field ! thank you in advance ... -
Getting error as -> 'NoneType' object has no attribute 'delete'
I am trying to delete the "profiles" manually using "admin" portal of the DJANGO, but when I click on delete after selecting some profiles, I am getting an error as -> 'NoneType' object has no attribute 'delete' I am using signals in my code. signals.py code:- from .models import Profile from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete def createProfile(sender, instance, created, **kwargs): if created: user = instance profile = Profile.objects.create( user = user, username = user.username, email = user.email, name = user.first_name, ) def updateUser(sender, instance, created, **kwargs): profile = instance user = profile.user if created == False: user.first_name = profile.name user.username = profile.username user.email = profile.email user.save() def deleteUser(sender, instance, **kwargs): user = instance.user user.delete() post_save.connect(createProfile, sender = User) post_save.connect(updateUser, sender = Profile) post_delete.connect(deleteUser, sender = Profile) models.py code:- from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank = True, null = True) location = models.CharField(max_length=200, blank = True, null = True) username = models.CharField(max_length=200, blank = True, null = True) email = models.EmailField(max_length=500, blank=True, null = False) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = … -
data imported from database(postgresql) appears twice in django admin panel
ive imported date from a table in my postgresql to django. As you can see all the data appears twice and it is not possible to accsses it through admin panel as it shows the following error: "get() returned more than one Coffee -- it returned 2!". In the database it all apear only once. admin panel -
Python, django filter by kwargs or list, inclusive output
I want to get get account Ids that will be associated with determined list of ids, currently I filter by one exactly id and I would like to input various Ids so I can get a Wider result. My code: from typing import List from project import models def get_followers_ids(system_id) -> List[int]: return list(models.Mapper.objects.filter(system_id__id=system_id ).values_list('account__id', flat=True)) If I run the code, I get the Ids associated with the main ID, the output will be a list of ids related to the main one (let's say, "with connection to"): Example use: system_id = 12350 utility_ids = get_followers_ids(system_id) print(utility_ids) output: >>> [14338, 14339, 14341, 14343, 14344, 14346, 14347, 14348, 14349, 14350, 14351] But I would like to input more variables avoiding to fell in a for loop, which will be slow because it will do many requests to the server. The input I would like to use is a list or similar, it should be able to input various arguments at a time. And the output should be a list of relations (doing the least number of requests to DB), example if id=1 is related to [3,4,5,6] and if id=2 is related to [5,6,7,8] The output should be [3,4,5,6,7,8] -
Django lexographic ordering on tuples with a where clause
As part of some custom cursor-based pagination code in Python Django, I would like to have the below filtering and ordering on a generic Queryset (where I don't know the table name up front) WHERE (col_a, col_b) > (%s, %s) ORDER BY (col_a, col_b) How can this be expressed in terms of the Django ORM? Note I would like the SQL to keep the tuple comparison and not have this based on AND clauses. In some previous tests, it seemed more likely that PostgreSQL would be more likely to use multi-column indexes.