Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve data from Models with Foreign Keys
I have a doubt about getting the data from another Model using ForeignKeys. I got a Salesman in a model class Salesman(models.Model): name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) def __str__(self): return "%s" % (self.name) Store model class Store (models.Model): name= models.CharField(max_length=50) phone = models.IntegerField() contactMail = models.EmailField() def __str__(self): return "%s" % (self.name) And a Product Model class Product (models.Model): name = models.CharField(max_length=40) description = models.CharField(max_length=150) price = models.CharField(max_length=7) store = models.ManyToManyField(Store) def __str__(self): return "%s" % (self.name) I was trying to get the name of the Store throught the Salesman because later I need to get Products associated in the Store and i want to use the same process or something similar to populate a HTML table with Products in that specific Store. I already got a Salesman called JohnSmith, in Store named LeBlanc. Pencil and Book are Product associated in LeBlanc In my view: def load_store(request): salesDude = Salesman.objects.filter(name='JohnSmith') print(salesDude) // <QuerySet [<Salesman: JohnSmith>]> <- gotcha Then I try to use the Salesman object to retrieve the ID from the Store but i'm stuck here. Forward, i need the name of the store to be recovered and used as a filter to retrieve the … -
ManyToMany models relationship Django
I have two models: class University(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=30, null=True, blank=True) country = CountryField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) departments = models.ManyToManyField(Department) class Department(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I want to University have many Departments and vice versa which works fine. But I also want to store more departments individually for one university. For instance: University1 has Department1 and Department2. University2 has Department1. I want those departments store individually for each university. Now when I update Department1, ofcourse every University which has that school will see changes. I don't want that. I want to update Department1 but only for the University1 record. Department1 in University2 shouldn't be updated. I assume that adding through option with intermediate model wouldn't help. What's the best solution? -
Display pop-up modal when user not in designated Django group
Currently, I'm redirecting users to the login page when they aren't in the group required by the page they're attempting to view with the below decorator. What I'd like to do is pop up some sort of "you aren't authorized" modal when they try to access a part of the site that requires a group they aren't in, but I'm a little fuzzy on the best way to go about passing the groups / requirements / logic / wiring it all together on the front end. def group_required(group, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user is a member of a specific group, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. Ex: @group_required('group',login_url='login') """ def check_perms(user): if isinstance(group, six.string_types): groups = (group, ) else: groups = group # First check if the user has the permission (even anon users) if user.groups.filter(name__in=groups).exists(): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url) -
How to show (the contents of) a subdomain as a path/subfolder with nginx
I have 2 websites: api.example.com (a Django app) example.com (a blog with Ghost) This is my current nginx setup for my blog (root domain) server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name example.com root /usr/share/nginx/html; index index.html index.htm; # this was created by ghost one click deploy on DigitalOcean location / { proxy_pass http://localhost:2369; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_buffering off; } I'm trying to make it so that I can go to example.com/api and see the contents of api.example.com, but am not redirected and the url in the addressbar should show example.com/api. I don't even know the right term for this.. Proxying? Masking? -
Reordering dropdown list on Modelform in Django
I am using Status table with 3 statuses used for reports. Each report is going through 3 phases (non-numerical), but now I have to implement new phase that has to be between phase 2 and 3 in earlier sequence. Status table has only 2 columns: status_id (pk) and type The problem I got is when I am showing drop down list (in modelForm), values appear sorted by primary key. What is best practice solution for this? p.s. It feels stupid to change the "type" in the database in order to get it right -
django-python3-ldap Sync Users Automatically and Securely
I have a Django app with Active Directory authentication using django-python3-ldap. I need to sync users from AD to auth_user each day so I can assign them to groups. Therefore, I thought I could use the python manage.py ldap_sync_users command. This command works well, but it requires AD credentials to be in the settings.py file like this: LDAP_AUTH_CONNECTION_USERNAME = "username" LDAP_AUTH_CONNECTION_PASSWORD = "password" Having the credentials in cleartext is not ideal, and putting it in an environment variable is also not ideal. Creating an AD account for the express purpose of running this command is not an option. How would I schedule this command to run without exposing credentials somewhere on the server? -
On Django with a MySQL backend, "Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='"
In a Python 2 Django app, I'm defining a string with a 'money with wings' emoji: # -*- coding: UTF-8 -*- MESSAGE = "Stash some cash 💸" This passes the pylint linter fine. However, I also have a model Message with a content field, and if I try to write to there, I get an error message: Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '=' Below is the full stack trace. How can I fix this? Since utf8mb4_general_ci is MySQL-specific, I suppose that the encoding the database is currently in, and utf8_general_ci is the encoding that I'm defining my string to be. How can I define my string to be in utf8mb4_general_ci instead of utf8_general_ci? /app/venmo_platform/current/venmo/communication/services/notification_service.pyc in get_message_for_notification(message_content) 99 100 def get_message_for_notification(message_content): --> 101 message, _ = Message.objects.get_or_create(content=message_content) 102 return message /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/manager.pyc in manager_method(self, *args, **kwargs) 125 def create_method(name, method): 126 def manager_method(self, *args, **kwargs): --> 127 return getattr(self.get_queryset(), name)(*args, **kwargs) 128 manager_method.__name__ = method.__name__ 129 manager_method.__doc__ = method.__doc__ /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/query.pyc in get_or_create(self, defaults, **kwargs) 403 self._for_write = True 404 try: --> 405 return self.get(**lookup), False 406 except self.model.DoesNotExist: 407 return self._create_object_from_params(lookup, params) /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs) 326 if self.query.can_filter(): 327 clone = clone.order_by() --> 328 num = … -
intermediate pages for a custom admin button
I have made a button in my django admin. template custom_change_form <input type="submit" value="Test Peer" name="_peer-test"> Then in admin.py def response_change(self, request, obj): if "_peer-test" in request.POST: self.message_user(request, "Peer Tested") return HttpResponseRedirect(".") return super().response_change(request, obj) And it works just fine. Now I want to add intermediate page to it. Normally by the standard action from admin you can do this!! def export_selected_objects(modeladmin, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect("/export/?ct=%s&ids=%s" % (ct.pk, ",".join(selected))) The question is how can I apply this to my custom button. so dat I can redirect to a view made by me and passes the variables. -
How to dynamically update sqlite3 db?
I have a sqlite3 db and I edit it by django-admin panel. Also I have a .py file which handles this db. How to make it so that when the .py is running, if I change the database through the django-admin panel, the program also changed? -
Django models getting data where there is a relationship
I have three Django Models: @python_2_unicode_compatible class GroupInvoice(models.Model): group = models.ForeignKey('Group', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return str(self.invoice.number) + ' ' + self.group.group_name @python_2_unicode_compatible class ProviderInvoice(models.Model): provider = models.ForeignKey('Provider', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) paid=models.BooleanField() created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.invoice.invoice_number + ' ' +self.provider.first_name @python_2_unicode_compatible class Invoice(models.Model): number = models.IntegerField(null=True, blank=True) #NOT THE INVOICE ID might be changed by user total = models.DecimalField(max_digits=11,decimal_places=2) # 10 digit max, date = models.DateField(auto_now=False, auto_now_add=False) paid = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return 'PK: ' + str(self.pk) + ' InvoiceID: ' + str(self.number) + ' ' + str(self.total) I am still a bit fuzzy on relationships in the models, but I WAS sending to a view a list of all invoices: class InvoiceListView(TemplateView): template_name = 'ipaswdb/invoice/list.html' def get(self, request, *args, **kwargs): context = super(InvoiceListView, self).get_context_data(**kwargs) status_requested = None invoices = None if request.GET.has_key('status'): status_requested = request.GET['status'] status_requested = status_requested.split('/')[0] # drop any trailing / (forward slashes) if status_requested: invoices = Invoice.objects.all() invoice_status = 'all' else: invoices = Invoice.objects.all() invoice_status = 'all' context['num_invoices'] = len(invoices) context['invoices'] = invoices context['invoice_status'] = invoice_status return render(request,self.template_name,context) It turns out I would really like to get … -
Python Django 'TypeError: object is not iterable' when trying to iterate over models query set
All, I've read through previous posts of a similiar issues and none seem to solve my problem. I'm making a website for my fantasy football league as my intro to Django. However, I'm running into an error every time I try to insert content from my models into the html template. The error shown is 'TypeError: 'PastSeasons' object is not iterable', with 'PastSeasons' being the model. I know the postgresql table and db is set up properly because I can view it via pgadmin4 and through the django /admin site. I can also run the 'python manage.py shell' and query the model, return a queryset, and then iterate through that queryset using the exact same syntax as the views.py file. Here is the django models.py file: from django.db import models class PastSeasons(models.Model): year = models.IntegerField() place = models.IntegerField() team_name = models.CharField(max_length=100, unique=False) owner = models.CharField(max_length=100, unique=False) wins = models.IntegerField() losses = models.IntegerField() ties = models.IntegerField() points_for = models.FloatField() points_against = models.FloatField() def __str__(self): return str(self.year) Here is the subsequent views.py file: from django.shortcuts import render from .models import PastSeasons def past(request): past_list = PastSeasons.objects.all() past_szn = {'past_szn': past_list} return render(request, 'basic_app/past_seasons.html', past_szn) Lastly, here in the html template (there's additional … -
Django Relation between two models
I am very new to Django. Can you please give a boilerplate of models how to relate two models between each other. --Below is Section model from articles.models import Article # Create your models here. class Section(models.Model): #associations user = models.ForeignKey(settings.AUTH_USER_MODEL) article = models.ForeignKey(Article) #Article --Below is Article model from sections.models import Section User = settings.AUTH_USER_MODEL # Create your models here. class Article(models.Model): owner =models.ForeignKey(User, null=False) sections = models.ManyToManyField( Section ) However. I got the below error: ValueError: Cannot create form field for 'article' yet, because its related model 'articles.models' has not been loaded yet Thanks All B -
Mezzanine Django Cartridge conectar con un servicio de pagos en mexico
Contexto: Uso un servidor local en fisico, con apache 2, el sitio ya tiene productos pero es necesario implementar la recepccion de pagos online. Cartridge 0.13.0 Mezzanine CMS Estoy tratando de agregar un método de pago a Cartridge en México, pero los que están recomendados en la documentación de Cartridge no estan disponibles en mi país. Braintree Egate Authorize.Net Stripe¶ Mi pregunta es si ¿alguien en mexico logro conectar un servicio de pagos con su sitio web? -
Resty Resolver issue Python
I was following a tutorial: https://medium.com/@ssola/building-microservices-with-python-part-i-5240a8dcc2fb from connexion.resolver import RestyResolver import connexion items = { 0: {"name": "First item"} } def search(): return items if __name__ == '__main__': app = connexion.App(__name__, 9090, specification_dir='swagger/') app.add_api('my_super_app.yaml', resolver=RestyResolver('api')) app.run() I keep getting the same error: ImportError: No module named api Does any one know how to resolve this error? I pip installed all the dependencies -
inserting data in a DateTimeField() in Django by using datetime-local
Please, I am creating a to-do list app as my first django project. My form is not valid because I am trying to insert DateTimeField in django using datetime-local. I did research, I discovered I need to do a custom model so I parse the datetime-local field. Pls guide me on how to create a custom model field. -
save() and object.create note worked in django
I'm new, trying to save and fail gives an error message, whsts do? p.save() and p=Post.objects.create not worked enter image description here -
Search and filter a list of lists
thanks for your time, I'm new in Python so I got this list of lists: raw-list = [ [((733, 706), (810, 733)), 'Joe'], [((748, 613), (815, 637)), 'Harold'], [((748, 614), (815, 638)), 'Harold'], [((815, 614), (882, 638)), 'Walter'], [((816, 614), (883, 638)), 'Walter'], [((883, 613), (950, 637)), 'Parker'], [((883, 614), (950, 638)), 'Parker'], [((902, 694), (969, 718)), 'Ernesto'], [((950, 613), (1017, 637)), 'Max'], [((950, 614), (1017, 638)), 'Max'] ] I would like to delete all the lists that already have a name that has been mentioned previously to obtain this: filtered_list = [ [((733, 706), (810, 733)), 'Joe'], [((748, 613), (815, 637)), 'Harold'], [((815, 614), (882, 638)), 'Walter'], [((883, 613), (950, 637)), 'Parker'], [((902, 694), (969, 718)), 'Ernesto'], [((950, 614), (1017, 638)), 'Max'] ] How can I achieve that?, Thanks to everyone! -
Time SQL Queries in Django
Is there a way to time sql queries in Django? I know there's such thing in dj debug toolbar but I just need to display time on my web-page. Since I can get a number of queries with: len(connection.queries) Maybe there's a similar way to get the time? -
How to get the current URL within a LoginRequiredMixin,UpdateView (Django template)?
I want to edit a data. For that I have to click on a button from my main page. I would like by clicking on the edit button, send the url to the page edition. And once I finish the changes, I'll want to go back to my main page. Here is the sequence of actions in pictures: --------------------------------------- Here is the view: class A_UpdateView(LoginRequiredMixin,UpdateView): template_name = 'page_form.html' login_url = '/login/' form_class = A_Form model = Team def form_valid(self, form): g_urls = self.request.POST.get('id_path') object = form.save(commit=False) form.instance.last_user = self.request.user.username self.object = form.save() return super().form_valid(form) def get_success_url(self): return reverse('g_urls') Here is the template: <form class="btn-group" id="login_form" method="get" action="{% url 'A_UpdateView' pk=f.pk %}"> <input type="hidden" name="id_path" id="id_path" value = "{{ request.build_absolute_uri }}" > <button class="btn btn-success" id="aaa" name="aa" type="submit"></button> </form> Here is the template to edit: <form method="POST" class="post-form"> {% csrf_token %} <!--{{form.as_p}} --> <table class="table table-bordered table-fit" border="0" > {{ form }} </table> <button type="submit" class="save btn btn-default">OK</button> </form> Thank. -
Ionic To Django POST data auto name change
Hi I am building an application in which my Ionic App need to send a post message to Django Backend. My data at Ionic end during pos seem to be like this // This is the value from ion-select with multiple set true let data = {'selectedId':[1,2,3,4,5,6]} In my django request.POST the data is converted like this <QueryDict : {u'selectedId[]' : [u'1',u'2',u'3',u'4',u'5']}> Why does the key value automatically converted from "selectedId" in Ionic to "selectedId[]" if i try to get the array value in Django by performing request.POST['selectedId[]'] this give me the length of the array 5 request.POST['selectedId'] this give me a MultiValueDictKeyError -
Django saves and updates slow down on partitioned table, but queries are much faster
I have identical tables in Postgres9 and Postgres10, except that the Postgres10 table is partitioned by state. When I make a query like this, it is about 10 times faster on the partitioned table than on the Postgres9 unpartitioned table. hooray! parcels = Parcel.objects.filter(state='15', boundary__intersects=polygon) But when I try to make an update like: for parcel in parcels: do something parcel.save() It is about 100 times slower on the partitioned table than on the Postgres9 version. Is this a common issue with partitions or with Postgres10? -
Uploading image into media directory in a form just by changing the field
i need when i just change the file field ajax send it to the save function in view and upload my image , if you have any better solution i waiting to hear of you tnx index.html <form action="{% url 'home:save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img" id="img"/><br/> <input type="submit" name="submit" value="Upload" /> </form> views.py def save(request): myfile = request.FILES['img'] fs = FileSystemStorage() filename = fs.save('easd09dasd.jpg', myfile) return HttpResponse('saved') js.js <script> $(function () { $('#img').change(function () { var file_data = $("#img").prop("files")[0]; var form_data = new FormData(); form_data.append("file", file_data); $.ajax({ type: 'POST', cache: false, contentType: 'multipart/form-data', url:{% url 'home:save' %}, data : form_data, enctype: 'multipart/form-data', processData: false, datatype:'json', }) }) }) </script> -
How do i integrate Django with Dialogflow?
I am new to Django and Dialogflow. I need to build a chatbot and need to code some backend logic in python and i don't know how to integrate them together. Any tutorials or links would help. Thank You -
Django debug toolbar - java error cannot find djdt
in console I am seeing the error below for debug toolbar: ReferenceError: Can't find variable: djdt Global Code — toolbar.js:306 I have everything setup as per https://django-debug-toolbar.readthedocs.io/en/latest/installation.html It did work but all of sudden no longer is and I'm pretty sure I didn't do anything to turn it off. anyone else come across this one? Thanks settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'api.apps.ApiConfig', ... 'storages', 'imagekit', 'django_celery_results', 'debug_toolbar', 'simple_history', 'crispy_forms', 'rest_framework', ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] INTERNAL_IPS = ('127.0.0.1') def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { 'JQUERY_URL':'', "SHOW_TOOLBAR_CALLBACK" : show_toolbar, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns -
filling django forms based on choice with models data as initial data
Need help regarding adding model class fields as initial data to our forms data. models.py class SourceCode(models.Model): source_description = models.CharField(max_length=80,unique=True) source_urls = ArrayField(ArrayField(models.TextField(blank=True),),blank=True,null=True) source_results = JSONField(blank=True,null=True) def __str__(self): return self.source_description forms.py class SourceForm(forms.Form): source_description = forms.ModelChoiceField(queryset=SourceCode.objects.all(),required=True) source_form_urls = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Enter URLS Here'})) I had created Source1 object & added https://stackoverflow.com value in source_urls field. Here's how it looks like: As soon as i select Source1 from forms.ModelChoiceField, i want it to show the source_urls field data of source_urls based on object selected by user.