Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python / django.db: How to create a generic class without hardcoded Meta.db_table?
I have a class using django.db as follows: from django.db import models class myClass(models.Model): "My class" class Meta: db_table = 'my_table' field1 = models.CharField() # more fields here def some_function(self): return "hello" I'd like to turn this into a generic class that does not have "my_table" hardcoded, so that I can use it in some way such as: class GenericClass(models.Model): class Meta: db_table = None # genericClass properties and methods here class myClass(GenericClass): id = models.CharField(max_length=20) def __init__(self, *args, **kwargs): super(self.__class__, self).Meta.db_table = 'my_table' super(self.__class__, self).__init__(*args, **kwargs) However, this gives me the following error (using Python 2.7 / Django 1.11): Local field u'id' in class 'myClass' clashes with field of similar name from base class 'GenericClass' Is there any way to create a generic class that extends django.db.models.Model, that supports a non-default database table name without hardcoding Meta.db_table? -
steps to configure prometheus metrices with django application
HiI am working on how I can configure Prometheus metrices in my Django-webapplication.I have a script which works fine if i add metrices and scrape it into prometheus but I want to do the same thing in my web-application with Django.Can anyone please guide me -
Django translations - translate days of week
I'm making multilingual website and have a problem in translating days of week So: var day = moment().startOf("week").format('dddd') This is short version. I've tried to use ugettext_lazy (_) - var one = _(moment().startOf("week").format('dddd')) But it doesn't work. full: var days = data.buckets.map(e => moment().startOf('week').day(1 + e.key).format('dddd')) This is d3/c3 format. I'm using days in x-axis in vertical bar chart(maybe it is important:)) I need to translate all day's names. -
Loading templates in Django doesn't work
I have a project that has 3 apps: app1, app2 and app3. In the first two apps I had different templates: app1/templates/app1/page.html app2/templates/app2/anotherpage.html And I load them like this: return render(request, "app1/page.html") It worked perfectly, but now I added app3, and I tried to do the same: app3/templates/app3/config.html but when I return "app3/config.html" I get the error TemplateDoesNotExist I simply created the app doing python manage.py startapp app3 and copy the files to the folder. However, this works: app1/templates/app3/config.html app2/templates/app3/config.html Why it's not working now? -
Basic http authentication asks login credentials for each request in chrome
I am implementing Basic http authentication with Nginx. My website is Django powered website. I am using Django auth as well for user authentication. My default behaviour for website it's checks user is logged in or not. If not returns the 401 status. Now i am trying to implement the http basic auth, it's working but for each request it's asking for login credentials. I am facing this issue in chrome. In firefox it's works fine. satisfy any; auth_basic "Restricted Area"; auth_basic_user_file htpasswd-docdoc; # Allowed IP Address List allow 127.0.0.1; deny all; I don't what wrong i am doing. -
How should I manage url versioning in Django
I have a doubt about the optimal structure of my files. Right now, I have all my urls in a file api.py. The endpoints for a new version of the app are being located in a new api_v2.py file, only the urls that require a new version, is that ok? Also, if a new functionality is added to the app, should I put the new urls directly on api_v2.py? or maybe on the base api.py and keep the api_v2.py for the urls that have a "new version" of themselves? Any advice will help. -
Deploying two different Django Applications on Windows Server in IIS
I am deploying two different Django applications on Windows 2012 in IIS. My first application is running but I can't seem to run my second application. My question is how do I configure my FastCGI Settings if I have two PYTHONPATH and two DJANGO_SETTINGS_MODULE? Do I put a semicolon every after values? For example: NAME: DJANGO_SETTINGS_MODULE VALUE: mysettings.settings;myothersettings.settings NAME: PYTHONPATH VALUE: C:\PythonApps\firstapp;C:\PythonApps\secondapp -
How to get apps url from inside the app's views or templates
I'm working on a FOSS app that the users can assign any url to in their project's urls.py But the problem is the app is setup in such a way that JS need to call the apps root url. The user might have set up any URL like ^forum/?. I need to know this url. Thanks. -
How to pass ID parameter to views.py in CreateView in Django?
I am doing a webapp containing products with a Rating (1-5) functionality. I created an app called rating and I want people to click on a button "rate" on single.html which will direct you to a rating page where people will be rating. The issue here is that I do not know how to pass the product ID to the Rating(CreateList) in views.py. so far Ive done: urls.py urlpatterns = [ url(r'^product/(?P<product_id>\d+)/rating/$', views.RatingView.as_view, name = 'rating'),] models.py class Rating(models.Model): RATING_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) productID = models.ForeignKey(Product, on_delete=models.CASCADE) indRating = models.IntegerField(choices=RATING_CHOICES) def __str__(self): return self.productID views.py class RatingView(CreateView): model = Rating fields = ['productID', 'indRating'] def get_context_data(self, **kwargs): context = super(RatingView, self).get_context_data(**kwargs) context['product_id'] = self.kwargs['product_id'] return context -
How to run a xml file using django localhost
Actually I am learning xml and I want to test my xml file by running it on a localhost . I want to run it on my django localhost server kindly help me in this regard -
Reading from xlsx limited to 65535 rows: openpyxl
When I read from an xlsx file containing more than half million entries. pyopenxl reads only 65535 rows. wb = load_workbook(filename=import_file, read_only=True) ws = wb['Sheetname'] rows = ws.rows # yields upto 65K rows What is confusing is, I have used the same package for the writing operation. I was able to write a million entries to an xlsx file. wb = openpyxl.Workbook() ws = wb.get_active_sheet() ws.cell # Write operations here wb.save(filename=file_path) It will be great if I was able to use the same package for reading and writing. -
Login not working in Django
I'm trying to login but Django is not allowing the navigation to the profile.html This is what I have so far views.py def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): userObj = form.cleaned_data print(userObj) username = userObj['username'] password = userObj['password'] user = authenticate(username=username, password=password) if user is not None: print("in login") login(request) return render(request, 'profiles.html', {'form': form}) else: return render(request, 'login_form.html', {'form': form}) else: return render(request, 'login_form.html') forms.py class UserLoginForm(forms.Form): username = forms.CharField( required=True, label='Username', max_length=32 ) password = forms.CharField( required=True, label='Password', max_length=32, widget=forms.PasswordInput() ) -
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 …