Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recursive filters of a django queryset
In a form the users can select some filters if they want. I want to filter the queryset on these three parameters but only if they are different from null (a filter is null if the user doesn't want to use it). The problem is that the queryset is always null even if there are elements respectful of filters. That doesn't happen if I change the name of my_query each time I apply a filter (see below) but I should explore all eight combinations or do some complicate if nested and I think there are better way to solve my problem. My model: class Mymodel(models.Model): myfield1 = models.CharField(max_length=32) myfield2 = models.CharField(max_length=32) My views.py: def my_view(request): if request.is_ajax(): myfield1 = request.POST.get('myfield1', None) myfield2 = request.POST.get('myfield2', None) myparameter3 = request.POST.get('myparameter3', None) my_query=Mymodel.objects.all() print(myquery) # myquery=[something] if myfield1 !='': my_query=my_query.filter(myfield1=myfield1) if myfield2 !='': my_query=my_query.filter(myfield2=myfield2) print(myquery) # myquery=[] ... my_query after the if is empty. ... if myfield1 !='': my_query1=my_query.filter(myfield1=myfield1) print(myquery1) # myquery1=[something] ... This works but complicate the code (or maybe it just look to me) -
Nginx non-responsive while celery is running
I have a django app configured to run behind nginx using wsgi. On a separate machine I am running celery, and pushing long running tasks from the webserver to the task machine. The majority of the task I/O is outbound http requests, which go on for an hour or more. The task broker is redis. When the tasks run for more than a minute or two, the webserver becomes unresponsive (503 errors). There are no errors raised anywhere within the python app. The tasks complete normally, after which the webserver continues handling requests. Has anyone experienced this before, and if so, how did you deal with it? Thanks -
Why I can't make a insert in Postgresql?
I am using Postgresql whith Django but I have a problem I need to make a INSERT INTO but alway show this message Not connected to the server or the connection to the server has been closed. But in other database I can do a Insert, I don't understand why in the database created by Djando I can't do query, I have reinstall postgresql but it doesn't work. -
django findstatic not looking in every directory
findstatic has a strange behaviour : On localhost python manage.py findstatic pic/xxx.jpg -v 3 gives me : Found 'pic/xxx.jpg' here: /[...]/myapp/app1/static/pix/xxx.jpg Looking in the following locations: /[...]/myapp/app1/static /[...]/myapp/app2/static /[...]/myapp/app3/static /[...]/env/lib/python3.6/site-packages/django/contrib/admin/static whereas on production it gives me Found 'pic/xxx.jpg' here: /[...]/myapp/app1/static/pic/xxx.jpg Looking in the following locations: /[...]/myapp/app1/static /[...]/myapp/app2/static /[...]/env/lib/python3.6/site-packages/django/contrib/admin/static (note that the 'app3' directory isn't looked into, despite it exists) Of course, the files located in the 'app3' directory are not found by findstatic, although they exist. Does someone have any idea where the problem could come from ? (I don't have any special parameter for staticfiles). -
Website with blog using Django and React or Angular
I am currently building a website for one of my clients and it will mainly be a blog. As he wants to deliver a bleeding-edge experience to its visitors, I'm considering making a React or Angular interface and consume the django-restapi (or grapehene-django for GraphQL). The main problem I'll have if I choose this solution is the management of the blog posts. I could use a built and tested app like DjangoCMS for that, but its overkill and Wordpress would by far be a better choice on that matter (managing posts), so I'm left with setting up a CMS on my own if I go this way. The question I have is: is it worth the extra work? Is Django the best framework for this (in any language, python is preferred but not mandatory)? Now, before you ask: why don't you just use Wordpress? First, because I don't like it. Second, although it will be MAINLY a blog, the website will have some custom functions (including a chattbot and a ticket management system). Thanks everyone! -
JavaScript Client is not able to connect to my Twisted Server
I have a Twisted server listening for connections on port 8080. When my javascript client connects to the server, the server acknowledges the new client. However, on the clients side, it doesn't receive any of the messages sent to it from the server. The browser notifies me that "Firefox couldn't connect to the websocket". I'm a bit confused because how is it not connecting, when my server acknowledges the new client and even prints it's address? Also, I don't know if this is pertinent information, my js client is located in a template in a django Template. JavaScript Client: <div id="check-status-button"> {% csrf_token %} <button onclick="webClient()"> Check Status </button> </div> <div id="check-status"> <textarea rows="4" columns="50" name="check_status" value = "{{ status_data }}"> </textarea> </div> <script type="text/javascript"> function webClient(){ var ws = new WebSocket("ws://localhost:8080/"); ws.open = function(){ alert("Message is Sent"); }; ws.onmessage = function(event){ var received_msg = event.data; console.log("received: ", received_msg); alert("Message received"); }; ws.onclose = function(){ alert("Connection is Closed"); }; }; </script> Python/Twisted Server: import os from datetime import datetime from twisted.internet.protocol import ServerFactory, Protocol from twisted.internet import task class serverProtocol(Protocol): def connectionMade(self): # self.transport.write(self.factory.data) # self.transport.loseConnection() print("Connection Made") self.factory.clientConnectionMade(self) class serverFactory(ServerFactory): protocol = serverProtocol def __init__(self, data): self.data = data … -
django-allauth user_signup signal not called for social signups
For some reason I don't get an "user_signed_up" signal when I sign in via Facebook with django-rest-auth along with django-allauth. The following is my code: views.py from allauth.account.signals import user_signed_up from rest_auth.registration.views import SocialLoginView from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter @receiver(user_signed_up) def user_signup(sender, **kwargs): print(kwargs) Essentially what I want to do is to create a UserProfile object when a User object is created, using the data from the social login. Does anyone know what the issue is and any alternative ways to do this? -
Combing 2 different Django websites
I have 2 independent django websites that I want to merge into one another. To go about doing this can I just drag and drop the folders of one of the websites into the other and just change the root url.py and settings.py and it should work correct? Or is it more complicated that that? -
Cache website to browser when navigating back
I have a single url/page of my website that I want to be cached to browser, so whenever a user navigates away from that page, and then presses the BACK button of the browser, I don't want that request to go to django at all, but serve the cached version of the page that is in the browser. Also, I can't use solutions that cache the page in between the web server and Django, as every user has different permissions on what data they can see. So I added this in my nginx config: ... location /search { expires 300s; add_header Cache-Control "private"; ... And this works very well, 50% of the time :). How can I make it work always? -
Django Variable Not Matching As Expected
I have the following code: {% for x in fixtures %} {% if currentSelectedTeam1Name == "Swansea" %} <tr> <td colspan="6"> {{x.straightredfixturelive.home_team}} | {{currentSelectedTeam1Name}} </td> </tr> {% endif %} {% endfor %} When I hardcode the team as "Swansea" it works and produces the following results: Swansea | Swansea Arsenal | Swansea Bournemouth | Swansea However, what I really want it to be is: {% if currentSelectedTeam1Name == x.straightredfixturelive.home_team %} But this produces no results which is a suprise as I would expect to see: Swansea | Swansea So x.straightredfixturelive.home_team seems to contain "Swansea" but does not match up. I even tried: {% if x.straightredfixturelive.home_team == "Swansea" %} And that produced no results as well. So even thought it displays on the webpage as "Swansea" it does not seem to match up. Maybe a data type issue? Any help would be great, many thanks, Alan. -
Django Categories with subcategories
I was able to show categories for Category Model (Man and Woman). Now i want to make forwarding for category to site with subcategory where will show subcategory with product This is my models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class SubcategoryMan(models.Model): category = models.ForeignKey(Category, related_name='subcategorymans') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) def __str__(self): return self.name class ProductMan(models.Model): category = models.ForeignKey(SubcategoryMan, related_name='productsman') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='productsman/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name this is my ciews.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = ProductMan.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) This is my url (in app shop) urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category') ] and this is my list.html {% extends "shop/base.html" %} {% load static %} {% block content %} … -
django create custom form
We could directly create a simple form by inheriting forms.Form. However, I want forms to be dynamically created based on the key-value specified by the admin. Consider, user provides a map as : [ { "key": "name", "value": "CharField" }, { "key": "url", "value": "URLField" } ] Based on the map given above how can I create a form which is equivalent to the class based form creation below: from django import forms class CommentForm(forms.Form): name = forms.CharField(label='Your name') url = forms.URLField(label='Your website', required=False) My current approach might be to iterate across each key-value pair and make a HTML form manually. Is it possible to create dynamic forms in django without having to write a class definition? -
how to make email field required in the django user admin
I want to make the email field required in the user admin add and change pages. I read this post: Django User model email field: how to make it mandatory and I did this: class MyUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(MyUserCreationForm, self).__init__(*args, **kwargs) # make user email field required self.fields['email'].required = True class UserAdmin(BaseUserAdmin): form = MyUserCreationForm add_form = MyUserCreationForm add_fieldsets = ((None, {'fields': ('username', 'email', 'password1', 'password2'), 'classes': ('wide',)}),) admin.site.unregister(User) admin.site.register(User, UserAdmin) This works fine in add user, but in change user I get the user's encrypted password shown in the password field, instead of what you normally see: algorithm: pbkdf2_sha256 iterations: 24000 salt: ****** hash: ************************************** Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form. And when I try to save from the change screen it says "Please correct the errors below." even though there are no errors shown. How can I fix these issues in the change form? -
Cannot install mysqlclient with PIP in Visual Studio Virtual Env Python 3.5 64bit
I am trying to install mysqlclient using PIP inside of visual studio 2015 update 3, running a virtual env with python 3.5 64bit. It is for a django web app. I get the following message when I try to install it. Installing 'mysqlclient' E:\Users\Tim Baker\Documents\Visual Studio 2015\Projects\DjangoWebProject1\DjangoWebProject1\env\Scripts\python.exe: No module named pip.__main__; 'pip' is a package and cannot be directly executed 'mysqlclient' failed to install. Exit code: 1 -
I need to create a number of very similar classes in Django, what's the DRYest way to do that?
I need to create several ModelAdmin and ModelForm classes in Django that all need to look like this: class CategoryForm(forms.ModelForm): class Meta: model = models.Category exclude = ['slug'] class CategoryAdmin(admin.ModelAdmin): form = CategoryForm They also need to inherit from this class, or have a way to call into this class: class Slugify(admin.ModelAdmin): class Meta: abstract = True def get_sluggable_field(self, obj): try: return obj.to_slug(obj.title) except AttributeError: return obj.to_slug(obj.category) except AttributeError: return obj.to_slug(obj.tag) def save_model(self, request, obj, form, change): field = self.get_sluggable_field(obj) if not obj.slug: obj.slug = obj.to_slug(field) else: self.to_slug(obj.slug) obj.save() The only thing different about the classes is the model from the Meta subclass. How do I do this with the little to no copy and paste? (I'm assuming there's some meta-programming involved.) -
Server-side graphics generation
I'm looking for a library which allows graphics to be generated. I would be able to run a function that plots some points and then draws a graphic which looks something like the picture below. https://i.stack.imgur.com/Zbrcp.png I'm developing a web application so it would be great if this could be done without creating a image, however this is not an imperative. -
How to save User objects in many to many field ?
I'd like to save two user objects in a ManyToManyField after a form POST, like so : ManytoManyField: [<User: user1>, <User: user2>] Here is what my code looks like, templates/page.html <form method="POST" action="...to my view..."> {% csrf_token %} <button type="submit">Send</button> </form> views.py if request.method == 'POST': user1 = ...<User: user1>... user2 = ...<User: user2>... two_users = [user1, user2] form = MessageForm(request.POST) if form.is_valid(): save_it = form.save(commit=False) save_it.users = two_users save_it.save() return redirect('/') ... return render(request, "room.html", {...}) models.py : class Message(models.Model): users = models.ManyToManyField(User) ... This code is an example of what I'm trying to do, this is what it should look like in the admin page after being saved : How can I achieve this ? -
How do I re-create databases after they were deleted?
I used the python manage.py makemigrations myApp and python manage.py migrate myApp commands to create Postgres tables in my database. Then someone manually deleted them with SQL queries. Can I re-create these tables, without data, using terminal commands? -
how to save an array of objects in django database
i'm writing a project with django and i ran into a bit of a problem: I need to define a model which contains an array [list] of TimeField. I'm not sure if i can use ArrayField since my database is sqlite (although i'm migrating to psql). what's the standard way to save an array of objects in django?I can't seem to find a descent answer. thanks in advance. -
django npm and node packages architecture
On the project I am joining this is the architecture for the node_packages: |- Django project |-- app1 |-- app2 |-- node_modules |--- foundation-sites |--- grunt |-- static |--- css |--- images |--- js |--urls.py |--settings.py |--package.json I personally think node_packages should be in the static under the js folder as well as the package.json like so: |- Django project |-- app1 |-- app2 |--- foundation-sites |--- grunt |-- static |--- css |--- images |--- js |---- node_modules |---- packages.json |--urls.py |--settings.py is there a difference? which is best practice? why? -
How to save a model in django when some of the fields are populated by a sequence in oracle?
I have a model MyModel in django one of whose fields gets a value from a sequence upon insert into Oracle 12c. So I do myModel = MyModel(field1=123,field2='abc') myModel.save() The problem is that field1 gets its value upon insert into the Oracle database. If I omit the field then try to save I get ORA-01400: cannot insert NULL. There's no way I can give the field a value in django, either. How do I save the model? Thanks. -
Automated tasks in django
I have a task in django. The Model can be described as Col1,Col2,Col3; all character values. I need to modify my mysql database(The above model), already connected to Django, everyday in the following ways: The value of col1=col2; and Col2=col3; The aforesaid task has to be performed in django, everyday.It is a kind of updation I need to perform automatically, before further interactions with the app. Can any one suggest me a suitable path to achieve so, specifically how do I update my model? -
AttributeError when using custom UserDetailsSerializer in django-rest-auth
We have created a custom UserDetailsSerializer but when trying to run the application we get the error: AttributeError: module 'path.to.serializers' has no attribute 'UserDetailsSerializer' The full error is pasted here. We've set up REST_AUTH_SERIALIZERS and USER_DETAILS_SERIALIZER in the django settings as the doc suggests as well as imported rest_auth in the serializers file but it just doesn't work. The name of the custom serializer is also UserDetailsSerializer - I've already tried different names to see if that was the problem but it wasn't. The workaround that we did was to remove the following lines from our local virtualenv, in the file /lib/python3.5/site-packages/rest-auth/serializers.py: # Required to allow using custom USER_DETAILS_SERIALIZER in # JWTSerializer. Defining it here to avoid circular imports rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {}) JWTUserDetailsSerializer = import_callable( rest_auth_serializers.get('USER_DETAILS_SERIALIZER', UserDetailsSerializer) ) And replacing JWTUserDetailsSerializer with UserDetailsSerializer in the same file. I know it's not a good practice to change third parties code and it doesn't make any sense to remove specifically the lines that are told to be required to allow custom USER_DETAILS_SERIALIZER, but we don't know whatelse to do to make it work, are we missing something? a config maybe? We're using django v1.10.1, djangorestframework v3.4.7 and django-rest-auth v0.9.0 -
Why this combo box look like this?
I am using Django smart selects but when the page load the combo look like an error if i remove jquery it look normal but the smart select don't work, how can I revolve that? When the pase load the combo look like this image But when I select an option the mark remove Sorry for my english -
Using a Django project and static files in a subfolder of root
I recently deployed a Django project to my DigitalOcean Droplet. I need to access it in a subfolder of root (i.e. www.domainname.com/). So far this works using the WSGI Aliasing in the apache config files. I am having trouble serving static js files though. I am using the {% static %} tag in templates to do this. However my js files seem to always be replaced by the current page's html when I inspect them in the browser. Here are my static related settings in settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/html/<project name>/static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "/static"), ]