Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Twilio Texting - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I’m new to Python and Django, but have decided to make my own wedding website based on https://www.placecard.me/blog/django-wedding-website/. The only major difference I want to make is to change the the email communication to SMS. I came across this https://github.com/CleverProgrammer/CP-Twilio-Python-Text-App texting app. I incorporated the texting app into a Django project to test and attempt to send a text message to all guests in the database. I’m running Python 3.6.5 and Django 2.0.5 I have the following directory structure for my Django project. Picture 1 I have the following code: settings.py import os enter code here`# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'twilio', 'sms_send', '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', ] ROOT_URLCONF = 'WebsiteSMS.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, … -
Django rest framework browsable api is rendering both a PUT and a POST form when it should only be rendering a POST form
Normally when I navigate to the url http://localhost:8000/api/v1/public_profiles/ using a ModelViewSet, I only get a POST form and when I navigate to a specific resource such as http://localhost:8000/api/v1/public_profiles/123456/ I only get a PUT/PATCH form. Currently both forms are being rendered at both locations. For many of my routes I will need more control over my views so I dropped down to generic views. I also wanted to take advantage of the router so I mixed in a generic viewset. The image above is the result of implementing the following view: class PublicProfileViewSet(viewsets.GenericViewSet, generics.ListCreateAPIView, generics.RetrieveUpdateAPIView): queryset = PublicProfile.objects.all() def get_serializer_class(self): if self.action == 'list': return PublicProfileReadSerializer elif self.action == 'retrieve': return PublicProfileReadSerializer elif self.action == 'create': return PublicProfileCreateSerializer elif self.action == 'update': return PublicProfileUpdateSerializer else: return PublicProfileReadSerializer Is there anything I can do to fix this so that a POST form renders on the LIST action and PUT/PATCH form renders on the RETRIEVE action? -
NameError at /system/invn/create name 'name' is not defined modelForm
I trying to create a form with ModelForm that save it to a database. But got an error. here my models.py class Inventory(models.Model): name = models.CharField(max_length=255) sn = models.DecimalField(max_digits=20, decimal_places=0) desc = models.TextField(blank=True, null=True, default='Tidak ada deskripsi') here my forms.py class InventoryForm(forms.ModelForm): name = forms.CharField(max_length=255) sn = forms.DecimalField(max_digits=20, decimal_places=0) desc = forms.CharField(widget=forms.Textarea) class Meta: model = Inventory fields = ('name', 'sn', 'desc',) here my views.py class InventoryCreateView(TemplateView): template_name ='system/inventory_form.html' def get(self, request): form = InventoryForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = InventoryForm(request.POST) if form.is_valid(): form.save() args = {'form': form, 'name': name, 'sn': sn, 'desc': desc} return render(request, self.template_name, args) its said NameError at /system/invn/create name 'name' is not defined modelForm from args = {'form': form, 'name': name, 'sn': sn, 'desc': desc} what missed here?... -
Is ordering a Django Queryset faster than a pandas dataframe?
I have converted my queryset into a dataframe in the application using django-pandas: from django_pandas.io import read_frame qs = Entry.objects.filter( date__range=(start_date, end_date), ).select_related( 'user', 'project' ) df = read_frame( qs, fieldnames=[ 'id', 'date', 'user', 'user__id', 'project__name', 'project_id' ] ) I was deciding whether to add an order_by to the query or to sort the dataframe with pandas. They will both have the same functionality so the choice is down to speed. There are 64k records in the table I am querying. -
Reading foreign key ref in save() override raises RelatedObjectDoesNotExist
I suppose this is by design, but here's my scenario: if saving a Child without a Parent, I want to create a new Parent. class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.PROTECT, related_name='children') def save(self, *args, **kwargs): if self.parent is None: # error happens here self.parent = Parent.objects.create() super().save(*args, **kwargs) c = Child() c.save() # django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Child has no parent. I get the above RelatedObjectDoesNotExist when executing if self.parent is None. I've tried if not self.parent as well, same error on the same line. I don't really want to make the parent field nullable. Just the act of reading self.parent, even to check if it's None, is enough to trigger the error. This is in Django 1.11, here's where the error is raised: https://github.com/django/django/blob/2b882a4bd954c8a6b1447f8fc0841a3352514c26/django/db/models/fields/related_descriptors.py#L193, so if I'm reading this right, just by reading self.parent, I'm ending up in that __get__. How can I "give it a value if it's None", if I can't check that it's None? -
Django timezne and dateTime format display
How can I give the user switch: 1. date time format 2. timezone both for display diffrents dateTime as the user determined. I want to enable this options in admin Django or UI and not manually settings page. -
Django form data lost on making login required on post
In my app, I want the following behaviour: User goes to contact form url User fills up the contact form (a) If user is logged in, validate and submit the form (b) If user is not logged in, redirect to login form for logging in and then if users credentials are validated, submit the form. In my views.py, I have: @method_decorator(login_required, name='post') class ContactView(FormView): template_name = 'extras/contact.html' form_class = ContactForm def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form, **kwargs) else: return self.form_invalid(form, **kwargs) def form_valid(self, form): instance = form.instance instance.request_user = self.request.user instance.save() messages.success(self.request, "Thank you for contacting us! We will reach you soon.") return super().form_valid(form) def get_success_url(self): return reverse('main_home') The idea of including a post method was taken from this SO Answer This does not work. The user is being redirected to login form, logged in, but displays a blank form and entered information before redirection is lost. How can I resolve this problem, any hints? -
Get only the PK value, and return in from django table
I want to search against the Tld table, only get the primary key value of the Tld object. I have the code to perform a query to extract the whole row, but i only want the PK value matching the query: Tld.objects.filter(d=base_url) How can this be accomplished? -
Migrate passwords from Django to Symfony 3
Our client requested to change technology used in a product, from Django to Symfony3. Now, when all work is done, we need to transfer all production users from Django to Symfony. Everything is done except password migration. I'm not sure on how to achieve this. The article that I found says what should be done, but im not sure how to do it. This is the url I found that has some information on it: link But im not sure how to implement it. Anybody who knows more on this or who has actually done it? -
Unity's request is not received by a Django server deployed in Heroku
We have successfully deployed Django server on Heroku, and connection through the Internet browser works well. Heroku's log is also output normally, and there is no problem. However, my project must communicate with the Django server via Unity, not Internet browser. I have implemented a separate class that inherits from Unity's UnityWebRequest, but in fact it's like using UnityWebRequest. However, even if a request is sent to the corresponding uri using this class, no results are found in the log. Of course, Unity does not receive the response normally. Is there an attribute in Django or UnityWebRequest that I do not know is set as the default? -
Django inbuilt functions not working
I am trying to make a user login page in Django following the book "How to Tango with Django" (for the most part). My form appears on the template as it should but upon submission I get the following errors: 'function' object has no attribute 'save' 'function' object has no attribute 'set_password' The relevant part of my view function is as follows: if user_form.is_valid() and profile_form.is_valid(): user = user_form.save user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user My model is: class UserProfile(models.Model): user = models.OneToOneField(User) picture = models.ImageField(upload_to='profile_pictures', blank=True) def __str__(self): return self.user.username -
This design[in image] suitable for web applications or it slow down the application process time.if suitable how can i do that
Folders to be in tree structure and data to be stored in leaf ,how can i do this, if it is possible plz explain how i can do this ,every folder user can add sub folder and data into the folder 2)User should be able to save the data successfully in leaf node and remain in the same page.] folders structure in image -
Django/ReactJS how to add django urls as props?
Keep in mind that i am completely fresh with react/django and I need all the help I can get. I want to create a Navbar component in my application with React. The problem is that the navbar has links to other parts of the application so what I am trying to do is to pass an array with all the links as props to my navbar component. But how can I get the links in javascript dynamically? Right now I have this: index.js: let navbarUrls = [ {key: 0, url: "{% url 'main:index' %}"} ]; ReactDOM.render(<Navbar urls={navbarUrls} />, document.getElementById('navbar')); Navbar.js: import React, {Component} from 'react'; class Navbar extends Component { render() { return ( <nav class="navbar navbar-toggleable-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {this.props.urls.map(url => ( <a class="navbar-brand" key={url.key} href={url.url}>Main Page</a> ))} <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> </ul> <div class="navbar-brand"> <div id="current-time"> </div> </div> </div> </nav> ) } } export default Navbar While the elements are created, the links are ofcourse not since it does not recognize twig... Maybe i am doing this completely wrong? Can someone direct me to the right way?? -
Unable to receive json response from Django view to template?
I am trying to send a json response from django view to template but when I try to console.log the response in my ajax, I am getting nothing. What could i be doing wrong ? I am trying to pass the result data from views to my ajax success function. I also noticed something strange that when I mention the datatype = json in my ajax then I dont receive any response in the success function but when I remove the dataType = json then I get the entire html of my template in my success function as a response. Why is that ?? views.py class ChangePassword(View): def post(self, request, *args, **kwargs): form = PasswordChangeForm(request.POST) #current_password = json.loads(get_value.current_password) #print ('current password',get_value['current_password']) if form.is_valid(): print("valid form") user = CustomUser.objects.get(email=request.user.email) current_password = form.cleaned_data['current_password'] print('current_password',current_password) new_password = form.cleaned_data['new_password'] print('newpassword',new_password) if user.check_password(current_password): print('entered') update_session_auth_hash(self.request, self.request.user) # Important! user.set_password(new_password) user.save() result = {'success': "Succefully reset your password"}; result = json.dumps(result) print ('result',result) return render(request, 'change_password.html',context={'result': result}) else: return render(request, 'change_password.html', {'error': "We were unable to match you old password" " with the one we have. <br>" "Please ensure you are entering your correct password" "then try again."}) else: print("not valid") return render(request, 'change_password.html', {'form':form}) def … -
Django ckeditor and django tables2 safe render
I am using django tables2 https://github.com/jieter/django-tables2 to display data in a table in my template that has been created by django-ckeditor https://github.com/django-ckeditor/django-ckeditor. Specifically the issue I am having relates to the rendering in the table of a LinkColumn: class MyTable(tables.Table): notes = tables.LinkColumn('notes_update', kwargs={"pk": Accessor("pk")},attrs={'th': {'id': 'thnotes'}, 'td': {'id': 'tdnotes'}}) The data is displayed in the table with the html <p> <p/> tags, as created by ckeditor. From what I can gather I need to render in the template using the {{ |safe }} tag in order to display the table data without html <p> <p/> tags with but im at a loss as to how to achieve this in conjunction with django tables2 as my table is rendered in my template as follows: {% render_table table %} I have tried without success to surround this with: {% autoescape off %} {% render_table table %} {% endautoescape %} Does anyone have any ideas to help me render notes data in my table without the html <p> <p/> tags? Any help will be much appreciated! -
registration form validation of open edx
I'm working on a project based on open edx. I added a phone_number field to the Userprofile model, so that phone number will be required when users register. The phone number need to be 11 digit. How do I add constrain on the phone number field of the registration form? Addition: my boss requires me to add this constrain through javascript, no change to python files. I'm stuck on it. Help needed. -
gce-ingress HTTPS backend
I was configuring the gce ingress on my kubernetes cluster and I specified a Django application as default backend. The app enforces HTTPS so if you try to do a simple HTTP request Django will return a 301. Obviously HTTP health check will not pass. I was following this example to enable the HTTPS health check. Once the health check was spawned I manually edited the path in compute engine but from the Django app logs it seems that it hasn't received any requests, so it results UNHEALTHY and I can't get the ingress to work. How can I make the health check to work in this case? Configuration: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress annotations: kubernetes.io/tls-acme: "true" kubernetes.io/ingress.global-static-ip-name: web-static-ip spec: tls: - hosts: - foo.domain.it secretName: production-tls backend: serviceName: app servicePort: app-https apiVersion: v1 kind: Service metadata: name: app annotations: service.alpha.kubernetes.io/app-protocols: '{"app-https":"HTTPS"}' labels: component: app role: web spec: type: NodePort ports: - port: 12345 targetPort: 8000 protocol: TCP name: app-https selector: component: app role: web type: LoadBalancer apiVersion: apps/v1beta1 kind: Deployment metadata: name: app labels: component: app role: web spec: replicas: 1 template: metadata: labels: component: app role: web spec: containers: - name: app image: [my-image] imagePullPolicy: Always … -
Django: Process extra fields in model save() and pass preselected items to add view
I have model Job. Model has field files that must store list of files like "file1;file2;file3". Delimiter type is not matter. Also i have model File and this one doesn't store data in DB. List of objects generated in FileManager(models.Manager) for each objects request def get_queryset(self): qs = super(FileManager, self).get_queryset() if self.get_updated_qs_list(qs): return super(FileManager, self).get_queryset() else: return qs When i add new Job i must select files for new job. I defined extra field in JobForm: class JobForm(forms.ModelForm): files_choose = forms.MultipleChoiceField(choices=[ (file.full_name, file.name) for file in File.objects.filter()]) class Meta: model = Job fields = ('files_choose', [...other fields...]) I have two issues that I cannot resolve. 1 issue: When I create job from standard add view I want process files_choose before model save. But model don't know about this field cause this one exists only in form. How to pass selected files to model def save(self, *args, **kwargs)? 2 issue: Admin user can mark files from changelist and select action "Create job for files". Next, admin user have to be redirected to standard add view with preselected files. I tried use intermediate page template for action and include JobForm to it. class FileAdmin(ModelAdmin): model = File readonly_fields=('name', 'full_name', 'mdate', 'hash', 'size', … -
Django inspectdb doesn't create foreign keys correctly on a pre-made database
I want to use a pre-made database but after inspectdb generates an auto generated models file the relations of the models are not according to django. For example user_id = models.IntegerField(blank=True, null=True) which should be a foreign key. i.e user_id = models.Foreignkey('User',on_delete=models.CASCADE) -
UserPassesTestMixin superclass - can't add message
I've created a mixin which checks, if user has myGroup attribute set toTrue. If not, they are redirected. In case they are redirected, I want them to see a message. But there is no message in context during rendering the template for some reason. class MyGroupAccessMixin(UserPassesTestMixin): def test_func(self): try: return self.request.user.maklerprofile.is_myGroup except: return False def handle_no_permission(self): if self.request.user.maklerprofile.is_makler: messages.info(self.request, "Keďže nie ste vedení ako člen skupiny MyGroup, boli ste presmerovaní") return HttpResponseRedirect(reverse_lazy("index")) return super(MyGroupAccessMixin,self).handle_no_permission() View class IndexView(LoginRequiredMixin, MaklerAccessMixin, TemplateView): template_name = 'main/index.html' def dispatch(self, request, *args, **kwargs): d = super(IndexView, self).dispatch(request, *args, **kwargs) userprofile = request.user.maklerprofile if not userprofile.is_makler: if userprofile.is_myGroup: return HttpResponseRedirect(reverse_lazy("myGroup:list_nehnutelnost")) return d def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context... user = self.request.user context... return context Do you know where is the problem? -
Django timezone fields don't accept all pytz timezones
Django timezone fields are built upon pytz timezones, but some of the timezones of the latter are not valid for the fields. With a model like from django.db import models from timezone_field import TimeZoneField class TestModel(models.Model): timezone_field = TimeZoneField(default='UTC') def save(self, *args, **kwargs): self.clean() self.full_clean() super().save(*args, **kwargs) If I run (in a shell) import pytz from models import TestModel model = TestModel.objects.get(id=1) for zone in pytz.all_timezones: model.timezone = zone model.save() I get django.core.exceptions.ValidationError: {'timezone': ["Value <DstTzInfo 'Africa/Asmera' LMT+2:27:00 STD> is not a valid choice."]} So it fails first on 'Africa/Asmera' (it fails on others too, e.g. 'GMT+0'). Any idea of how to resolve this inconsistency? At the moment the user can select a timezone on the frontend that will give a backend error (the frontend is built in React and gets the timezones from moment timezone) -
Override settings in django tests
I try to: @override_settings(EMAIL_HOST_PASSWORD='sdsds') def test_email_not sent(self): .... I want to brake down Django SMTP settings and test, but setting didn't get overrided. -
How can I use Django ORM outside without problems?
I use Django ORM for telegram bot which written with PyTelegramBotAPI lib and I had a trouble MySQL Server has gone away, then I increased MAX_CONNECTION and wait_timeout, but it didn't help, now I haven't errors but the bot falls every few hours. -
After I distribute my Django/Django-Rest-Framework project, I can not request its `media` and `static` direcoty
I have a Django/Django-Rest-Framework project, and it only provide the APIs. This is one of the drf APIs, I request the remote ipaddress in the browser: I can not request its static resources. I am not sure whether when Django APIs distribute, I will config the nginx for static and media placement. If need Nginx config for Django APIs static resources, How can I config it? this is an example of nginx vhost configure file: server { listen 80; server_name www.abc.xyz; access_log logs/www.abc.access.log main; location / { root /var/www/html/website/; index index.html index.htm; } location ~ /media/*\.(jpg|png|jpeg|bmp|gif|swf)$ { access_log off; expires 30d; root /var/www/html/python_backend/abc; break; } location /api/ { proxy_pass http://101.20.32.76:8000/api/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /media/ { proxy_pass http://101.20.32.76:8000/media/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } You see the localtion /: location / { root /var/www/html/website/; index index.html index.htm; } because my Django/Django-Rest-Framework is only provide APIs, there is no such index.html files, so I don't know how to config it. and the http://101.20.32.76:8000/media/ I can not access, so the configuration of location /media/ and location /static/ is invalid right? -
creation of servertoserver call api in django
POST /somelink Host: hostname User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Content-Type: application/x-www-form-urlencoded Content-Length: 683 Cookie: xxx Connection: keep-alive access_token=xxx How can i form a api call with this details? I already tried payload={ "POST":"somelink", "Host":"hostname", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language":"en-US,en;q=0.5", "Accept-Encoding":"gzip, deflate, br", "Content-Type": "application/x-www-form-urlencoded", "Content-Length": "683", "Cookie":" xxx", "Connection":"keep-alive", "access_token":"xxx"} headers = {} r = requests.post(url, data=json.dumps(payload), headers=headers) But if i try this way I get 'Connection aborted.', gaierror(-2, 'Name or service not known'. Can anyone help me in this ?