Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a form page for a parent model whose child has multiple foreign keys in Django?
I'm trying to design a single form page using Django that will allow inputting everything about a Customer in one place. My Customers can have multiple Locations. Each Location has a foreign key to not only its Customer, but also to a Contact and an Account Manager (Location has 3 foreign keys in all). Customer, Location, Contact, and Account Manager are all models; all of them have several character and boolean fields in addition to the foreign keys on Location that I already mentioned. Ideally, the form page will allow a user to input a single Customer while also creating multiple new Locations, and creating a new Contact and Account Manager for each one -- or optionally selecting an existing Contact or Account Manager. What is the best way to plan the design of this form page? Should I be looking at ModelForms and InlineFormsets? Or should I be creating a new Django Form from scratch? Or a Formset based on several Django Forms? I haven't provided any code because I'm less interested in exact implementation than in how to approach this problem, but I can provide details if necessary; let me know. Higher-level advice is much appreciated. Thank you … -
python subprocess for convert command does anything
I have a function to convert a pdf file to a thumbnail after upload. def book_post_save(sender, instance=False, **kwargs): pdf = Post.objects.get(pk=instance.pk) command = "convert -quality 95 -thumbnail 100 %s%s[0] %s%s" % (settings.MEDIA_ROOT, pdf.file, settings.MEDIA_ROOT, pdf.file) proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout_value = proc.communicate()[0] post_save.connect(book_post_save, sender=Post) But the subprocess command doesn't return anything. I tried to type it in a terminal but I got a subprocess-error-returned-non-zero-exit-status-1. I got no thumbnail generated. -
AttributeError: object has no attribute '_state'
I'm working on this django app, and I've been getting this AttributeError. Here is my models.py: class Service(models.Model): slug = models.SlugField() provider = models.ForeignKey(User, related_name="service_provider", on_delete=models.CASCADE) description = models.TextField() Here is my views.py: from django.contrib.auth import get_user_model User_s = get_user_model() class ProfileServices(LoginRequiredMixin,ListView): template_name = 'users/manage_listed.html' queryset = User_s.service_provider And in the html template it's being called as follows: {% for services in service_list.all %} The error I get is 'ProfileServices' object has no attribute '_state' Any help would be highly appreciated! Thanks! -
how to add a button/on click action in Django admin page model
I have a model where I have list of servers: Here is my mode: class Ipaddress(models.Model): ip_address=models.CharField("Ip address",max_length=20) device_type= models.ForeignKey("DeviceType", on_delete=models.CASCADE) slug = models.SlugField(unique=True) machine_name=models.CharField("Machine Name",max_length=500) user=models.CharField("User",max_length=200) department= models.ForeignKey("Department", on_delete=models.CASCADE) location= models.ForeignKey("Location", on_delete=models.CASCADE) updated = models.DateField("Date Updated",null=True) note =models.TextField() class Meta: verbose_name = 'IP Management' def __str__(self): return self.ip_address[:50] I want to add ping server action for every model record and store "Yes" if it revived any response. Here is admin page: from django.contrib import admin from pages.models import Ipaddress, DeviceGroup, Location,Department, from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter class DepartmentAdmin(admin.ModelAdmin): search_fields = ['name'] class LocationAdmin(admin.ModelAdmin): search_fields = ['description'] list_display =('description',) class IpaddressAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('ip_address',)} search_fields = ('ip_address', 'machine_name') list_display = ('ip_address', 'device_type', 'machine_name', 'user', 'department','location','updated',) list_display_links =('ip_address', 'device_type', 'machine_name', 'user', 'department','location','updated',) autocomplete_fields = ['location','department',] list_filter = ( ('user', DropdownFilter), ('department', RelatedDropdownFilter), ('location', RelatedDropdownFilter), ('device_type', RelatedDropdownFilter), ) I am thinking to add a button to pop up a small dialog box from where user will confirm ping. Need some help how I can do that. -
Dockerized Django application refuses connections
My Django application that is running on Docker won't allow me to connect to it when I type 0.0.0.0:8000 or even my docker-machine ip. The error shows as below: Safari can’t open the page “0.0.0.0:8000” because the server unexpectedly dropped the connection. This sometimes occurs when the server is busy. Wait for a few minutes, and then try again. Also when I try docker-machine ssh default I then type wget -qO- 127.0.0.1:8000 to see if the server will let me connect from within the docker vm, I get this error response: docker@default:~$ wget -qO- 127.0.0.1:8000 wget: can't connect to remote host (127.0.0.1): Connection refused Dockerfile FROM python:3.6-alpine # Copying requirements files for python modules ADD requirements.txt /requirements.txt # Installing build deps for running images RUN apk add --no-cache --virtual .build-deps \ build-base postgresql-dev libffi-dev \ && pip install -r requirements.txt \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && runDeps="$( \ scanelf --needed --nobanner --recursive /usr/local \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs … -
python get request bearer auth token + access key
I have tried access the data using post man with bearer token and access key please see screenshot. now i wanted to know How to add accesskey in header on a request in pyhon i have already added the bearer token. code headers = {"Authorization": "Bearer sdfjkdsjfs088gftdd' test = requests.get('http://blah.blah/api/1.0/blah', headers=headers) -
In setting viewset, I got an error AttributeError: 'function' object has no attribute 'get_extra_actions'
I'm learning DRF and feel confused a little now. I set up QuestionView and QuestionSerializer like this. views.py class QuestionView(viewsets.ModelViewSet) : queryset = models.Question.objects.all() serializer_class = QuestionSerializer def list(self, request, *args, **kwargs): serializer = QuestionSerializer(models.Question.objects.all()) return Response(serializer.data) serializer.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model= Question fields= ("question_text", "owner", "pub_date") urls.py router = routers.DefaultRouter() router.register('profile', cebula_views.SettingView) router.register('question', cebula_views.QuestionView.as_view({ 'get':'list', }), 'userpage-question') urlpatterns = [ ... url(r'^', include(router.urls)), ... ] File "C:\Users\1Sun\Cebula3\businessproject\urls.py", line 34, in url(r'^', include(router.urls)), File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 101, in urls self._urls = self.get_urls() File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 363, in get_urls urls = super(DefaultRouter, self).get_urls() File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 261, in get_urls routes = self.get_routes(viewset) File "C:\Users\1Sun\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\routers.py", line 176, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' In my opinion, It is that I should write get_extra_actions method in class QuestionView. If so, how I write that? like this? def get_extra_actions() : return ??? If not, what is the problem? -
Passing data from domain to subdomain in django
I have a domain example.com and a sub domain booking.example.com . I want to pass some data from example.com to booking.example.com, I just dont know how. By the way I am using Django and deploying on Google App Engine and I also want to know whether I have to create a seperaate project for this. -
E1101:Instance of 'Meta' has no 'title' member
im working on a project with Django 2.1 (Python 3.7), so i used an inner class of another one, and i tried to use the "title" variable of the parent class ,but unfortunately i had an error (Instance of 'Meta' has no 'title' member),here is the code, can you guys please help me ? enter image description here -
Django inclusion doesn´t show content
I created two custom tags in my "templatetags" folder (with init.py) See picture with two tags The first tag is a simple_tag and the integration works fine. But when I open test.html it only shows "Hello World Tag" and not the numbers from the inclusion tag. I tried a lot, but the dict with '33'and '22' didn´t came up. Any idea? Loading Tags into html -
How do I add a parameter in the django rest framework documentation?
I installed coreapi in my django application. I have set the url normally as the default in the documentation: http://www.django-rest-framework.org/topics/documenting-your-api/ When I open the url, a page with the "list - GET" and "create - POST" parameters is returned to me. However, within the GET parameters, I can not see the filters I've added. How do I show the filters in the GET parameter table? Currently only the "page" and "page_size" parameters appear, but I need to also show "matricula", "ano", "vinculo" and "mes". urls.py from django.conf.urls import url from django.urls import path from rest_framework.documentation import include_docs_urls from api.views import FuncionarioList urlpatterns = [ path('api/funcionarios/folha', FuncionarioList.as_view()), url(r'^api/docs', include_docs_urls(title='Documentação API')), ] views.py from django.db.models import Q from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import IsAuthenticatedOrReadOnly from api.core.serializer import FuncionarioSerializer from pessoal.models import Funcionario class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 class FuncionarioList(generics.ListCreateAPIView): """ get: List Funcionarios - Folha """ serializer_class = FuncionarioSerializer permission_classes = (IsAuthenticatedOrReadOnly,) pagination_class = StandardResultsSetPagination def get_queryset(self): # Busca Todos queryset = Funcionario.objects.all() # Filtros matricula = self.request.query_params.get('matricula', None) ano = self.request.query_params.get('ano', None) mes = self.request.query_params.get('mes', None) vinculo = self.request.query_params.get('vinculo', None) # Lista de Filtros filtro_api = (Q()) # Validadores if … -
Does anyone know the ids or class of the fields in django-two-factor-auth forms?
I am using the django-two-factor-auth package, and the problem is I have not been able to identify either the ids or class of the fields in the included wizard forms. I have tried #id_username and #id_password, but my styling does not apply. I thought these would be the ids because I believe the form inherits from AuthenticationForm. I have also tried a variety of others including #username, #password; #id_username_field, #id_password_field, and #username_field, #password_field. Maybe it's something else I am overlooking. Does anyone know how to call on these fields for styling with css? -
Placing a <select> field using Django templates with custom bootstrap styles
I am having an issues connecting my html css javascript front-end with django. I have html templates that look and work exactly as I want them too. I can display data without issue with I make a call to a django field that is part of my current view using: <a>{{ thing.attribute }}</a> That works great. My issue is when trying to connect a form to the django view I created for updating and creating records using a POST action. For example, when using an mdbootstrap themed template, I have implemented an html <select> object like this: <select type="select" class="mdb-select" id="fieldOne"> <option value="0">Something</option> <option value="1">Something</option> <option value="2">Something</option> </select> This works and looks exactly like I want it too as it is correctly utilizing the proper css and javascript. When I want to place a django form object in place of the same field, I have to call it like this: <div class="mdb-select">{{ thing.attribute }}</div> I have to call it as a <div> in django, and it's breaking my css and javascript, thus not displaying correctly and not usable. I can see the data being returned when I look at the rendered html in dev tools, so I know my django … -
Django, trouble deleting a record?
i have a django class based delete view It is called by a template (DetailsView, which has a button on the bottom which i want to be able to click in order to delete the record) The code in the template is this: enter code here <div> <a href="{% url 'update_candidate' object.pk %}" class="button">Edit</a> </div> <form method="post" action="{% url 'delete_candidate' object.pk %}" class="inline"> {% csrf_token %} <input type="hidden" name="object_pk" value="{{ object.pk}}"> <button type="submit" name="delete" value="delete" class="link-button"> </button> </form> The update_candidate works using the object.pk... a page is displayed with the right object, but if i try and delete i get error Request Method: POST Request URL: http://127.0.0.1:8000/candidates/delete_candidate/1/ Django Version: 2.0.6 Exception Type: ImproperlyConfigured Exception Value: DeleteCandidateView is missing a QuerySet. Define DeleteCandidateView.model, DeleteCandidateView.queryset, or override DeleteCandidateView.get_queryset(). POST Variable Value object_pk '1' csrfmiddlewaretoken 'Vp3McmK88riynpBJ9U2yPRXNvI3i8ufeepY2FnRt1cktW7aw48p7JsYTnFWvk4kD' delete 'delete' Has anyone any ideas how to fix this issue ? -
Fetch data from manytomany relationship along with onetomany
If we consider the three following models: clients, companies, contacts. Clients can purchase goods from several companies and a company has many clients. Moreover, a company has several "contact" types (email, fax, phone,...). class Clients(models.Model): fname= models.CharField(max_length=45, null=False) company= models.ManyToManyField(to='Companies', related_name='provider', blank=True) class Companies(models.Model): name= models.CharField(max_length=45, null=False) class Contacts(models.Model): contact= models.CharField(max_length=45) type= models.IntegerField(choices=TYPE) company= models.ForeignKey(to='Companies', related_name= 'company_contacts', on_delete=models.CASCADE) For a given client, I would like to retrieve all the companies he purchased from along with all the company's details (stored in the model "Contacts"). In SQL, with an intermediate table (clients_companies), I will do: SELECT cl.fname, cp.name, ct.contact, ct.type FROM Clients cl JOIN Clients_Companies cc ON cl.id = cc.clients_id JOIN Companies cp ON cp.id = cc.companies_id JOIN Contacts ct ON cp.id = ct.companies_id; Which will give: +---------+-----------+-----------------+--------+ | fname | name | contact | type | +---------+-----------+-----------------+--------+ | Client1 | Company A | 333-555-1234 | phone | | Client1 | Company A | email@email.com | email | | Client1 | Company B | 202-555-0191 | phone | | Client1 | Company B | 202-555-9999 | fax | | Client1 | Company B | arg@arg.com | email | +---------+-----------+-----------------+--------+ In django, I'd like something similar to: data = [ {'Company A':[{'type':'phone', … -
change month, year & date width individually in SelectDateWidget
In SelectDateWidget dropdown options, month_names need to be wider then days and years. How to make Months wider without affecting the width of other two dropdowns. -
Django Channels - Cannot send event to a consumer
I am using Django Channels to run a MQTT listener in background and push MQTT events to browser using Websockets. For that I have written a SyncConsumer which I trigger when the web application starts and inside this consumer, I setup the MQTT Client and register on_message handler. The problem is when I receive MQTT event in on_message handler, I cannot send any event to a named channel or a Group. Please help. Thanks Code: class MQTTSubscriber(SyncConsumer): def subscribe_mqtt(self, message): print('starting MQTT listener worker...') import paho.mqtt.client as mqtt client = mqtt.Client() self.client = client client.connect(settings.MQTT_HOST) def on_connect(client, userdata, flags, rc): print('Connected to mqtt broker!') client.subscribe('vf/reported/#') def on_disconnect(client, userdata, flags, rc): print('Disconnected from MQTT broker, reconnecting...') client.connect(settings.MQTT_HOST) def on_message(client, userdata, msg): print('MQTT event received!') async_to_sync(get_channel_layer().send)( 'notify-browser', { 'type': 'notify.observers', } ) client.on_connect = on_connect client.on_message = on_message client.on_disconnect = on_disconnect client.loop_forever() class NotificationsConsumer(SyncConsumer): def notify_observers(self, message): print(message) ### never called routing.py application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ url(r'^events/', WebsocketConsumer), ]) ), 'channel': ChannelNameRouter({ 'subscribe-mqtt': MQTTSubscriber, 'publish-mqtt': MQTTPublisher, 'notify-browser': NotificationsConsumer, }) }) -
Change django's default admin but without redirecting the models to the default admin
I have a custom administrator but when I click on a model it redirects me to the default administrator django, so it would not make sense to do a custom admin, thanks for your collaboration. This is my custom admin is in myapp / admin.py, in this case user / admin.py, I just want the user logged in without super user visualize the administration of their foundation. class AdminFundacion(AdminSite): site_header = "Administracion de fundación" def has_permission(self, request): if request.user.is_active : if request.user.rol=='1' : self.index_title="Bienvenido a la gestion de "+str(request.user.fundacion) return request.user.is_active AdminFundacion = AdminFundacion(name='fundacion-admin') AdminFundacion.register(Fundacion,FundacionAdmin) This is your respective URL in myapp / url.py from users.admin import AdminFundacion url(r'^fundacion-admin/$', AdminFundacion.urls), When I register the model in the customized admin (Admin Foundation), without registering the model in the default admin: admin.site.register(Fundacion, FundacionAdmin) This appears to me, as the model is disabled: When I register the model in the default admin, the model is enabled but when I click on the model, it loses the url user / fundacion-admin / or app / fundacion-admin / and redirects it to admin / app or admin / users in this case What can I do so that I can only manage from the custom … -
how to set foreignkey value in child serializer in django rest framework when the parent record exists
I have two models first as parent model "Country", that filled before the second one as child model "City". as the following class Country(models.Model): name = models.CharField(max_length=35) icon = models.ImageField() def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=35) country = models.ForeignKey(to=Country, on_delete=models.CASCADE) def __str__(self): return self.name My serializers.py for my need as following : class CountrySerializer(ModelSerializer): class Meta: model = Country fields = '__all__' class CitySerializer(ModelSerializer): country = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all()) class Meta: model = City fields = ('name', 'country') view.py class CountryAPIView(ListAPIView): queryset = Country.objects.all() serializer_class = CountrySerializer permission_classes = [AllowAny, AllowAnonymous] class CityAPIView(ListAPIView): queryset = City.objects.all() serializer_class = CitySerializer permission_classes = [AllowAny, AllowAnonymous] def post(self, request): serializer = CitySerializer(data=request.data) if serializer.is_valid(raise_exception=ValueError): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) now when i run get api it run and gives me a result fine . But when im trying to create a new city and set "country":"id" in json i got this error Cannot assign "2": "City.country" must be a "Country" instance. So if i was not clear ,, what i need is exactly set foreign key to city when i create city ,, not create city and country,, please any one had a solution help, because i tried many ways … -
Enable wagtail DateField when a wagtail BooleanField is true
I need to have a wagtail DateField disabled by default, but if the content author checks a box (a wagtail BooleanField) then the field should be enabled and required. I'm struggling to find the best way to solve this, I haven't found documentation on how to do this. I was thinking about using Django signals or wagtail hooks but it does seem like a complex solution for what I think should be a common use case. So I was wondering if anyone has a better alternative or point me to the right direction. -
Show error message if password and username incorrect in Django form_template
I am trying to show error when user enters wrong login credentials using form_template .So far I tried below approach but not working. Forms.py: class UserForm(forms.Form): username=forms.CharField(max_length=50) password=forms.CharField(widget=forms.PasswordInput) model=User fields=['username', 'password'] Views.py: class loginform(View): template_name='essay/Login.html' form_class=UserForm def get(self,request): # if the request is get then only view the function form=self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): #user = form.save(commit=False) # it doesnot save in database, it is used to et clean the values # clean data username = form.cleaned_data['username'] password = form.cleaned_data['password'] # authenticate user: user = authenticate(username=username, password=password) if user is not None: login(request, user) if(request.user.is_prof==True): return redirect('essay:file', ) else: return redirect('essay:stdprofile') else: return render(request,self.template_name, { 'error_message': ' Login Failed! Enter the username and password correctly', }) else: msg = 'Errors: %s' % form.errors.as_text() return HttpResponse(msg, status=400) return render(request, self.template_name, {'form': form}) Form_template: {% for field in form %} <div class="form-group"> <label class="control-label col-sm-2">{{ field.label_tag }}</label> <div class="col-sm-10">{{ field }}</div> <!-- inputs on the rigth --> </div> {% endfor %} Login.html: <body> <div class="login-card"> <h1>Log-in</h1><br> <form class="form-horizontal" action="" method="POST" enctype="multiport/form-data"> {% csrf_token %} {% include 'essay/form_template.html' %} <input type="submit" name="login" class="login login-submit" value="login"> </form> {% error_message %} </div> </body> The problem I got when I … -
Is it possible to have creator and updater separately in Django admin?
In my Store model, I have author attribute so I can tack who wrote and updated a store. However, I would like to have who created and who updated separately. I think I have to get who created in my save_model in admin.py. Is there a way to get a creator and updater separately in Django admin? models.py class Store(models.Model): ... author = ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='promotions_of_author', null=True, blank=True) admin.py class StoreAdmin(SummernoteModelAdmin): ... def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() -
Safely store KMS encrypt output with aws_encryption_sdk for python
I want to encrypt an oauth access and refresh token to store in my Postgres database for later use in my Django project. I'm using the Python aws_encryption_sdk, calling the encrypt function, following the example from here: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/python-example-code.html. I can successfully encrypt and decrypt my token using the following method and a similar decryption method. ciphertext, encryptor_header = aws_encryption_sdk.encrypt( source=access_token_plaintext, key_provider=master_key_provider ) print('Ciphertext: ', ciphertext) Now I want to store the ciphertext in a model field attached to a user so that I can make api calls for the user without having them need to re-authenticate. But although ciphertext successfully contains the encrypted access_token, it also contains my AWS ARN + keyId in plaintext, so storing ciphertext seems to defeat the whole purpose of the encryption. ciphertext is a bytes object, so it makes it hard to extract just the encrypted token text, which is what I've been trying to do. Is there a better way? Is it safe to store my ARN as part of the ciphertext bytes object? Do I need to store all this on a separate database? When I print ciphertext, this is the response type I get back: b'\x01\x00{\x03\x0cencryption_context_example_string\x00\x0cencryption_context_example_match\x00\x15aws-crypto-public-key\abcdefghighlmnopqrstuvwxyz/1234567==\x00\x01\x00\x07aws-kms\x00Karn:aws:kms:region_name:account-number:key/ABCD1234-ABCD-1234-A1B2-ABCD1234\x00\xcd...' -
How to retrieve key from model_utils Choices?
If I have some choices variable: In [1]: from model_utils import Choices In [2]: CHOICES = Choices( ...: (1, 'somekey', 'The long title'), ...: ) In [3]: CHOICES[1] Out[3]: 'The long title' How to retrieve somekey key from it? This answer doesn't work for me. In [10]: {v: k for k, v in dict(CHOICES).iteritems()} Out[10]: {'The long title': 1} -
Issue running Python37 on Google App Engine
I know this question has been asked in some facet or another, but I have gone through readings as shown here and I am still not seeing where my issue is as I am still unable to publish my Django 2.1.1 app in the Python37 environment in Google App Engine: Python 3 Django on App Engine Standard: App Fails to Start Overall what I am attempting to do is publish a simple app engine app using: gcloud app deploy My application works locally but when I publish, it goes through without issue, but I get the annoying: 500 Server Error message When I look at the logs in Google I get the same error as many others have gotten: ModuleNotFoundError: No module named 'main' here is my relevant directory structure project_portal project_portal init.py settings.py urls.py wsgi.py app.yaml requirements.txt my app.yaml file runtime: python37 entrypoint: gunicorn -b :$PORT project_portal.wsgi env: standard beta_settings: cloud_sql_instances: project:us-west1:sql-instance handlers: - url: /static static_dir: staticfiles/ - url: .* secure: always redirect_http_response_code: 301 script: project_portal.wsgi.application env_variables: # to do my project_portal/wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_portal.settings') application = get_wsgi_application()