Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django condition aggregate foreign key by value
TL;DR I want to make the long annotated query (at the project object manager part below) more elegant and efficient, and able to recalculate it self after related object was updated. Background I'm building a market place - every customer should be able to create a project that contains parts. The parts are the objects up for pricing offers. Every part contains a status Enum field - so we could know if it up to bid or already in work. Im Using Python 3.8.1 Django-rest-framework 3.10.3 (django-url-filter 0.3.14)[https://github.com/miki725/django-url-filter] Postgres 12.1 The functionality I need Projects should be filtered by their contained parts status - with specific conditions. Update on the project status should update all related parts. Projects can be created, update and deleted with the same object manager. Part Model Only relevant parts of the code: class PartStatuses(Enum): Draft = "Saved but not published" PendingBID = "It's BIDing time!" Proposal = "All BIDs are set" PendingPO = "Waiting for vendor to approve PO" WorkInProgress = "Vendor has accepted a PO" OnItsWay = "The part is ready and now await to be delivered" Delivered = "Delivery process has ended" Disputed = "Open for Dispute" Closed = "Part has received" Paid … -
Get an object id from HTML in in request.POST
I have an user with list of tasks that he can add. I want to give him ability to delete those tasks, or mark as done. The problem is that my solution is working only when user has one task, because of non-unique id's problem Is there any way to pass the id to html so that it will be easily accesible in views? Thank you! This is my current code {% for task in tasks %} <form id='is_checked' method='POST' action="{% url 'mark_as_done'%}" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group-text"> <input type="hidden" id="id_checked" value="{{task.id}}" name = "id_checked"> </div> </form> <form class="input-group" action="{% url 'delete_task'%}" method='POST' enctype="multipart/form-data"> {% csrf_token %} <div class="input-group-prepend"> <div class="input-group-text"> <input onChange="document.getElementById('is_checked').submit()" type="checkbox" {% if task.is_done %}checked{% endif %}> </div> </div> <h7 type="text" class="form-control">{{task}}</h7> <input type="hidden" id="id" value="{{task.id}}" name = "id"> <button type="submit" class="input-group-append btn btn-danger">Delete</button> </form> {% endfor %} And in views: def delete_task(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['id']) task.delete() return redirect('tasks') @login_required() def mark_as_done(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['id_checked']) task.is_done = True task.save() return redirect('tasks')``` -
Django REST: Problem with AUTH_USER_MODEL importing
I'm following this tutorial and trying to create custom user for REST-API. settings.py: INSTALLED_APPS = [ # blah blah 'courses', ] AUTH_USER_MODEL = 'courses.CustomUser' I have django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'courses.CustomUser' that has not been installed project tree: - django-project - courses - models.py models.py: class CurstomUser(AbstractBaseUser): username = None first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(max_length=254, unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [USERNAME_FIELD, 'first_name', 'last_name'] role = models.CharField(max_length=2, choices=UserRole.choices, null=False) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) What's the problem? It seems I've set up AUTH_USER_MODEL correct way -
Query ManyToMany relationship Django
Hey everyone I want to query a manyToManyField from my database it seems that it doesn't work. I would like to get from the database model the list of all framework incompatibility. But when I do a query, I get nothing from that. Here is my models: class Framework(models.Model): name = models.CharField(max_length=200) language = models.ManyToManyField(Language) version = models.CharField(max_length=20) typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE) pros = models.ManyToManyField(Pro) nombreAvantage = models.IntegerField(default = 0) cons = models.ManyToManyField(Con) nombreDesavantage = models.IntegerField(default = 0) additionalInformation = models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE) incompatibility = models.ManyToManyField("self",blank=True) def __str__(self): template = '{0.name} {0.version} {0.typeOfFramework} {0.nombreAvantage} {0.nombreDesavantage} {0.additionalInformation}' return template.format(self) def getLanguage(self): return ", ".join([p.name for p in self.language.all()]) def getPros(self): return ", ".join([p.advantage for p in self.pros.all()]) def getCons(self): return ", ".join([p.disadvantage for p in self.cons.all()]) def getIncompatibility(self): return ", ".join([(p.name + ' '+ p.version) for p in self.incompatibility.all()]) def __iter__(self): return [ self.name, self.language, self.version, self.typeOfFramework, self.pros, self.cons, self.additionalInformation ] class DataPro(models.Model): advantage = models.CharField(max_length=200) def __str__(self): template = '{0.advantage}' return template.format(self) class DataCon(models.Model): disadvantage = models.CharField(max_length=200) def __str__(self): template = '{0.disadvantage}' return template.format(self) class Database(models.Model): name = models.CharField(max_length=200) version = models.CharField(max_length=20) pros = models.ManyToManyField(DataPro) nombreAvantage = models.IntegerField(default = 0) cons = models.ManyToManyField(DataCon) nombreDesavantage = models.IntegerField(default = 0) … -
How to send value in javascript to django
I try to get value in django from javascript but it's none value in some variable. template.html <script> $(document).ready(function () { first(); $('#btnAdd').click(first); }); var choices = ["one", "two", "three"]; function first() { var id = $('#cover div').length + 1; var wrapper = $("<div id=\"field" + id + "\" class='row info'><p></p>"); var category = ""; category = "<div class='col-md-2'><select class='form-control' name=\"category" + id + "\">"; for (i = 0; i < choices.length; i = i + 1) { category += "<option value='" + choices[i] + "'>" + choices[i] + "</option>"; } category += "</select></div>"; var product = $("<div class='col-md-5'><input type='text' id='tags' name=\"product" + id + "\" class='form-control' size=40 placeholder='ชื่อสินค้า' required/></div>"); // สร้าง input wrapper.append(category, product); $('#cover').append(wrapper); $(wrapper).find("input[name^='product']").autocomplete({ source: "/autocomplete_product?category", minLength: 2, }); } views.py product = request.GET['term'] category = request.GET['category'] I try to print request.GET, it show category and term variable. The term variable is normal (there is value) but category is null. I have question how to I send category to django. -
django.db.utils.IntegrityError: NOT NULL constraint failed: BookApp_book.publisher_id while updating models with fake data
I am trying to populate my models using some fake data generated through faker in my django project. I have created three models Publisher, Author, and Book. The migrations are done correctly and the models are created successfully. I am able to add the data to the models through admin interface, but when i try to populate the models through fake data i am getting the following error.django.db.utils.IntegrityError: NOT NULL constraint failed: BookApp_book.publisher_id I am not able to figure out what is the mistake. Here is my models.py from django.db import models # Create your models here. class Publisher(models.Model): ''' Publisher class model with name,country,email,website ''' name = models.CharField(max_length=25) country = models.CharField(max_length=25) website = models.URLField() def __str__(self): return self.name class Author(models.Model): ''' Author model with name,contact,email,age,location ''' author_name = models.CharField(max_length=25) age = models.PositiveSmallIntegerField() email = models.EmailField() # method for string representation of the class def __str__(self): return self.author_name class Book(models.Model): ''' Book model with title,pages,author,publisher,publication_date ''' title = models.CharField(max_length=100) pages = models.PositiveSmallIntegerField() author = models.ManyToManyField('Author') publisher = models.ForeignKey(Publisher,related_name='publisher',on_delete=models.CASCADE) publication_date = models.DateField() # method for string representation of book class def __str__(self): return self.title populate_bookapp.py import os # set the default environment to the projects settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BooksProject.settings') import django django.setup() … -
Django Website Built using Python 3.7.6 + Django 3.0.3 + Pandas 1.0.1 Hangs on Apache 2.4.41 due to Pandas 1.0.1
I have build a basic Website using Python 3.7 + Django 3.0.0 + MySQL 8.0.18 + Pandas 1.0.1. This site works very well using py manage.py runserver on my local environment. However, as soon as I deploy it on Apache 2.4.41 configured on Windows 10 Server. The site starts giving 408 error. Further this environment configured Apache(2.4.41) + mod_wsgi(mod_wsgi-4.7.1+ap24vc15.dist-info) + Python(3.7.6)+ django(3.0.3) + Pandas (1.0.1). On further debugging I have observed that imports from pandas are the root cause of the issue. Please code from model.py for your reference - from django.db import models, connection # from pandas import DataFrame # from pandas import concat, to_datetime, to_numeric **# Un-commenting above two lines cause the issue** # Create your models here. class ISMADates(models.Manager): def date_list(self): with connection.cursor() as cursor: cursor.execute("select date_id, date from master_date order by date_id desc LIMIT 10;") result_list = cursor.fetchall() # print(result_list) return result_list However as per my understanding pandas should work seamlessly with Django. And this combination is quite widely used. Please suggest the next steps to proceed further. -
How to load javascript file after ajax sucess in django
im working with ajax and trying to load external javaScript file after ajax success. So far what i have is this $.ajax({ url: "{% url 'app:cat_data_for' %}", type: "POST", async: false, data: {cat_data: cat_data,csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (data) { $.getScript("{% static 'type.js' %}"); }); But It's not working. How to do this. Thanks in advance. -
URL management with Django, GraphQL, Apollo and VueJS
As said in the title, I'm using Django, GraphQL, Apollo and VueJS in my project. I'm developping it as a SPA (Single Page Application). Everything works fine, until I hit the F5 button and refresh the page. Indeed, it shows an unknown page. The thing is it is VueRouter that is managing the SPA and it works fine. But when I press F5, that is Django that tries to serve a page for the current URL and since it doesn't know it, it can't serve the appropriate page. I know I can set the VueRouter 'history' mode, which I did, and add a URL to Django that serves index.html whatever the URL is. My problem is the following : When I'm on a particular form view (i.e : a User form view) my URL is the following : http://localhost:8000/user Since I'm using GraphQL for my API, the retrieved data is not based on the URL. In fact, that is my VueJS component that says : Hey Apollo, run that GraphQL to retrieve the User I want. So when I refresh, yes it serves the User form view..but empty. The question is : How could I solve this ? For clarification … -
Editing button in the wrong form when editing a manytomany field
I am trying to edit a ManyToMany relation field and I am using ModelForm in my forms.py and I am using Createview in my views.py. In my forms.py file I am using ModelMultipleChoiceField for the editing of the ManyToMany relation from the 'participant' field to Person model. The problem is that when the template render the form, it puts the editing button at the last field, not the one that I want to edit. for example: model=Activity participant=ModelMultipleChoiceField(queryset=Activity.objects.all()) fields=['activity_name','project','participant','min_stage_area'] this will put the editing button right behind the 'min_stage_area' form, not the 'participant' form where I want it. how do I solve this? views.py: class CreateTour(CreateView): form_class=CreateTourForm template_name='artdb/createtour.html' def get_context_data(self,**kwargs): context=super(CreateTour,self).get_context_data(**kwargs) return context def form_valid(self): response=super(CreateTour,self).form_valid() self.object.project=self.form.cleaned_data['project'] return response forms.py: class CreateTourForm(ModelForm): class Meta: model=Activity participant=ModelMultipleChoiceField(queryset=Activity.objects.all()) #person_instance.first_name.add(activity_instance) fields=['activity_name','project','participant','min_stage_area'] models.py: class Activity(models.Model): activity_name=models.CharField(max_length=200,default='no name') project=models.ForeignKey(Project,on_delete=models.CASCADE,default=1) participant=models.ManyToManyField(Person) min_stage_area=models.IntegerField(default='2') light_requirements=models.CharField(max_length=200,default='no requirements') sound_engineer=models.CharField(max_length=200,default='not needed') comment=models.ManyToManyField(Comment) def __str__(self): return self.activity_name class Meta: ordering = ('activity_name',) class Person(models.Model): SALARYTYPE=(('None','N'),('Faktura','F'),('Lön','L')) first_name=models.CharField(max_length=200,default='firstname') last_name=models.CharField(max_length=200,default='lastname') # role=models.ManyToManyField(Role) mail=models.EmailField(default='yourname@gmail.com') homepage=models.CharField(max_length=200,default='www.yourhomepage.com') phone_number=PhoneNumberField(default='+46707305134') street_address=models.CharField(max_length=200,default='streetAdress') zipcode=models.CharField(max_length=200,default='99999') city=models.CharField(max_length=200,default='Göteborg') country=models.CharField(max_length=200,default='Sweden') payment=models.CharField(max_length=10,choices=SALARYTYPE,default='none') comment=models.ManyToManyField(Comment) def __str__(self): return "%s %s" % (self.first_name,self.last_name) class Meta: ordering = ('first_name','last_name') template: {% extends "artdb/index.html" %} {% block ct %} <form method="post">{% csrf_token %} <div class="input-group"> {% for fr in formset %} {{fr}} … -
Reverse Url from slug with Persian or arabic languages in Django
hi i want to reverse url from slug in model i have slug : slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) and for get absolute url : def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) and in settings.urls : urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] and in shop.urls : app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ] and value for my slug is : slug="گالری-شلوار" now i get error : Reverse for 'product_list_by_category' with arguments '('گالری-شلوار',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'] -
Django Admin - call change_view for inline
I am currently developing an application in Django. In the Admin part, I would like to exclude the "groups" part in the modification view, using the "change_view" method Here is the error returned: Information: I have an extended user table. In addition the error indicates that I can try with "user_permissions", but after testing it tells me again that I can use "groups" ... So it's not a naming problem Here is the code: # ADMIN # class UserExtendInline(admin.StackedInline): model = UserExtend max_num = 1 fk_name = 'user' can_delete = False fields = ('user','offer', 'valid_payments') class AccountsUserAdmin(UserAdmin): inlines = (UserExtendInline,) list_display = ('email','first_name','last_name','Formation_Souscrite','last_login','Paiement_Valide','is_active') readonly_fields = ('email', 'last_login', 'date_joined') def get_inline_instances(self, request, obj=None): if not obj: return list() return super(AccountsUserAdmin, self).get_inline_instances(request, obj) def Formation_Souscrite(self, obj): user_extend = UserExtend.objects.filter(user=obj).prefetch_related('offer') user_extend = user_extend[0] if not user_extend.offer is None: return user_extend.offer.name else: return "Aucune" def Paiement_Valide(self, obj): return UserExtend.objects.get(user=obj).valid_payments def change_view(self, request, object_id, extra_context=None): self.exclude = ['groups'] return super(AccountsUserAdmin, self).change_view(request, object_id, extra_context) Paiement_Valide.boolean = True # unregister old user admin admin.site.unregister(User) # register new user admin that includes a UserProfile admin.site.register(User, AccountsUserAdmin) admin.site.unregister(Group) Thank you for your reply -
Using live_server fixture in pytest: Site cannot be reached
I am trying to run selenium tests with pytest-django for my django app. Pytest-django provides a fixture called live_server. I am supposed to get the URL with live_server.url. Now when I try to visit live_server.url it opens a browser but then the browser shows that the site cannot be reached. This is the not-working code I am trying to run: @pytest.mark.django_db class TestAdmin(): @pytest.fixture def setup(self): global browser browser = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME, ) browser.implicitly_wait(5) yield browser.quit() def test_user_can_visit_website_with_chrome(self, live_server, setup): """Website is reachable in Chrome browser. """ browser.get(live_server.url) assert 'mywebsite' in browser.title The following code works if I use djangos inbuilt test runner: class AdminTest(BaseTestCase): def test_login(self) self.selenium.get(f"{self.live_server_url}/admin") path = urlparse(self.selenium.current_url).path self.assertEqual('/admin/', path) So with django's inbuilt live_server_url it visits my localhost without complaining. But I need this in pytest and I don't really want to mix both syntaxes. Reading the documentation it only says: live_server This fixture runs a live Django server in a background thread. The server’s URL can be retrieved using the live_server.url attribute or by requesting it’s string value: unicode(live_server). You can also directly concatenate a string to form a URL: live_server + '/foo. As I understand this it should work with the code that … -
Django ORM : Select rows from table A if it has the same id(FK) in the table B, where the rows in B are selected if it satisifies a condition:
I have table hospitals and other table departments. I need to do a search operation based on the city. When the user selects the city and types the department, it should check for hospitals in the hospital's table working in the user given city and then check in the department's table whether any of those hospitals are there in the table with the user given department. How do I do this with Django ORM? class HCSProfile(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) class HCspeciality(models.Model): hospital = models.CharField(max_length=255, blank=True, null=True) speciality = models.CharField(max_length=255, blank=True, null=True) hospital_id = models.ForeignKey('HCSProfile', on_delete=models.CASCADE) -
CSRF protection to a view with a download api request
I have this view in my application that calls an api to download a pdf: @login_required def generateContractPdf(request): file_id = request.POST.get('contract') contract_id = request.POST.get('contract') payload = {"file_id": file_id} data = {"data": json.dumps(payload, default=str)} headers = {'content-type': 'application/json'} brokkr = os.environ.get("BROKKR_ADDRESS", default='localhost') response = requests.post('http://'+brokkr+':5000/contract', params=data, headers=headers) filename=str(contract_id)+".pdf" response = HttpResponse(response.content, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="'+filename+'"' return response But I just realiced that if I dont use render() the csrf doens't work, so this view could be exploited. How can i transforme it to keep that protection? -
how to display a list of colleges based on the percentage in Django-FormWizardView
I have a three-page form-list coming out of a single model and I want to display Colleges depending on percentage selection in the second step but it displays a list of all colleges from the database in the third step. how to display a list of colleges based on the percentage in Django-FormWizardView Here is my models.py class Percentage(models.Model): number = models.CharField(max_length=100) def __str__(self): return self.number class College(models.Model): percentage = models.ForeignKey(Percentage, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Student(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) firstname = models.CharField(max_length=100,validators=[alphanumeric]) lastname = models.CharField(max_length=100,validators=[alphanumeric]) image=models.ImageField(upload_to='files/%Y/%m/%d', blank=True) percentage = models.ForeignKey(Percentage, on_delete=models.SET_NULL, null=True) college = models.ForeignKey(College, on_delete=models.SET_NULL, null=True) description=models.TextField(blank=True) def __str__(self): return self.firstname forms.py class FirstForm(forms.ModelForm): id = forms.IntegerField(widget=forms.HiddenInput, required=False) firstname = models.CharField(max_length=100,validators=[alphanumeric]) class Meta: model = Student fields = ('firstname',) class SecondForm(forms.ModelForm): lastname = models.CharField(max_length=100,validators=[alphanumeric]) image = forms.ImageField(required=False) class Meta: model=Student fields=('lastname','image','percentage') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['percentage'].widget.attrs={ 'id': 'percentage', 'label':'percentage', 'name': 'percentage'} def save(self, commit=True): user = super(SecondForm, self).save(commit=False) user.percentage = self.cleaned_data['percentage'] if commit: user.save() return user class ThirdForm(forms.ModelForm): description = forms.CharField(widget=forms.Textarea) class Meta: model = Student fields = ('college','description',) def __init__(self, *args, **kwargs): super(ThirdForm, self).__init__(*args, **kwargs) self.fields['description'].widget.attrs={ 'id': 'id_description', 'class': 'myDescriptionClass', 'name': 'myDescriptionName', 'placeholder': 'myDescriptionholder'} self.fields['college'].widget.attrs = {'id': 'college', 'label': 'college'} if 'percentage' in … -
When do you need to use iri_to_uri after using url_has_allowed_host_and_scheme in Django?
In the Django 3.0 release notes, this comment is made about url_has_allowed_host_and_scheme: To avoid possible confusion as to effective scope, the private internal utility is_safe_url() is renamed to url_has_allowed_host_and_scheme(). That a URL has an allowed host and scheme doesn’t in general imply that it’s “safe”. It may still be quoted incorrectly, for example. Ensure to also use iri_to_uri() on the path component of untrusted URLs. I understand what the purpose of url_has_allowed_host_and_scheme is. Take the common use-case of providing a next query parameter, for example: http://example.com/foobar?next=http%3A%2F%2Fexample2.com%2Fhello . You could program the view that handles this path to redirect to the URL provided by the next parameter, in this case: http://example2.com/hello . If the URL is not validated, then this is an "open redirect" vulnerability. Malicious actors could take advantage of an open redirect to hide malicious URLs behind a URL that looks trustworthy. You can use url_has_allowed_host_and_scheme to ensure that the URL has the expected hostnames and scheme. My question is concerning iri_to_uri. The documentation implies that you also need to use this function as well. When would I need to use it? -
How to prevent your free tier heroku app from idling(python/django)
Is there any way, through code, to prevent your app from idling? I'm thinking something like what is being done here. How to do this through code, but in python/django as that is what my app is done in, i.e. what is the equivalent in python to Node's setInterval. What are the disadvantages of using a pinging service over doing it through code(other than if the site goes down your app wont get pinged). Can you recommend a good pinging service? Thanks in advance. -
Models not ready when using import-export ModelResource in tasks,py
I am trying to use a celery job to import data. As my data structure is rather complicated I can't really use import-export-celery by timthelion. When I import my ModelResource into tasks.py I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. due to File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 747, in __new__ readonly=False) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 895, in field_from_django_field FieldWidget = cls.widget_from_django_field(django_field) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 861, in widget_from_django_field result = getattr(cls, result)(f) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 841, in get_fk_widget model=get_related_model(field)) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/import_export/resources.py", line 47, in get_related_model if hasattr(field, 'related_model'): File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/U/.virtualenvs/proj/lib/python3.6/site-packages/django/db/models/fields/related.py", line 95, in related_model apps.check_models_ready() Resource: from import_export import resources from bewertung.models import Optimierungsergebnis class testResoruce(resources.ModelResource): class Meta: model = TestModel Edit: The issue only arises if TestModel has a ForeignKey if have double checked celery.py and tried to use django.setup() as other posts on similar errors had suggested. -
How to connect iphone to a local server running on mac?
I am running a django server at localhost:8000 to accces it from iPhone i had connected the iphone and mac to the same network. ifconfig |grep inet inet 127.0.0.1 netmask 0xff000000 inet6 ::1 prefixlen 128 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 inet 127.94.0.1 netmask 0xff000000 inet 127.94.0.2 netmask 0xff000000 inet6 fe80::aede:48ff:fe00:1122%en5 prefixlen 64 scopeid 0x4 inet6 fe80::10a0:e008:9d34:5f7e%en0 prefixlen 64 secured scopeid 0x6 inet 192.168.43.234 netmask 0xffffff00 broadcast 192.168.43.255 inet6 2401:4900:2320:f3e9:10a0:ab34:c773:1104 prefixlen 64 autoconf secured inet6 2401:4900:2320:f3e9:b444:77e0:94f:8ccc prefixlen 64 autoconf temporary inet6 fe80::b4ed:bff:feba:10c2%awdl0 prefixlen 64 scopeid 0x8 inet6 fe80::b4ed:bff:feba:10c2%llw0 prefixlen 64 scopeid 0x9 inet6 fe80::54e:e417:7879:b351%utun0 prefixlen 64 scopeid 0xf inet6 fe80::203b:4e44:1f36:a04c%utun1 prefixlen 64 scopeid 0x10 inet6 fe80::eaa6:a7d3:cf35:3fe1%utun2 prefixlen 64 scopeid 0x11 inet6 fe80::7604:df44:d8c4:65be%utun3 prefixlen 64 scopeid 0x12 inet6 fe80::3e0f:e8c3:e7a:f96c%utun4 prefixlen 64 scopeid 0x13 inet6 fe80::3719:2c00:294b:88be%utun5 prefixlen 64 scopeid 0x16 After running the ifconfig command i took out the ip adress of the mac i.e. 192.168.43.234. And using this address in safari i am not able to access the server from iphone. -
How to limit the inline ForeignKey queryset to the instance itself in Django admin
I have 5 models and their relations are as follows: class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) class C(models.Model): b = models.ManyToManyField(B) class D(models.Model): pass class I(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) c = models.ForeignKey(C) d = models.ForeignKey(D) I decide to use the django admin class IAdminInline(admin.TabularInline): pass class DAdmin(admin.ModelAdmin): inlines = [IAdminInline, ] The admin page makes a lot queries,if too many I instances are related to D, which is time consuming. So I disable the Django default actions by setting the formfield_for_foreignkey: def formfield_for_foreignkey(self, db_field, request, **kwargs): field = super().formfield_for_foreignkey(db_field, request, **kwargs) field.choices = [] # django will not make any queries if set choices Instead, I use ajax to get the corresponding data, and use javascript to render the select widgets and bind actions , which make it easier to add data since these widgets are related to each other. Page loads faster but problem is that, the above code would clear I instances initial values that are apparently already existing in the change view page. I want to ask how can I render the existing inline object select widgets to their own values? I haven't find any solutions yet... -
What's CART_SESSION_ID holding?
I am following Django by example book. In settings.py CART_SESSION_ID = 'cart' in cart.py in cart app class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart``` if its a string then if not cart: block will never execute. i am unable to understand how CART_SESSION_ID is working here? -
How to display certain group users in template with generic views?
I am gradually learning class based views in django. Now I am trying django generic views. I can do this easily with function based views. Here I got confused on which methods(get_queryset or get_object or get_context_data) to override while using generic views for this task . class UserGroupDetail(generic.DetailView): model = Group context_object_name = 'group' template_name = 'user_groups/group_detail.html' # how to query the group's users template I can do like this for permissions. {% for permission in group.permissions.all %} .... {% endfor %} For users ?? -
ModuleNotFoundError in tkinter heroku
I'm getting the error and Im using heroku in my Proc-file i specified the app path is where is my wsgi file located i don't know why and another problem is im getting the error (import _tkinter # If this fails your Python may not be configured for Tk 2020-02-24T07:14:05.594389+00:00 app[web.1]: ModuleNotFoundError: No module named '_tkinter') - [ ] my error page -
DRY validation of query params for djangorestframework view
I want to create a view in django-rest-framework. This view would accept several custom query parameters, so it wouldn’t be based on any existing view. I want the query parameters to be available in the OpenAPI 3 schema for the purpose of type-checking in the TypeScript client. My questions are: How can I perform the validation of these parameters declaratively? Is using Serializer a good way to perform validation of a query string? How can I generate the corresponding part of the OpenAPI 3 schema in a DRY way? I see that the existing drf views don’t use a DRY pattern here (they just return a static directory for schema). Also, the method that generates schema for Serializers is underscore-prefixed, so it might not be a good idea to use it directly (although I don’t know the rationale for this). So what are my options here?