Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkbox to select multiple images and download (Django)
I am stuck with implementing a multiple image download using Django. As seen in the photo, I want to download the images that are checked. How am I able to go about doing this using Django and Jquery? I am able to download individual images using html tag but this is not what I need. Any help would be greatly appreciated! Using Jquery, on click of the download button at the bottom of my webapp, I would check for the checkboxes that are ticked and then grab the url of those images and append them to an array. I am stuck from this step onwards. Link to webapp image -
How to return a multiple values of one method in template in django
How to return a multiple values of one method in template in django class Invoice(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT) price = models.DecimalField(default=0, max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) def total(self): x = self.price y = self.quantity return x, y How to implement it in Html ? {{ invoice }} -
Django DetailView not displaying the content from the database
I am trying to develop a job portal where people can post jobs. I created a Listview and a DetailView for the application. The list view is working but the content isn't appearing on the details page. views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Application_create # Create your views here. class AllApps(ListView): model = Application_create template_name = 'fundamentals/allapps.html' ordering = ['-id'] class ApplicationInDetail(DetailView): model = Application_create template_name = 'fundamentals/application_detail.html' urls.py: from django.urls import path from .views import AllApps, ApplicationInDetail urlpatterns = [ path('allappslist', AllApps.as_view(), name='applist'), path('app_in_detail/<int:pk>', ApplicationInDetail.as_view(), name='application_detail') ] models.py: from django.db import models from django.urls import reverse_lazy # Create your models here. class Application_create(models.Model): application_title = models.CharField(max_length=500, default='') application_opening = models.DateTimeField(auto_now=True) application_closing = models.DateField() application_description = models.TextField(default='') company_name = models.CharField(max_length=500, default='') skills_req = models.CharField(max_length=2000, default='') job_pay = models.IntegerField(default=10000) freelancing_pay = models.IntegerField(default=10000) job_type = models.CharField(max_length=500) def __str__(self): return self.application_title + self.company_name def get_absolute_url(self): return reverse('application_detail', args = [str(self.id)]) base.html: <html> <head> {% load static %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'css/allappslist.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light navbar_custom"> <a class="navbar-brand" … -
django `django.contrib.auth.urls` to generic view set for get auto documentation using redoc?
I used a redoc for auto-documentation my API this is my route router = DefaultRouter() router.register('user', GenericsUserViewSet, basename='user') router.register('userProfile', GenericsUserProfileViewSet, basename='userProfile') urlpatterns = [ .... path('api/v1/doc/redoc/', schema_view.with_ui('redoc', cache_timeout=0)), .... path('api/v1/accounts/', include('django.contrib.auth.urls')), # THIS WHAT I WANNA REG INTO ROUTER ] my question is, how to transform django.contrib.auth.urls into generic view set, so i can register that into router for auto documentation? -
Plotly margin is not working in update_layout - Django
I'm using Plotly to draw gauge charts in my Django project. In views.py, I tried to update layout by setting margin for the graph like the following: gauge_toc = go.Figure(go.Indicator( mode = "gauge+number", value = 5, domain = {'x': [0, 1], 'y': [0, 1]}, title = {'text': "TOC [mg/L]"}, gauge = {'axis': {'range': [0, 50]}, # 'steps' : [ # {'range': [0, 250], 'color': "lightgray"}, # {'range': [250, 400], 'color': "gray"}], # 'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 490} } ) ) gauge_toc.update_layout(font = {'color': "black", 'family': "Arial"}, margin = dict(t=0, b=0, l=5, r=5,)) config = { 'scrollZoom': False, 'displayModeBar': False, 'editable': False, 'showLink':False, 'displaylogo': False } div_toc = opy.plot(gauge_toc, auto_open=False, config=config, output_type='div') Although the left and right margins seem to work, the vertical margins won't disappear! this isthe template: <div class="row"> <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3"> {% if graph_temperature %} <div > {{ graph_temperature|safe }} </div> {% endif %} </div> <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3"> {% if graph_ph %} <div > {{ graph_ph|safe }} </div> {% endif %} </div> </div> any suggestions? -
AttributeError: 'NoneType' object has no attribute 'secret'
I am working on a django tenants app. I want to store stripe api keys to db. Here is my code class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) The model has been migrated and I have added a single set of data to db. But when I print out to terminal from view it shows empty and if I print out and instance it throws the above error. api_key = ExternalKeys.objects.order_by('pk').first().secret print(api_key) I can see the data in django admin -
Create a backup of every posts
I've developed my personal blog to learn Django, I would like to make a backup of every post on a second model. Below there is an example of my aim: from django.db import models class mainModel(models.Model): text = models.CharField(max_length=250) class copyModel(models.Model): main = models.ForeignKey(mainModel, on_delete=models.CASCADE) text = models.CharField(max_length=250) def save(self, *args, **kwargs): self.text = mainModel.text super(copyModel, self).save(*args, **kwargs) When I create or modify a post into mainModel must be create a copy of it into copyModel. With the code above I can create a "post" but the save method from copyModel doesen't work. Is this the right way? -
Django decorators to handle admin users redirection
I want normal users to be redirected to <address>/panel and need admins to be redirected to <adress>/admin. So what I did in views.py is something like: from django.contrib.auth.decorators import login_required @unauthenticated_user def registration_view(request): ... @unauthenticated_user def login_view(request): ... @login_required(login_url='login') @allowed_users(allowed_roles=['admin']) def admin_home_view(request): context = {} return render(request, 'account/admin/home-page.html', context) @login_required(login_url='login') @allowed_users(allowed_roles=['user']) def user_home_view(request): context = {} return render(request, 'account/user/home-page.html', context) And in decorators.py I have: from django.http import HttpResponse from django.shortcuts import redirect from groups_manager.models import Group, GroupMemberRole, Member def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('panel') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): allowed_role = allowed_roles[0] username = request.user.username member = Member.objects.get(username=username) roles = GroupMemberRole.objects.filter(groupmember__member=member) label = roles.get(label=allowed_role).label if label == allowed_role: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not allowed!') return wrapper_func return decorator I want to know how I can redirect admin users to <address>/admin url. My urls.py is: urlpatterns = [ path('admin', views.admin_home_view, name='admin'), path('panel', views.user_home_view, name='panel'), path('panel/register', views.registration_view, name='register'), path('panel/logout', views.logout_view, name='logout'), path('panel/login', views.login_view, name='login'), ] -
How to restart a django project without refresh session data stored in process/thread space?
In my django project, I store an instance of a complex class in the thread space. This instance is hard to be serialized so it cannot be stored in the database and resumed from database. When a request coming, the instance is used to response. When I refresh the code, I wanna to reload the project without refresh the instance. As the instance keep a lot of information which takes a very long time to construct again. Is there any way to keep the instance(object that cannot be serialized) when reload django project? Or is there any way to keep the instance and resume it which cannot be stored in database? -
RelatedObjectDoesNotExist in Django
i am working on ecommerce site and i get this error "Exception Type: RelatedObjectDoesNotExist Exception Value: User has no customer." models.py class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py def cart(request): customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() context={ 'items':items } thanks beforehand. -
how can i itter on each file of folder in django project?
i am trying to read each file in folder with this code: for filename in os.listdir('spectrum_order/zip_file'): if filename.endswith(".xlsx") or filename.endswith(".xls"): read = pd.read_excel(filename) labels = read['x'].tolist() but it raise this error: No such file or directory: '1.xlsx' it Shows the names of the files in the folder. But it says there is no file. my folder: image of folder when i remove 1.xldx it raise: No such file or directory: '2.xlsx' -
Char is UTF But I Still See Encrypted Letters
When some Korean texts went through the Django server, I printed the 'data' variable just to see if this encryption issue was caused by Python. Fortunately, Korean letters show well: However, when the letters go through the Django templates, it shows like this: Notice the words like \uc57c,\ud734,\ud734,\uc57c,\uc57c \ud734,\uc57c,\uc57c,\ud734,\ud734 Below is the source code of the templates: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Group Share</title> </head> <body> <p>{{ user.first_name }} opened {{ room_name }} group schedule</p> <h3>Group Members</h3> <ul> {% for member in group_members %} <li>{{ member.first_name }}</li> {% endfor %} </ul> <div id="group-schedule" class="flex"> </div> <textarea id="chat-log" cols="100" rows="20"></textarea><br> {{ room_name|json_script:"room-name" }} <script charset="UTF-8"> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/groupshare/channel/' + roomName ); chatSocket.onopen = function(e) { const data = JSON.parse(e.data); document.querySelector('#chat-log').value += (data.message + '\n'); document.querySelector('#chat-log').value = (data.new_schedule + '\n'); console.log(data.new_schedule) }; ... ... ... Settings are all set for UTF-8. Everyone tells that UTF-8 setting will solve the problem but it hasn't worked out yet. -
I want to change status and show customer the tran id
I want to show status and successfull message after a successful payment. Here I tried SSLCOMMERZ Here I apply payment integration process: def post(self, request, *args, **kwargs): settings = { 'store_id': 'gngbdlive', 'store_pass': '5F22684A3D96651198', 'issandbox': False } customer = Customer.objects.get(id=request.session['customer']['id']) order = Order.objects.get(pk=kwargs['id']) total = order.total name = order.fname phone = order.phone address = order.address quantity = order.quantity transaction_id = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) Order.objects.filter(pk=kwargs['id']).update(transaction_id=transaction_id) sslcommez = SSLCOMMERZ(settings) post_body = {} post_body['total_amount'] = total post_body['currency'] = "BDT" # post_body['tran_id'] = "123sdf5xxxxx234asf2321" post_body['tran_id'] = transaction_id post_body['success_url'] = "https://gngbd.com/Successurl/" post_body['fail_url'] = "https://gngbd.com/user_dashboard/" post_body['cancel_url'] = "https://gngbd.com/orders" post_body['emi_option'] = 0 post_body['cus_name'] = name post_body['cus_email'] = customer.email post_body['cus_phone'] = phone post_body['cus_add1'] = address post_body['cus_city'] = "Dhaka" post_body['cus_country'] = "Bangladesh" post_body['shipping_method'] = "NO" post_body['multi_card_name'] = "" post_body['num_of_item'] = quantity post_body['product_name'] = order.product.name post_body['product_category'] = order.product.category post_body['product_profile'] = "general" response = sslcommez.createSession(post_body) return redirect(response['GatewayPageURL']) after successful payment users will redirect to success.html Here is my success.html: Your Order have Been Placed! Thank You For ordering from GNGBD.COM Your TRXID: {{tran_id}} After successful payment the status will update to PAID Here is my Order Model class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address … -
I have created the django but it is not loading my home page
I am learning django app and I am stuck. I don't know the error because the compiler is working fine but the url is not loading. Here is my code. views.py>> ''' from django.shortcuts import render def home(request): # prams={'name':'Abhinav', 'place':'Earth'} return render(request, "index.html") ''' index.html>> ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template Home</title> </head> <body> Welcome to template: <h1>Text Analyzer : Enter your text below : </h1> <form action='/analyze' method='get'> <textarea name='text' style='margin: 0px; width: 1498px; height: 166px;'></textarea><br> <input type='checkbox' name='removepunc'>Remove Punctuations<br> <input type='checkbox' name='spaceremove'>Remove Space<br> <input type='checkbox' name='capfirst'>Capitalize First<br> <input type='checkbox' name='newlineremove'>Remove New Line <br> <button type="submit">Analyzer</button> </form> </body> </html> ''' Urls.py>> ''' from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('analyze/', views.analyze, name='analyze'),] ''' There is no error but the url is not connecting, it should show the index.html file but it is showing install app successfully , the default page of django app . Please Help I have mention my code above. -
Why does `HyperlinkedRelatedField` in Django rest framework needs its view to return `request` paramater as context?
I'm new to DRF. While defining a HyperlinkedRelatedField in serializer class, request paramater has to be returned from the related view. But i dont understand why. Someone please help me understand. -
pre-commit hook to check django migrations
I'm trying to write a pre-commit hook to my Django project that checks for missing migrations. That is, it ensures all changes are reflected in a migrations file. One way to implement this is to PASS the pre-commit hook if the makemigrations command returns no changes. $ ./manage.py makemigrations --dry-run No changes detected And to FAIL the pre-commit hook if it returns something: $ ./manage.py makemigrations --dry-run Migrations for 'myapp': myapp/migrations/0003_auto_20201213_2233.py - Alter field type on event How can I write this pre-commit hook? Is there a better approach than using makemigrations? This is what I have so far but it always passes (I think I need to parse the response): repos: - repo: local hooks: - id: pre-commit-django-migrations name: Check django migrations entry: ./manage.py makemigrations --dry-run language: system types: [python] pass_filenames: false -
Carousel Item exceeding height..or height not adjusting to carousel item
https://topqna.herokuapp.com/ The text is missing in each carousel item, each time i have to manually adjust the carousel height and add < br> to get it to work but every day's text length might be different. Is there an automatic way so that the the entire text is visible while also the gap between navbar and item is fixed. Here's the html (albeit as a django template) {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/kiddinglol">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large material-icons right">sentiment_very_satisfied</i> </a> </div> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/iamonceagainsaying_your_net_sucks_sry"> C O Z Y <i class="large material-icons left">favorite</i> <i class="large material-icons right">favorite</i> … -
filter user records based on their names
I simply have a django medical website where users have their medical records and can view when logged in. I have achieved the filtering based on user that is logged in, what i want is another user(doctor) to see this records based on user(patient he selects). currently the doctor can see if the record is one(using get_object_or_404, but i want loop over many records. The models.py class Medrecs(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="meds") title = models.CharField(max_length=60, null=True) doctor = models.ForeignKey('Doctors.Doctor', null=True, on_delete=models.PROTECT) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True, null=True) meds = models.TextField() def __str__(self): return self.title Views.py def detail(request, pat_id): patient = get_object_or_404(Patient, pk=pat_id) medrecs = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/detail_pat.html', {'patient': patient}, {'medrecs': medrecs}) In the view above i can see the patient records which are single records, but the medrecs(Medical records am unable to filter them based on the user(patient), it just gives me the page with the code(the template page unexecuted ). Medrecs.objects.filter(user=request.user) same case, .get will bring the number of rows and an error multipleobjects returned. As a side note i was able to filter this records in the user's(profile page) with the view: def my_profile(request): if request.user.is_authenticated: meds = Medrecs.objects.all().filter(user=request.user) return render(request, 'MyDoc/my_profile.html', {'meds': … -
Any way to distribute load between microservice api points from inside a celery task?
I have a Django back-end which takes some data and does some heavy processing on it which might take up to one minute. There is a microservice endpoint hosted on different servers which takes in all the data and does the work. Now, I have to send a POST request from inside the celery tasks to those servers. I am facing difficulty on how to actually implement network traffic management and send different requests to different servers (all of them produce the same result). Here is a sample of the celery task: @app.task def execute(**kwargs): ... exec_args = { "code" : code, "filename" : filename, "time" : time, "mem" : mem, "compile_command" : language.compile_command, "run_command" : language.run_command } param = { "input_file_urls": input_file_urls, "input_file_hashes": input_file_hashes, "output_file_hashes": output_file_hashes, "output_file_urls": output_file_urls, "exec_args": exec_args } net_res = requests.post(executor_url, json=param) net_res = net_res.json() ... Now the problem is in the executor_url part. I have different urls how do I load balance between them. -
Model permissions via a ForeignKey relationship
How can I instruct Django that the permissions for a model are resolved via a ForeignKey relationship where those permissions are declared? from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class ConfidentialityLevel(models.Model): """ A possible level of confidentiality of stored records. """ name = models.CharField(primary_key=True, max_length=50) class LoremRecord(models.Model): """ Lorem record. """ uuid = models.UUID(primary_key=True) class IpsumRecord(models.Model): """ Ipsum record. """ uuid = models.UUID(primary_key=True) class RecordConfidentiality(models.Model): """ A level of confidentiality for a record. """ record_type = models.ForeignKey(ContentType) record_name = models.CharField(max_length=50) record = GenericForeignKey(ct_field='record_type', fk_field='record_name') level = models.ForeignKey(ConfidentialityLevel) Each ConfidentialityLevel name is used for categorising which users may view (etc.) records. Examples might be secret, embargoed, beta, published. Each RecordConfidentiality instance represents that the particular record (which might be a LoremRecord, or IpsumRecord, etc.) should be confidential only to those users with permission to ConfidentialityLevel level. So permissions will be (for example) view_secret_record, edit_embargoed_record, delete_published_record. The intention is that these apply to any of LoremRecord, IpsumRecord, and any others which might be referenced from RecordConfidentiality. How can I implement authentication so that users can only perform an action on the record, if they have the ConfidentialityLevel permission corresponding for that record? -
Django Back and Next button in html file
I read django document, I know django has get_next_by_foo with foo is datetime and dont have not null=True. I created in model 2 function get_previous, and get_next but when I call it in html file, i doesnt show anything In my model.py class Contracts(models.Model): id=models.AutoField(primary_key=True) contract=models.CharField(max_length=255,blank=True, null=True) name=models.CharField(max_length=255,blank=True, null=True) debt=models.IntegerField(blank=True, null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True,blank=True) objects=models.Manager() class Meta: ordering=["-created_at"] def get_absolute_url(self): return "/contract_detail/%s/" % self.contract in my view.html def next_back(request, id=None): queryset = get_object_or_404(Contracts, id=contract) the_next = queryset.get_next_by_created_at() the_prev= queryset.get_previous_by_created_at() context ={ "title": queryset.title, "instance": queryset, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail.html", context) in my url.py urlpatterns = [ path('admin/', admin.site.urls), path('demo',views.showDemoPage), #path("",views.home, name='home'), path('customer/', views.index, name='index'), path('customer1/', views.list_contract, name='list_contract'), path('add_items/', views.add_items, name='add_items'), path('search/', views.searchcontract, name='search'), path('contract_detail/<str:pk>/', views.contract_detail, name="contract_detail"), url(r'^export/csv/$', views.export_search_csv, name='export_search_csv'), and in my contract_detail.html <a href="{{ the_next.get_absolute_url }}">Next</a> <a href="{{ the_prev.get_absolute_url }}">Previous</a> Do I misunderstand its concept? If I do, how can I deal with it? Thanks in advance! -
Is it possible to runserver with django without makemigrations?
I am trying to separate my project into multiple sub projects. Model for users has changed. I have only deleted some unnecessary fields. There are no newly added fields or amended field data. From the existing main project, I have done makemigrations and migrated them all. For example, the User model in the file models.py for the main project would look like this. class User(AbstractBaseUser): password = models.CharField('password', max_length=128, blank=True) username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email_address', blank=True) phone = PhoneNumberField('phone', blank=True) address = models.CharField('address', blank=True) python manage.py makemigrations and python manage.py migrate is all completed so the user model is set in my database. In the new sub project, the model would look like this. class User(AbstractBaseUser): password = models.CharField('password', max_length=128, blank=True) username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email_address', blank=True) The sub project is also connected to the same database which the main project is using. If I python manage.py runserver this sub project, ValueError: Dependency on app with no migrations: {application name} occurs. Runserver works properly if i python manage.py makemigrations. Is there any ways for me to not makemigrations and run my subproject server? I don't want to makemigrations because I am still using the … -
Python, Django: django-filter and ForeignKeys
Good morning, I would like to ask if there's a way to use django-filter with the Foreignkey? For example: models.py class Company(models.Model): name = models.Charfield(max_length=50, null=False, blank=False) location = models.Charfield(max_length=50, null=False, blank=False) class Person(models.Model): first_name = models.Charfield(max_length=50, null=False, blank=False) last_name = models.Charfield(max_length=50, null=False, blank=False) age = models.Integerfield() company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE) filters.py class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = [ 'first_name ', 'last_name ', 'company ', ] Right now, I only know how to filter for the whole company and often thats's totally fine, but is there a way to - for example - filter for the 'loaction' or any other values as long it's connected with ForeignKey? And if it's not, is there a better solution than django-filter? Thanks to all of you and a great day! -
How to embed a valid CSRF token in a Django Transactional email hyperlink
My application sends an email to a user a when a specific event occurs. I would like the user to be able to click on one of two buttons 'accept'/'decline' within the email body, and execute a request which then my Django application can receive and process. The user needs to be authenticated (its ok if link also does an auto-login). My intuition tells me that it will have to be done via a get() request, with a ton of logic that stores keys, verifies them, log's in the user etc. Is that the only way? -
How to save data in django without method post and forms?
I'm trying to save data, but i don't want to use method post or forms there's some way to do it?. I can do something like this? class Number(models.Model): data = models.PositiveIntegerField() The view from django.shortcuts import render from .models import Number def x(request): #something different happened to (if request method ==POST, GET,etc) number = Number.objects.create(data=1) #now something different happened and the view automatically do something like this. number = number +1 number.save() Can i do this with django? I appreciate your help