Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'HTTPMessage' object has no attribute 'getparam'
I use python3 version in Ubuntu. The code I use could run in python 2.7 version. But I got some of Import Errors and Attribute Errors in python 3. I want to edit this code for 3.6 version. But I can't find any document for Attribute Error trouble shooting. The error message I got is as below : taylor@taylor-Rev-1-0:~/taylor/pyBook/ch2$ python parse_image.py Traceback (most recent call last): File "parse_image.py", line 35, in <module> main() File "parse_image.py", line 28, in main charset = f.info().getparam('charset') AttributeError: 'HTTPMessage' object has no attribute 'getparam' and the methods or classes I imported is shown as below : from urllib.request import urlopen from html.parser import HTMLParser -
Modeling two many-to-many relationships that have a constraint between them
In an application I'm writing, I have 3 models: Player, Plan, and Coach. They are related like so: A Player can have many Plans, but each Plan is related to exactly one Player. A Plan can have many Coachs and a Coach can have many Plans. (e.g. Coachs might collaborate to come up with a Plans for Players.) By themselves, the modeling of these two relationships seems pretty clear: the first is a one-to-many relationship, where a Plan has a foreign key to a Player, and the second is a many-to-many relationship between Player and Coach. However, there's a third softer relationship between these models: A Coach coaches many Players, and a Player can have many Coachs, but the set of Coachs set of Players will always the set of Players reach-able through all of the Coach's Plans. This is the relationship I'm not sure how best to model. This feels like a ManyToMany relationship with a defined through model (where Plan is the through model), but the fact that Plans to Coaches is many-to-many messes this up, since the Django documentation seems to cite that the through model must have a single ForeignKey to each model. I'm also using … -
How to make UUID field default when there's already ID field
I'm working on a project and problem is I've already created models with simple ID column but now my requirements are changed and I want to replace ID field (model) with UUID field I just updated my model: uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) but when I run my migrations I got an error django.db.utils.OperationalError: (1829, "Cannot drop column 'id': needed in a foreign key constraint Please guide me how can I perform this migration? -
Django Social Auth Linkedin Rest API Internal Server Error
I'm using Django Social Auth with Linkedin OAuth2 backend and keep getting a HTTP 500 Internal Server Error when trying to authenticate with my Linkedin account. { "errorCode": 0, "message": "Internal service error", "requestId": "UE6GBQYK4T", "status": 500, "timestamp": 1515645281366 } -
django rest framework display authtoken model and token authentication
Is it possible to display the authtoken model in api json view with all its function ? If yes, how do i do it ? I am only able to see it in the django admin site and i am using djoser token authentication. Based on the django site, there are 3 field. key, user and created. I also want to know how does django lookup for the user based on the token in header. If they doing the lookup by its long string token, wouldnt it cause longer search time if there are many users ? i tried using this code for displaying authtoken in api: serializer class SessionSerializer(serializers.ModelSerializer): class Meta: model = Session fields = ('id', 'userId', 'token', 'firstActive', 'lastActive') -
Where the uploadfile_ptr comes from when I use inherit to create the model?
I change my upload file model WorkOrderUploadFile to inherit from base model like bellow: Base model: def generate_files_directory(instance, filename): url = "%s/%s" % (instance.filepath , filename) # will output something like `images/imgs/test/` return url class UploadFile(models.Model): """ Base upload model """ #filepath = models.CharField(max_length=128, default="images/qiyun_admin_servicemanage_workorder/") file = models.FileField(upload_to=generate_files_directory) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.file def __unicode__(self): return self.file My WorkOrderUploadFile class: class WorkOrderUploadFile(UploadFile): """ work order upload file """ filepath = models.CharField(max_length=128, default="images/qiyun_admin_servicemanage_workorder/") When I makemigrations, I get bellow issue: $ python3 manage.py makemigrations You are trying to add a non-nullable field 'uploadfile_ptr' to workorderuploadfile without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py But I did not add a field name uploadfile_ptr in my base model and how to deal with it? I tried give 1 to the value but I still get error, it will report error: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1062, … -
I want to call multiple views from a single template
I want to call these views(getsql_view, getbind_view) from a single template(getsql.html). These views takes an id variable and executes the Oracle procedure to pass the result. want to show the result of two views on getsql.html. There is no problem running it one by one. Please teach me how to do it. Models.py ... class getbind(models.Model): # fields name = models.CharField(max_length = 32) position = models.CharField(max_length = 2) value_string = models.CharField(max_length = 32) datatype_string = models.CharField(max_length = 20) last_captured = models.DateTimeField() class Meta: managed = False @staticmethod def search(id): # create a cursor cursor = connection.cursor() # you need to make sure you have a "raw" cx_Oracle cursor!! rawcursor = cursor.connection.cursor() cur_var = rawcursor.var(cx_Oracle.CURSOR) # execute the stored procedure passing in search_string as a parameter rawcursor.callproc("pkg_sqlmon.pc_get_bind", (id, cur_var)) # grab the results results = cur_var.getvalue().fetchall() cursor.close() # wrap the results up into over3 domain objects return (getbind(*row) for row in results) class getsql(models.Model): # fields sql_id_plan = models.CharField(max_length = 13) sql_id_awr_plan = models.CharField(max_length = 13) sql_id_report = models.CharField(max_length = 13) sql_id_bind = models.CharField(max_length = 13) sql_id_format = models.CharField(max_length = 13) sql_fulltext = models.TextField() class Meta: managed = False @staticmethod def search(id): # create a cursor cursor = connection.cursor() # you … -
Django switch the primary server to secondary along with mysql db
I'm completely new to Django. I have developed a simple web application in Django and hosted it on external server. And that web application uses default mysql database. Now, I want to switch to a secondary server if my primary server goes down. Copying and running the same code is not the option. Can anyone explain how do I do it along with an example ? -
How can I use the same url in django urlpatterns
I have a django project and I need to use this two urls hostname.com/users/username/ hostname.com/users/username/rides/ this is my urls file urls.py from django.conf.urls import url, include from django.contrib import admin from rides import views urlpatterns = [ url(r'^$', views.home, name='index'), url(r'^admin/', admin.site.urls), url(r'^rides/', include('rides.urls')), url(r'^users/', include('users.urls')), ] users/urls.py from django.conf.urls import url from . import views app_name = 'users' urlpatterns = [ url(r'^login/$', views.login, name="login"), url(r'^logout/$', views.logout, name="logout"), url(r'^register/$', views.register, name="register"), url(r'^(?P<username>\w+)/$', views.UserProfile.as_view(), name="user_profile"), url(r'^(?P<username>\w+)/rides/$', views.UserRidesView.as_view(), name="user_ride_list"), ] I can access to hostname.com/users/username/ but not to hostname.com/users/username/rides/ I get this error NoReverseMatch at /users/ramiro/rides/ Reverse for 'user_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>\\w+)/profile/$'] How can I fix this problem? -
django shared session auth cross-domain
I'm looking for a way to share authentication across multiple domains. My use case is simpler than most multiple domain projects in that it's the same shared codebase, with these different domains just pointing to a specific app in the project, and having the same shared database / users. Because of this... It's redundant to have people logging in / out across all the domains. I looked at django_shared_auth which tries to set a session token saying the user has already logged in to control single sign on / log out across multiple domains. However, this relies on the token key showing in request.session which won't work since these aren't subdomains (to my knowledge). Testing on localhost vs 127 doesn't work when inspecting the different sessions / contents. django-xsession does work locally, but fails in production. Even if I could get this package to work in production it seems very hacky injecting scripts. And these seem to be the only two options / packages out there that have what I'm looking for. How can I get around this? I'm already using django-allauth so I'm looking for a lightweight / token based solution to simply mark that the user has already … -
I am trying to edit an existing post and save it to the database but getting no reverse match error. below is my code
urls.py file. from django.conf.urls import url from posts import views app_name = 'posts' urlpatterns = [ url(r'^create/', views.create, name='create'), url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'), url(r'^(?P<pk>[0-9]+)/downvote', views.downvote, name='downvote'), url(r'^user/(?P<pk>[0-9]+)', views.user_post, name='user_post'), url(r"^delete/(?P<pk>[0-9]+)", views.delete_post, name="delete"), url(r"^edit/(?P<pk>[0-9]+)", views.edit_post, name="edit"), url(r"^save_post/(?P<pk>[0-9]+)", views.save_post, name="save_post"), ] views.py file. function for saving the post after editing def save_post(request,pk): if request.method == 'POST': post = Post.objects.get(pk=pk) post.title = request.POST['title'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): post.url = request.POST['url'] else: post.url = "http://" + request.POST['url'] post.save() return redirect('home') else: return render(request,'posts/edit_post.html') edit_post.html file. html file where existing data will be fetched and user can edit that {% extends 'base.html' %} {% block body_block %} <div class="jumbotron"> <h3>Edit Post</h3> <form method="POST"> {% csrf_token %} <div class="form-group form-group-md"> <label for="title">Title</label> <input class="form-control" id="title" name="title" type="text" value="{{post.title}}"> <label for="url">URL</label> <input class="form-control" id="url" name="url" type="text" value="{{post.url}}"> </div> <a href="{% url 'posts:save_post' %}" class="btn btn-md btn-success">Save</a> </form> </div> {% endblock %} when going to save, getting following error -
How do I retrieve lat & long coordinates from the client without them needing to POST once?
I'd like to do some server side processing with their lat/long as soon as they agree to share them--I'd like for the results of that processing to be in the same page the users are in, immediately after they "Allow" location access. Currently, I am able to retrieve their coordinates, but a POST removed. So when they "Allow", I fill out a hidden lat/long form, and wait for them to POST a form before I do the server side processing with Geodjango. What's an efficient way to send over the coordinates to the server as soon as they're available, OR retrieve an estimated location, pronto? -
Django queryset optimization with prefetch_related
I'm working on a project based on Django 1.11, and I'm trying to optimize database access with prefetch_related, here is what I'm facing: I have some model definitions(simplified): class D(models.Model): foo = models.IntegerField() class A(models.Model): foo = models.FloatField() class B(models.Model): a = models.ForeignKey(A) d = models.ForeignKey(D, related_name='bs') # Some fields are identical to C foo = models.CharField() # A special field bar1 = models.FileField() class C(models.Model): a = models.ForeignKey(A) d = models.ForeignKey(D, related_name='cs') # Some fields are identical to B foo = models.CharField() # A special field bar2 = models.FloatField() I want to retrieve some objects of D, when retrieving them from DB, I want to retrieve them along with all related(directly) B objects and C objects and related(indirectly) A objects, Currently I'm using: >>> qs = D.objects.filter(foo=1) # some queryset of D >>> qs = qs.prefetch_related('bs__a', 'cs__a') The performance is ok(compared with no prefetch_related), I see raw SQL queries from django-debug-toolbar and it looks like Django breaks the query into something like(psuedo SQL): select * from D select * from B where `d`.`id` in (ids from D) select * from A where `A`.`id` in (ids from B) ---> first time select * from C where `d`.`id` in (ids from … -
Django: m2m select with thumbnails
I am new to Django development and trying to build my own site with a portfolio of my work and a blog. The portfolio part of my site has posts that include a variable number of images to use as thumbnails. In Django admin, I would like to be able to see thumbnails of each image in the select form. Django's filter_horizontal is very close to what I am looking for, but it can't display thumbnails of the images Anyway, the models involved look something like this: class Image(models.Model): original = models.ImageField(upload_to='images') medium = ... thumbnail = ... class Project(models.Model): title = models.CharField(max_length=100) images = models.ManyToManyField(Image, blank=True) description = RichTextField(max_length=1000) content = RichTextField() This is a mockup of what I am trying to achieve. I've been reading through the documentation on Forms, ModelForms, and Widgets, but I am not entirely sure how to piece it all together or if I'm looking at the wrong thing entirely. Any help would be much appreciated, even if it's just pointing me in the right direction. -
Customize the nested data in Serializer
I have a ModelSerializer: class WorkOrderRetrieveSerializer(ModelSerializer): workordercomments = WorkOrderCommentForWorkOrderSerializer(many=True, read_only=True) class Meta: model = WorkOrder fields = "__all__" The JSON data is bellow: { "id": 1, "workordercomments": [ ..... { "id": 21, "content": "test files", "files": "[71]", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } ], "workorder_num": "WON15118747168252", "name": "order01", "content": "first conntetn", "workordertype": "teck", "workorder_status": "created", "user_most_use_email": "lxas@128.com", "server_id": null, "public_ip": null, "belong_area": null, "files": null, "ctime": "2017-11-28T21:11:56.826971+08:00", "uptime": "2017-11-28T21:11:56.827064+08:00", "to_group": 3, "user": 2 } The "files": "[71]", in my JSON is a string of a group contains file ids. workordercomments is the related-name of the workorder. I want in the JSON workordercomments shows the files like this: { "id": 21, "content": "test files", "files": "['/media/images/xxxxx.png']", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } The "files" value I want to is the link rather than its id. "files": "['/media/images/xxxxx.png']", or "files": ['/media/images/xxxxx.png'], Is it possible to customize the format? should I come true what function in serializer ? -
Pass data from Views.py to Forms.py
I am trying to move data from my views.py to my forms.py pages. I am using the FormWizard, however i dont think it will matter here. views.py def get_context_data(self, form, **kwargs): context = super(CheckoutWizard, self).get_context_data(form=form, **kwargs) kwargs = super(CheckoutWizard, self).get_form_kwargs() def get_form_kwargs(self): kwargs = super(CheckoutWizard, self).get_form_kwargs() kwargs.update({'first_name': 'james'}) kwargs.update({'last_name': 'bond'}) form = CreditCardForm(kwargs) return kwargs forms.py - in CreditCardForm def __init__(self, *args, **kwargs): for a in args: for key in a: print("key: %s , value: %s" % (key, a[key])) super(CreditCardForm, self).__init__(*args, **kwargs) In the forms file above I am accessing the data in *args with the nested loops because if i call args without the * i get this back ({'first_name': 'james', 'last_name': 'james'},) which i believe is a tuple with a dictionary in it. I have seen other solutions where other people are using **kwargs instead. My current solution feels a bit hacky so if there is a more correct or simpler way of doing this id appreciate the help. Its also strange to me that in views i am adding to kwargs, but then accessing that data in args. Any explanation on the differences would also be appreciated. Thanks! -
Django - adding checkout to django-carton
I've built a product app that utilizes django-carton, and I want to add 'checkout' functionality. I know the best route would be to use something like django-oscar, but in the spirit of finishing what I've started, and learning along the way I want to see if I can add checkout to this app. I'm looking for a starting point - since the checkout app will need to hand off for payment, and in some cases, deliver a link to a product. What is the best way forward for that? -
CSRF token missing or incorrect from form on `/`
I have this in urls.py: url("^$", direct_to_template, {"template": "index.html"}, name="home"), url("^searched-location", views.searched_location, name="searched_location"), I have this in index.html: {% extends "base.html" %} {% load pages_tags mezzanine_tags i18n staticfiles %} {% block main %} <form id="my-form class="input-group"> {% csrf_token %} <input type="text" class="form-control"> <script src="{% static "script/script.js" %}"></script> </form> {% endblock %} script.js has this line: document.getElementById("my-form").addEventListener("submit",function(event){ event.preventDefault(); },false); function when_User_Types_Something_Send_That_Stuff_To_The_Backend(typedStuff){ // some code $.post("/searched-location",{typed_stuff: stuff_the_user_typed}); } views.py has this: def searched_location(request): print request # More code here Problem is I'm getting this error in my terminal when I run python manage.py runserver locally: Forbidden (CSRF token missing or incorrect.): /searched-location [11/Jan/2018 01:57:06] "POST /searched-location HTTP/1.1" 403 2502 Why is the CSRF token missing or incorrect? How do I find or correct it? -
(1129, "Host 'IP is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'")
Please do not mark as duplicate if possible. I do find out LOTS asking about this problem and all the results seem to be either flush hosts; or change the max_connect_errors variable to a higher value. But none of the posts are able to really have a reason of this. I am wondering are those the only two options? For me, this happened not right after but few days after I used galera to create few master to master mariadb replications. I had no idea why this is happening and it just happened randomly, even though I did try the flush hosts which worked perfectly each time, but it was still weird how this even happened. Does replication have something to do with this though? I did read some posts about crontab by the time when this error started to happen, I was researching how to make a bash to check maria db connection, cluster status and cluster size but haven't even done it yet. Today, I figured there is one way that this error will happen for sure, which is by going to django admin dashboard and go to one of my models. The first page only displays 100 … -
form.isValid() always return false in custom registration form django
I'm trying to make a custom user registration form in django but I can't understand why the method isValid() always return false please help me! forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = [ 'email', 'first_name', 'last_name', 'gender', 'birth_date', 'country', ] labels = { 'email':'Correo Electrónico', 'first_name':'Nombre', 'last_name':'Apellido', 'gender':'Sexo', 'birth_date':'Fecha de Nacimiento', 'country':'País' } widgets = { 'birth_date' : forms.SelectDateWidget(years=range(1930,2010)), 'gender' : forms.RadioSelect(), 'country' : CountrySelectWidget() } This is my views.py This is my register.html -
Djanjo dlib integration - pip install dlib have errors on macos 10.13.1
I am trying to install dlib library for my django project on my mac (macos 10.13.1), however i have this failure. I am using pip install dlib the last line had failed with error code 1 in /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-build-m4fk5wp2/dlib/ below is the full execution with error $ pip install dlib Collecting dlib Downloading dlib-19.8.1.tar.gz (2.7MB) 100% |████████████████████████████████| 2.7MB 40kB/s Installing collected packages: dlib Running setup.py install for dlib ... error Complete output from command /Users/axilaris/Documents/project/somedotcom/somedotcomenv/bin/python3 -u -c "import setuptools, tokenize;__file__='/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-build-m4fk5wp2/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-k_j5yu44-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/axilaris/Documents/project/somedotcom/somedotcomenv/include/site/python3.6/dlib: Warning: Functions that return numpy arrays need Numpy (>= v1.5.1) installed! You can install numpy and then run this setup again: $ pip install numpy running install running build Detected Python architecture: 64bit Detected platform: darwin Configuring cmake ... -- The C compiler identification is AppleClang 8.1.0.8020042 -- The CXX compiler identification is AppleClang 8.1.0.8020042 -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- Check for working CXX … -
How do I make my nginx load all static files from django docker app over HTTPS?
I have my nginx installed on the server and I have my Django application running inside a docker container. While my app loads fine over HTTP, it doesn't load any static files (CSS) over HTTPS. What changes should I make in nginx conf or docker app to solve this? -
Django templates inheritance looses original data
I'm learning django. I have a site with a data table that has the following html template: {% load static %} {% load table_tags %} <link href="{% static 'table/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="{% static 'table/js/jquery.min.js' %}"></script> <script src="{% static 'table/js/bootstrap.min.js' %}"></script> <link href="{% static 'table/css/datatable.bootstrap.css' %}" rel="stylesheet"> <script src="{% static 'table/js/jquery.browser.min.js' %}"></script> <script src="{% static 'table/js/jquery.dataTables.min.js' %}"></script> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Impala query metrics</title> </head> <body> <div class="container" style="margin: 10px 10px 10px"> <h1>Impala Query metrics</h1> <br /> {% render_table people %} </div> <a href="/logout">logout</a> {% block content %} {% endblock %} </body> When i try to inherit with another template by adding {% extends "base.html" %} to the first line, it inherits with base.html but my original data table disappears. Any help on how to keep my original data table or pointing me to the right documentation would be appreciated. -
Differences in import expressions?
I have a question regarding the import//from statement in python. In my views.py file (Project/App/views.py) I have this line: from django.views.generic import TemplateView, ListView Why do I have to include 'django' in that line? Why is it not enough to specify which directory (views) that the generic file is located in? This is what I have done in many of my previous python-only scripts - an example being: from random import foo as well as in my current django url.py file. There, I have: from app.views import view Why don't I have to specify that further, like with the first example where 'django' is included in the path-specification? How come I don't have to write it like this: from project.app.views import view Thank you! -
Django Admin Calander can't get reverse url to pull up next/previous month
I am getting an error on this reverse url call: extra_context['previous_month'] = reverse('admin:portal_event_changelist') + '?day__gte=' + str( previous_month) extra_context['next_month'] = reverse('admin:portal_event_changelist') + '?day__gte=' + str(next_month)