Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stack trace exception while saving object to database Django SQLITE3
I had a really tough time to get fix this issue please help if you know this. I have a project on django, It contain model with two fields, one is of type foreign key and other one is jsonfield. When it goes to save object in database, it doesn't get saved instead it throw exception. I don't know what's the issue is. But issue is only specific to sqlite3 database. it is working fine with other databases. I am pasting stack trace and code. it throws exception on this line student_record_obj.save() Stack trace: Internal Server Error: /tableapp/postdata/ Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python35\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line β¦ -
Django Model Settings, but not Per-Object
I'm trying to set a custom set of variables once per model. For example, a model object might have the variables: has_meetings has_comments has_attachments What I'm trying to accomplish is to specify the settings once per model, not once per instance of the model. Originally, I tried: class BaseModel(models.Model): has_comments = Boolean(default=True) has_meetings = Boolean(default=True) But then I realized that will propagate in the admin to every single instance of the object. What I want to do is something that applies to any sub-classes of BaseModel, but not on every instance. Has anyone come across this issue? What was the fix? -
Python Django Mezzanine - TypeError coercing to Unicode: need string or buffer, int found
Making an admin page in Mezzanine for my Django app, I am getting this type error - TypeError at /path/ - coercing to Unicode: need string or buffer, int found I'm not trying to do any type coercion or anything like that. admin.py extra_fieldsets = ( ("General", { "fields": ("id1", "id2"), }), ) class appAdmin(admin.ModelAdmin): fieldsets = extra_fieldsets search_fields = ("id1", "id2") admin.site.register(app, appAdmin) models.py class app(models.Model): id1 = models.IntegerField(primary_key=True, null=False) id2 = models.IntegerField() class Meta: managed = False verbose_name = "app" verbose_name_plural = "apps" db_table = u'"app_table"' def __unicode__(self): return self.id1 I added this admin page at the same time as two others, both of those following the same general format and working properly (With different fields, of course). Can't seem to figure out why this one has some sort of type coercion error happening. -
Django group by dates and SUM values include SUM zero
Django group by dates and SUM values include SUM zero values = self.model.objects.values('datetime').annotate(data_sum=Sum('data')).filter(datetime__range=( ? ) ) I want to add all the values of each day in the month. Include days on which the sum is zero. Why sum operate on both datetime and data? I tried to everywhere on django doc, here on stack but didn't find something coherent with my problem. Any suggestion ? There is a post similar to this, but it does not display the sum of the day values that is zero Django group by dates and SUM values +---------------------+-----------+ | datetime | SUM(data) | +---------------------+-----------+ | 2013-07-01 | 489 | | 2013-07-02 | 2923 | | 2013-07-03 | 984 | | 2013-07-04 | 2795 | | 2013-07-05 | 0 | | 2013-07-06 | 1365 | | 2013-07-07 | 1331 | | 2013-07-08 | 0 | | 2013-07-09 | 919 | | 2013-07-10 | 722 | | 2013-07-11 | 731 | | 2013-07-12 | 489 | | 2013-07-13 | 2923 | | 2013-07-14 | 984 | | 2013-07-15 | 2795 | | 2013-07-16 | 0 | | 2013-07-17 | 0 | | 2013-07-18 | 0 | | 2013-07-19 | 0 | | 2013-07-20 | 919 β¦ -
Use custom function in ModelViewSet with Django Rest Framework
Django 2.0, Python 3.6, Django Rest Framework 3.8 I'm still pretty new to Django Rest Framework, and I'm trying to wrap my head around the logic for using functions in a viewset (and if this is even the correct place to include a function). Basically, I would like to send out an email when a user posts something to the api in this specific viewset. I tried using the send_mail function, but have been unsuccessful. I have the following class based view: class SendInviteView(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer @action(methods=['post'], detail=True) def send_the_mail(self, request): send_mail( 'Invitation', 'Try our app!', 'exampleemail@gmail.com', ['examplerecipient@gmial.com'], fail_silently=False, ) [The Model and Serializer are pretty basic, and I don't think will be required for the context of this problem, basically just an EmailField(). I eventually plan to use the input of that email field to replace examplerecipient@gmail.com, but for now I just want to understand how to add functionality to viewsets] This results in an error when running python manage.py check I have my email client set up through sendgrid and am able to successfully send emails to users who ask to have their passwords reset through rest-auth, but I don't understand how sending an β¦ -
How can I pass through arguments using redirect?
I would like to let the user know that their information has been updated once they have filled out the form and clicked the "update" button. Right now everything works but after they click the "update" button they get redirected to their profile to see the new information. I'd like to also have a little note that says something like "Your profile has been updated" on that HTML template. I know that I can passthrough arguments using the render method, but I'm wondering how/if it's possible to do so with redirect. Here's my edit_profile function from views.py: @login_required def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse("view_profile")) else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) Is there any way to pass through a variable that contains a message that I can display in my HTML template like this using the redirect method? <!-- if profile is updated succesfully --> {{ success }} Thanks -
Dynamic Datagrid Based on Search Criteria Checkboxes Using Django and jQuery
Django jQuery Dynamic Datagrid I have a general strategy question. Django and jQuery. I'm loading a bunch of "accident" objects into the template. Every accident has lots of attributes and related objects, like people involved, severity, body part, hospital, etc. I have lots of checkboxes to select multiple criteria. So you can select "right arm", "torso", "Mayo Clinic", and "John Doe", for instance. There will also be a button to do an AND search (accidents displayed must match all selected criteria), or an OR search (accidents displayed can match any of the selected criteria). As these things are selected I want the spreadsheet on the bottom of the page to fill automatically with appropriate entries based on the criteria selected. I feel like I know enough django and jQuery that I could hack together something that would work but I'm worried about making it harder than it needs to be, or about the next developer coming along and thinking "What was this guy doing??" This seems like a common enough problem that there's probably a best practice. Links to tutorials would also be appreciated! Thanks in advance!! -
ManyToMany on Self Model: How to add new instances to this relation
I have a Profile class, which extends the User class, and I would like to allow every profile to be able to bookmark other user profiles. I've set up the following: class Profile(models.Model): # some fields e.g. name, email bookmarked_profiles = models.ManyToManyField("self") Now, I'm a bit confused, for example, how would I 'bookmark' new profiles for a given profile instance? E.g. something like # add new bookmark for profile instance p = Profile.objects.get(pk=1) profiles_to_bookmark = Profile.objects.all() p.bookmarked_profiles = profiles_to_bookmark I would also like to know the number of bookmarked profiles e.g. p.bookmarked_profiles.count() -
Django Dynamic Views/routes?
I recently received a request from my boss on putting together a simple asset management application that can be deployed (with customization) for multiple clients. The idea here is not to have a huge complicated interface where you build tables/models etc (if possible anyway). What I was considering was using django and the Django-rest-framwork to create an api. What I'd like to be able to do is get everything set up and then create the actual asset models that the specific client needs to track. The trick here would be - I don't necessarily want to have to also go and routes, setup serializers etc. So I'm wondering if there's a way to generate these dynamically. Or if the only way to do this is create a generic asset model, generic attribute model etc, and create entries from there. The reason for wanting to do it this way is because it allows for easily coding logic into the models. Anyway, I'm open to other technologies that might do this better, or if there's a better way to accomplish this. Hopefully that's clear! -
How to fix django appendslash runtime error?
So basically I have a pdf.html that is called upon by my view. My form in the pdf.html is as follows: <form action="{% url "soapdf:submitemail" %}" method="post"> {% csrf_token %} {{ emailform }} <input type="submit" value="Submit"> </form> The corresponding function on views.py looks like this: def submitemail(request): if(request.method=='POST'): return HttpResponse(request.POST['text_email']) else: return HttpResponse("false") and my urls.py looks as follows: app_name = 'soapdf' # use this to namespace the application so that you can use the url tagging scheme urlpatterns =[ path('',views.get_pdf,name='get_pdf'), path('submitemail/',views.submitemail,name='submitemail') ] However on clicking the submit button I get the following error. My redirect has the slash but still doesnt work. RuntimeError at /submitemail You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:8000/submitemail/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Any Ideas on how to fix this runtimeerror -
Django - get_object_or_404
I'm currently building an app with Django and ran into a problem when doing a get_object_or_404() request. object = get_object_or_404(Model,some_field=some_parameter) where some_parameter = cleaned_data['some_parameter'] in a form. From the values in my DB for some_field for each model object, I expected the object to be returned, except that I get a 404. So then I print() out the list of values for the some_field field by doing.. values = Model.objects.all().values_list('some_field', flat=True) ...which returns... <QuerySet [u'value_1', u'value_2', u'value_3']> ...where value_2 for example is the some_parameter value that I entered in my form! Anybody know why the object isn't being found even though the parameter I entered in the field actually matches up with one of the object fields? Thanks -
Django Streaming Output File
I am implementing a program in django, the goal is to find sales difference from months to months. Users upload 2 files then hit execute button, afterwards, the user will download results.csv automatically(once the program finished running) which contains sales difference and that csv file will be created in /pythonprojects/djangoprojects/results.csv. Below is the code to push out the file to the user. def results(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="results.csv"' writer = csv.writer(response) return response When I open the file manually in /pythonprojects/djangoprojects/results.csv, the differences are there and the file weighs around 500kb. However, the file that I downloaded(results.csv) contains nothing and its 0kb. I'm wondering what causes this? Shouldnt the code be pushing the file that contains the difference? It is acting as if it just creates difference.csv with nothing in it -
Adding style tag in django inherited template
I am new to Django. I want to add just a few lines of styling code in my Django template i.e 'blogs.html' which is already inheriting from a 'base.html' django template.But If I add a style tag and try to give a background image using {%static %} it doesnt work. Blogs.html {% extends 'base.html'%} {% load staticfiles %} {% block content %} <style> body{ margin:0; padding:0; } box1{ height:100vh; width:100%; background image:{%static 'images/ps1.jpg'%}; background-size:cover; } box2{ height:100vh; width:100%; background image:{%static 'ps2.jpg'%}; background-size:cover; } box3{ height:100vh; width:100%; background image:{%static 'ps3.jpg'%}; background-size:cover; } </style> <div id="box1"> </div> <div id="box2"> </div> <div id="box3"> </div> <div id="box4"> </div> {% endblock %} -
Displaying attribute of first element of list in django
So I am trying to display the first attribute of the first object of my list in django template. I currently have tried {{objArray.0.name}} and {{objArray.0.getName}} In my template and class ObjInfo(): def __init__(self,name): self.name=name def getName(self): return self.name is my class definition. I hard-coded my variables to be declared on any request but I printed it out to be sure it was declared. When I go to the page after running the server, nothing populates. Please help. -
iterate new url-request when the scroll reached the bottom of the page
Have url request in views.py: def main(request): page=str(1) d3 = requests.get('https://d3.ru/api/posts/?sorting=rating&threshold_date=day&page='+page).json() And in my template i have a listener when user reaches to the bottom of the page: <script> $(window).scroll(function () { if ($(window).scrollTop() + $(window).height() == $(document).height()) { //how from here to increase the page index in def main } }); </script> How can i increase the page index in def main() when user reaches to the bottom from my template? -
Django 1.11.0 TemplateSyntaxError at /tableapp/index/ 'verbose_names' is not a registered tag library. Must be one of:
I am working on django project. When I run server on windows using python 3.5 it is working fine for me. But on Linux, using python 2.5 it is not working. it is giving following error: TemplateSyntaxError at /tableapp/index/ 'verbose_names' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz widget_tweaks verbose_names.py is defined in folder tableapp/templatetags/ from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ return instance._meta.get_field(field_name).verbose_name.title() @register.simple_tag @stringfilter def trim(value): return value.lower().strip() @register.filter def get_item(dictionary, key): return dictionary.get(key) Template (configuration.html) renders at /tableapp/index/ : {% extends 'base.html' %} {% load verbose_names %} {% block extra_css %} <style> /*Tags not selected class*/ .span1 { background-color: #ADD8E6; border: none; border-radius: 12px; color: white; padding: 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 13px; margin: 1px 1px; } /*Setting Width for tagsBox*/ .bootstrap-tagsinput { /*width: 70% !important;*/ width: 420px !important; } /*Avoid text box*/ .bootstrap-tagsinput { border: none; box-shadow: none; } .bootstrap-tagsinput input { display: none; } /*Tags Selected Class*/ .myclass { background-color: #3090C7; border: none; border-radius: 12px; color: white; padding: 10px; text-align: center; text-decoration: none; display: β¦ -
Running model.save() method asynchronously?
I am wondering if it is possible to run a save method for a model that I've overwritten asynchronously? If so how would you implement it? -
Groupby using Django ORM
I have a table Snapshot where customer id is present scheme id is present.Each customer can multiple entries for same the scheme id.I want to form one query where I have to GroupBy the data for a customer based on scheme id. As I am new to Django and python ,I hav no idea on how to achieve this. Any suugestions on how to fetch the data grouped on scheme id ? -
Why add() method for m2m not working for single object - django
I am trying to add object to m2m with add method but neither its showing error nor adding item, I can't understand why Here is my view : class UpdateCartView(generic.UpdateView): model = Cart fields = ['products'] template_name = 'update_cart.html' success_url = reverse_lazy('carts:home') def form_valid(self,form): product = ProductCreateModel.objects.get(pk = self.request.POST.get('product')) size = Size.objects.get(pk = self.request.POST.get('size')) colour = Colour.objects.get(pk = self.request.POST.get('colour')) products = Products.objects.create(product = product, size = size, quantity = int(self.request.POST.get('quantity')), colour = colour) product.save() cart = self.get_object() print(products) cart.products.add(products) cart.save() return super(UpdateCartView,self).form_valid(form) def get_object(self): cart_obj, cart_created = Cart.objects.new_or_get(self.request) return cart_obj Everything is working fine, no errors, also print the products but in my admin panel its showing empty cart means cart.products.add(products) not added products why ? -
Google Directory API insert user
I'm really struggling with trying to add a new user with this API. I'm following every step at google Directory docs but I failed. from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Admin SDK Directory API SCOPES = 'https://www.googleapis.com/auth/admin.directory.user' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('admin', 'directory_v1', http=creds.authorize(Http())) # Call the Admin SDK Directory API #Insert User body = { "name": {"familyName": "Test", "givenName": "Mahalo"}, "password": "mahalo@test", "primaryEmail": "test@test.com", } user_add = service.users().insert(body=body).execute() When I try the insert method I got this error googleapiclient.errors.HttpError: https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Domain not found."> If I try to run the list method like in the quickstart guide it runs perfect https://developers.google.com/admin-sdk/directory/v1/quickstart/python -
I have an article page where I'll show all the article but at the homepage, i want to show only 12 latest articles
I'm making a portfolio site by Django 2.06. At the home page, i want to show not more than 12 articles. I have an article page where I'll show all the article but at the homepage, i want to show only 12 latest articles. How to make it happen at the home page. Do I need to use any kind of template tags? I used "for" tags to render it at the template. class HomeView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['articles'] = Article.objects.all() return context Thank you -
Add additional data to JSON response in ListCreateAPIView
class ItemListView(ListCreateAPIView): model = Item serializer_class = ItemSerializer # model serializer def get_queryset(self): return self.model.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) Is there any chance to add additional data to JSON response in get method? -
AsyncJsonWebsocketConsumer not handling 2nd message before 1st finished
After moving to channels2 I'm still struggling with python's "new" async/await and asyncio. First I tried to reproduce Worker and Background Tasks from the docs but then I realised that my task should just run as simple async function. So, my test function is async def replay_run(self, event): print_info("replay_run", event, self.channel_name) import asyncio for i in range(10): await asyncio.sleep(1) print_info("replay_run-",i, event, self.channel_name) and both of the following calls inside async def receive_json(self, event) seem to prevent a subsequent incoming message from being handled right away. Version 1: await self.channel_layer.send( self.channel_name, { "type": "replay_run", "sessionID": msg["sessionID"] }) Version 2: await self.replay_run(msg) First I thought of version 1 because I thought I needed to register a "new event consumer" like await asyncio.gather... Any hint on how to do this right is appreciated ... -
Unable to connect to sql server database from another network
I have an application server (Written in Python [Django]) running on one network and the sql server database on another network (due to security) and I am trying to get the values from that database to my application server. The error I am getting is: OperationalError: ('08001', 'u'[08001] [Microsoft] [ODBC Driver 13 for SQL Server] SQL Server Network Interfaces: Error Locating Server/ Instance Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [08001] [Microsoft] [ODBC Driver 13 for SQL Server] Login Timeout Expired (0); [08001] [Microsoft] [ODBC Driver 13 for SQL Server] Invalid connection string attrbute (0); [08001] [Microsoft] [ODBC Driver 13 for SQL Server] A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)') Things I have already checked: I am able to ping from the network where sql server database is to the application server network. Remote connections is enabled on the sql server database. Verified Windows firewall is not blocking the connection. Verified there is a rule in firewall which allows all traffic from the sql β¦ -
Django double import during tests
whenever I run Django tests, I fall into a double import trap with my models. Every time I get RuntimeError: Conflicting 'userdevice' models in application 'cart': <class 'cart.models.devices.UserDevice'> and <class 'fridge.libs.cart.models.devices.UserDevice'> Minimal failing example is at https://www.dropbox.com/sh/m802q544cet5dui/AACRGOMQXWqxUzi92WfqfvYea?dl=0 My folder structure is . βββ apps β βββ __init__.py β βββ milk β βββ __init__.py β βββ tests β βββ __init__.py β βββ test_commands.py βββ __init__.py βββ libs β βββ cart β β βββ __init__.py β β βββ models β β βββ devices.py β β βββ __init__.py β βββ __init__.py βββ Makefile βββ manage.py βββ settings βββ __init__.py βββ settings.py I have apps and libs folders in INSTALLED_APPS. My models/__init__.py file contains from .devices import * From test_commands.py I include model with from cart.models import UserDevice I read multiple questions here at SO and some articles on web. I was also debugging this for a few hours, so I know the problem is that my model is imported twice. Once during the Django project initialization as cart.models.devices.UserDevice and once by the unittest library as fridge.libs.cart.models.devices.UserDevice but I simply do not know how to fix this situation. This is also causing more problems in files, which can be initialized only once during the β¦