Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending AJAX data to Django view
I am trying to send text through AJAX from a template to a view and save it to a text file, however, I somehow cannot get AJAX to recognize the view. I have a debugging print statement that doesn't go off (sys.stderr.write(repr("I'm in submit text") + '\n')). I have tested AJAX outside of the GET function and it works. I think is has to be an issue with my URL's but I can't seem to find the problem. views.py def submit_text(request): text = '' sys.stderr.write(repr("I'm in submit text") + '\n') if request.method == 'GET': text = request.GET['submitted_text'] sys.stderr.write(repr("Here") + '\n') downloads_folder = ('/Users/<username>/Downloads') file_path = os.path.join(downloads_folder, 'codetext.txt') f = open(file_path, 'w') f.write(text) f.close() return HttpResponse() AJAX $(document).ready(function(){ $('#submit-button').click(function(){ var text; text = editor.getValue(); $.get('/assignments/submit/'), {submitted_text: text}, function(){ $('#submit-button').addClass('btn-sm'); }; }); }); application URL's urlpatterns = [ url(r'^$', views.user_login, name='user_login'), url(r'^logout/$', views.user_logout, name='logout'), url(r'^submit/$', views.submit_text, name='submit_text'), url(r'^(?P<assignment_name_slug>[\w\-]+)/$', views.show_assignment, name='show_assignment') ] project URL's urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^assignments/', include('mainapp.urls')), url(r'^admin/', admin.site.urls), ] -
how to download a file in django
I have few files stored in /media/documents. I've also set the MEDIA_URL and MEDIA_ROOT in settings.py and have given appropriate url in urls.py. So now how can I add a link to the files present in the folder so as to download it? -
Python Django I want remove language code in url(path)
I want remove language code in url for example select en select jp select cn I want it to appear as www.abc.com instead of www.abc.com/jp, www.abc.com/cn. I want to get language code from session and activate it. not url help me urls.py urlpatterns += i18n_patterns( url(r'^', include('web.urls')), prefix_default_language=False ) helpertags.py @register.simple_tag(takes_context=True) def change_lang(context, lang=None, *args, **kwargs): """ Get active page's url by a specified language Usage: {% change_lang 'en' %} """ path = context['request'].path url_parts = resolve(path) url = path cur_language = get_language() try: activate(lang) url = reverse(url_parts.view_name, kwargs=url_parts.kwargs) finally: activate(cur_language) print("%s" % url) return "%s" % url templates.html <ul class="dropdown-menu"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <li><a href="{% change_lang language.code %}" class="btn-lang">{{ language.code }}</a></li> {% endfor %} </ul> -
Django REST client test with specific IP
The Django REST docs read the address from META. So I have to create Whitelist model storing the ip-address/subnet for it. Not a big deal I had all 302 subnets in my database already. from rest_framework import permissions class BlacklistPermission(permissions.BasePermission): """ Global permission check for blacklisted IPs. """ def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists() return not blacklisted Problem: I want to test whitelist from other ip-address rather than 127.0.0.1 How can I do that in pytest? -
How to filter a manytomany field before using to compare to another list for filtering the parent model
I need to filter results for records of individuals such that only users who are members of a program that has a non-expired release of information from the individual. Example: User Sam is a member of Program FoodDelivery Individual Mike has signed a release of information authorizing Program FoodDelivery users to see his home address. The release is good for one year from signing. When Sam goes to list all the individuals he has access to through the FoodDelivery program, Mike should initially show up. A release is expired when expiration_date__lte='today' When the Release expires, Mike should no longer show up. I've got it working to the point where users are shown only the individual records which have any release listing the user's program as authorized. How can I filter that list of released programs to only those where the release isn't expired? ``` python # simplified code for the relevant classes. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") program_list = models.ManyToManyField('Program', blank=True,) class Program(models.Model): name = models.CharField(max_length=100, blank=True, default='') individual_list = models.ManyToManyField( 'Individual', related_name='program_individual_list', through='ReleaseAuthorization', blank=True ) class Individual(models.Model): name = models.CharField(max_length=100, blank=True, default='') authorized_program_list = models.ManyToManyField( 'Program', related_name='individual_authorized_program_list', through='ReleaseAuthorization', blank=True ) class ReleaseAuthorization(models.Model): individual = models.ForeignKey( Individual, related_name="release_authorization_individual", … -
Django Updating Mode; 2 arguments needed 1given
I'm trying to create a form that will update one specific field in my Model, but I'm apparently passing too many arguments. I think I need all of them, so I don't know where the mistake is. Thanks in advance for your help. HTML <div class=assessment_container> <div id=over> <label class=labels>Results:</label> <form action= "{% url 'Project:new_entry' %}" method="POST"> {% csrf_token %} <textarea name="result"</textarea> <input class="save" type="submit" value="Save"> </form> </div> </div> Urls.py url(r'^new_entry$', views.new_entry, name = "new_entry") Views.py def new_entry(request, tableA_id): new = tableA.objects.edit('TableA_id', request.POST) return redirect('/') Models.py class TableAManager(models.Manager): def edit(self, TableA_id, postData): answer = TableA.objects.get(id=TableA_id) answer.result = postData["result"] answer.save() class TableA(models.Model): first_cat = models.CharField(max_length=50) result = models.TextField() def __str__(self): return str (self.first_cat) objects = TableAManager() -
User shows no results in shell
when im running python manage.py shell and i run the following commands, i get this result. What strikes me as odd, is that I have created 2 users in my website that can join groups. >>> from accounts.models import User >>> User.objects.all() <QuerySet []> this is my accounts/models.py file class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) However, when i run these commands below, i get the results i want. >>> from groups.models import GroupMember >>> GroupMember.objects.all() <QuerySet [<GroupMember: test2>, <GroupMember: test2>, <GroupMember: test1> groups/models.py class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships') user = models.ForeignKey(User, related_name='user_groups') def __str__(self): return self.user.username class Meta: unique_together = ('group', 'user') Could someone please explain to me why this happens? Running on python 3.5 in django 1.11 Thank you in advance, you guys are awesome. -
Django viewflow - Permission Denied
I understand that each flow node have six (6) REST API methods. But i don't understand about /activate_next/ and /undo/. When i try both of the methods i got an error Permission Denied. Thank you -
Django with MySQL: OperationalError (1054, "Unknown column '' in 'where clause'") when trying to query over Many-To-Many relationship
I realise that there are many previous questions with similar titles, however they are in a different context. I have not been able to find an answer that relates to Django and my particular situation. I have a Many-To-Many relationship between 2 models in Django, as shown below: class User(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True) def __unicode__(self): return self.user.username class Course(models.Model): users = models.ManyToManyField(User, through='UsersTakeCourses') title = models.CharField(max_length = 128) description = models.CharField(max_length = 1024) def __str__(self): return self.title class UsersTakeCourses(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) mark = models.IntegerField() In Django's views.py, given a username, I want to query the database in order to retrieve all of the courses that particular user is taking. This is my view method: def my_courses(request, user_name): current_user = User.objects.get(username=user_name) current_user_courses = Course.objects.filter(users__pk=current_user.pk) context_dict = {'user_courses': current_user_courses} return render(request, 'FAProject_app/my_courses.html', context_dict) However, when I run the server and try to load the page this view relates to, I get the following error message: OperationalError at /firstaid/my-courses/testuser/ (1054, "Unknown column 'FAProject_app_userstakecourses.user_id' in 'where clause'") I realise this is probably a syntax error in the mySQL query, however I don't know that would happen as Django builds the query itself. Any help is much appreciated. -
Dynamic choice field excluding objects over a certain amount of entries
I am trying to return a list of dates for a form based on the current amount of bookings in a model. The current threshold is set at 6, so If 6 bookings already exist it will exclude it from the list of dates available. Here's my current code def get_available_dates(): dates = next_x_months(12) weds = [last_wednesday(year, month) for year, month in dates] choices = list() for i, wed in enumerate(weds): booking_total = Booking.objects.filter(booking_date=wed) total = booking_total.count() if total >= 6: weds.pop(i) else: choices.append((wed, wed,)) return choices class BookingForm(forms.ModelForm): booking_choice = forms.ChoiceField(choices=get_available_dates()) ... weds returns the following: [datetime.date(2018, 1, 31), datetime.date(2018, 2, 28), datetime.date(2018, 3, 28), datetime.date(2018, 4, 25), datetime.date(2018, 5, 30), datetime.date(2018, 6, 27), datetime.date(2018, 7, 25), datetime.date(2018, 8, 29), datetime.date(2018, 9, 26), datetime.date(2018, 10, 31), datetime.date(2018, 11, 28), datetime.date(2018, 12, 26)] Now, I have some test data in my model. There are 6 entries for 31/1/2018, and 2 entries for 28/2/2018. However, what get_available_dates() is returning drops the 31/1/2018 date (as it should) but also drops 28/2/2018 which it shouldn't. I feel like I'm missing something obvious here. -
Django save data from calling api in views
So i have a views which have a Get and Post request that call to another django project API. But i want to also save the information that i get from the api call. Project 1 has a Appointment table which has these field clinic Id, time, and queueNo. When i do a Post request to Project 2 to make/create an appointment, when successfully created, it will display those 3 field which i want to save into Project 1 Appointment table database. How do i do it ? My Appointment also has a API made so how do i save it there? Here is the code for my view to call api to another django project views.py @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) if r.status_code == 200: # r.text, r.content, r.url, r.json return HttpResponse(r.text) return HttpResponse('Could not save data') -
django-import-export data import use alias
I installed django-import-export app successfully, and I can import data from admin. let's say if I have some database like: name | system_id id | system a | 1 1 | system_a b | 1 2 | system_b so the system_id is a foreign key. The question is I want to import data from excel: name | system c | system_c d | system_d How can I do to make the data corresponding for each other. So I can use the real name of system in my excel. -
Django: import error in test
I have a new project in django, without any test. I think that it should say that all is ok, because there are not tests when I try python manage.py test. Instead of that, I obtained this exit: shell screen Any one know why? -
Django one to many opposite
I have an API endpoint returning pets and their owners. Each owner has a name and one or more pets Each pet has a name and one owner Example Django models: class Owner(models.Model): name = models.CharField(max_length=200) class Pet(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField(max_length=200) I've configured my API to return JSON data like this: [ { "id": 2, "name": "Scotch", "owner": { "id": 2, "name": "Ben" } }, { "id": 3, "name": "Fluffy", "owner": { "id": 1, "name": "Fred" } }, { "id": 1, "name": "Spot", "owner": { "id": 1, "name": "Fred" } } ] Example DRF serializers: class OwnerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Owner fields = ("id", "name") class PetSerializer(serializers.HyperlinkedModelSerializer): owner = OwnerSerializer() class Meta: model = Pet fields = ("id", "name", "owner") While that's all fine and dandy, I'd actually like to have an endpoint that returns a list of owners and their pets. So I'd get this data instead: [ { "id": 1, "name": "Fred", "pets": [ { "id": 1, "name": "Spot" }, { "id": 3, "name": "Fluffy" } ] }, { "id": 2, "name": "Ben", "pets": [ { "id": 2, "name": "Scotch" } ] } ] How can I achieve that output? -
unbound method save() must be called with MyModel instance as first argument
I'm using setattr() to set attributes of a new object of a Django model. obj = apps.get_model(app_label="theme", model_name="MyModel") setattr(obj,"myCol",100) obj.save() I got this error: TypeError: unbound method save() must be called with DataPopulationTracts2016 instance as first argument (got nothing instead). I want to save the new instance of MyModel to the model, using get_model() and setattr() to make a new instance of the model and set its attributes. How do I make get_model() and setattr() work with save()? -
Running the Django REST framework example with Django 2.0
I'm trying to adapt the example shown on http://www.django-rest-framework.org/ to Django 2.0, but I'm running into an error. Firstly, I created a project using django-admin startproject rest_example. I've added 'rest_framework' to the INSTALLED_APPS list in settings.py and added the REST_FRAMEWORK variable: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Here is my adapted urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')) ] The problem is that when I python manage.py runserver and navigate to localhost:8000, I get a 404: Similarly, if I navigate to localhost:8000/api-auth/, I get Why is this not working? -
block tag will not show anything
im running two apps. one app is mapped to localhost:8000/blog/ the other is mapped to localhost:8000/email/ everthing works fine so far. BUT when im on my blog (localhost:8000/blog/) it wont show the contact block. when im on my contacts (localhost:8000/email/) it wont show the blog block. my folder structure: ---templates | index.html | +---blog | blog_detail.html | blog_list.html | ---contact email.html success.html -
internal server error: /robots.txt
I am getting an internal 500 server error but the site is not crashing. Below is what comes out on the console and this happens on every route call, both http and api. [23/Jan/2018 16:12:49] "GET /robots.txt HTTP/1.1" 500 58587 [23/Jan/2018 16:12:49] "GET /checkout HTTP/1.1" 200 192777 Internal Server Error: /robots.txt Traceback (most recent call last): File "/usr/local/lib/python2.7/dist- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist- packages/django/utils/deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "/usr/local/lib/python2.7/dist- packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' Here is the contents of my robots.txt file: User-agent: ia_archiver Disallow: / User-agent: Googlebot Disallow: / User-agent: Slurp Disallow: / User-agent: MSNBot Disallow: / User-agent: * Disallow: / I am not sure which files I should starting looking into to traceback the error as I am a junior dev working alone. Would you guys be kind to guide me in the right direction? -
possible to add list of selected value together in django?
for example I have this as my list in django [ {'price': Decimal('45.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('45.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('45.00'), 'total': 2L, 'quantity': 1} {'price': Decimal('40.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('40.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('49.00'), 'total': 1L, 'quantity': 1} ] What I want my output to be is that the same price will be added togther but there's another catch which is, same price times the total. For the example above, what I want as my output would be [ {'price': Decimal('180.00'), 'total': 4L, 'quantity': 1} {'price': Decimal('80.00'), 'total': 2L, 'quantity': 1} {'price': Decimal('49.00'), 'total': 1L, 'quantity': 1} ] since price 49 only has total of 1, there is no changes to it. As for price 40 it's total of two, so the output is 80 as for price of 45 it's total of 4 so 45*4=180 I thought of the javascript lodash which this situtation came up and googled there is something called pydash but somehow I couldn't figure out the way to use it though. Is anyone able to give me an idea how this can work with minimum loops? Thanks in advance. -
Django pass bulk values by checkbox
I want to delete multiple rows from a table by checkbox this is my template : {% if mystocks.all %} <table id="example" class='table table-list-search table-responsive table-hover table-striped bordered" width="100%'> <thead class="alert alert-info"> <tr> <th>name</th> <th>brand</th> <th>id</th> <th> suffix</th> <th>command</th> <th>price</th> <th>days </th> <th>situation</th> </tr> </thead> {% for item in myst %} <tr> <td><input type="checkbox" name="todelete" value="{{ item.id }}"></td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.suffix }}</td> <td>{{ item.comment }}</td> <td>{{ item.price }}</td> <td>{{ item.date|timesince }}</td> <td>{{ item.confirm }}</td> <td><a href="{{ item.id }}" onclick="return confirm('Are you sre?');">delete</a> </td> <td><a href="/stock/{{ item.id }}">Edit</a> </td> </tr> {% endfor %} </table> {% else %} <p style="margin:2em" > You have no stock</p> {% endif %} <form class="" method="post"> {% csrf_token %} <input type="submit" name="delete" value="Delete Items" /> </form> and this is my view : def mystocks_view(request): if request.method=='POST': todel = request.POST.getlist('todelete') print(todel) Stocks.objects.filter(user=request.user,id__in=todel).delete() But it returns null ! and print(todel) prints [ ] How can i get the value of multiple checkbox in the view? -
Django REST framework not picking up API endpoint
I'm trying to refactor an API to use the Django REST framework. I've changed my urls.py to the following (still in Django 1.11): from django.conf.urls import url from . import views from rest_framework import routers, serializers, viewsets from .serializers import SessionSerializer from .viewsets import SessionViewSet router = routers.DefaultRouter() router.register(r'^api/v1\.0/feedback/$', SessionViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^api/v1\.0/profile/$', views.get_profile), url(r'^api/v1\.0/update_profile/$', views.update_profile), url(r'^api/v1\.0/update_password/$', views.update_password), url(r'^api/v1\.0/sessions/$', views.get_session), url(r'^api/v1\.0/user/$', views.get_user), url(r'^api/v1\.0/sessions/send_schedule_request/$', views.send_schedule_request), url(r'^api/v1\.0/sessions/confirm_session_time/$', views.confirm_session_time), url(r'^api/v1\.0/password_reset/$', views.password_reset), url(r'^api/v1\.0/me/apn/$', views.save_apn), url(r'^api/v1\.0/confirm_activation_code$', views.confirm_activation_code), url(r'^api/v1\.0/update_user_via_activation_code$', views.update_user_via_activation_code), url(r'^api/v1\.0/questions/$', views.get_questions), url(r'^api/v1\.0/answers/$', views.save_answers), # url(r'^api/v1\.0/feedback/$', views.record_feedback), url(r'^session_types/$', views.session_types), url(r'^send_custom_notification/(?P<id>\d+)/$', views.send_custom_notification, name='send_custom_notification'), url(r'^admin/lucy_web/send_session_time_notifications/(?P<user_id>\d+)/(?P<session_id>\d+)/$', views.send_session_time_notifications, name='send_session_time_notifications'), url(r'^admin/lucy_web/app_activate/(?P<id>\d+)/$', views.app_activate, name='app_activate'), url(r'^admin/lucy_web/create_activation_code/(?P<id>\d+)/$', views.create_activation_code, name='create_activation_code'), ] However, if I python manage.py runserver and go to localhost:8000/api/v1.0/feedback/, I get a 404 error response: It seems like the r'^api/v1\.0/feedback/ endpoint is not being picked up, even though it is passed as an argument to router.register(). Any ideas why this is not working? -
django-embed-video wagtail can not display saved videos
I am trying to display the Embed saved videos on my homepage, but for some reason only the object class divs are created,the image itself with its title don't show up. This is my models.py class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), # InlinePanel('home_images', label="Gallery images"), InlinePanel('video') ] class VideoBasedModel(models.Model): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='video') video = models.ForeignKey( 'wagtail_embed_videos.EmbedVideo', verbose_name="Video", null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [ EmbedVideoChooserPanel('video') ] template_name = 'home/homepage.html' and this is my home_page.html {% block list %} <div class="lists"> <div> <!-- List Nunti --> <div class="title"> <hr /> <h3>Nunti</h3> <hr /> </div> {% for item in page.video.all %} <div class = 'object'> {% video item.video 'small' %} </div> {% endfor %} </div> </div> {% endblock %} Am I missing something, does django-embed-video have a default template where the code for the embed videos need to go? -
Create dict based on queryset result
Imagine I get some queryset: my_queryset_result = ...values('my_column').distinct() if I print it it comes out like: <QuerySet[{'my_column':'foo'}{'my_column':'bar'}]> I need to create a dictionary with the result, like this: {'foo':0, 'bar':0} Can it be done? Or should I use a different approach? -
When working with Python 3 and Django do you modify pip packages when debugging?
I am coming from PHP and playing with Python at the moment. In PHP, composer would install dependencies into ./vendor within your project dir and you can modify them in any way when working. This is usually useful when debugging or when you want to try something out or even to look up some function signature quickly. In Python I used pip to install dependencies off a provided requirements.txt file but the packages get installed into a system dir and it doesn't look like they are meant to be modified. What is your workflow for Python apps: do you modify pip packages and if yes, how do you do that? -
how create multiple objects using drf from a single payload
# in views under POST method json_data = json.loads(request.body.decode('utf-8')) display_name = json_data['displayName'] job_url = json_data['url'] start_time = json_data['timestamp'] execution_url = json_data['url'] execution_number = json_data['number'] # #create stage execution # serializer = StageExecutionSerializer(request.data) # if serializer.is_valid(): # serializer.save() # #create platform # serializer = StageExecutionSerializer(request.data) # if serializer.is_valid(): # serializer.save() I am struggling to figure out the most efficient way to take request.data and create objects leveraging DRF from this data. Passing in display_name, job_url, etc. to the serializer doesn't make sense to me because those have already been deserialized by json.loads, however this is the route I might have to take. The ideal scenario would be to pass in request.data to each serializer, and have it automagically know which key/values to take when creating object. Is this possible?