Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python: Calling a model/class function with an argument from Template
In Django 2.0, I'm trying to call a method from a class, from a template. Call from template {% test.method(user) %} Method from class def method(self, user): return Test.objects.filter(test_id=self.id, user_id=user.id) I know this isn't possible, but what would be the best alternative? There's no way I can execute the query without passing user as an argument. Thanks! -
Django Project: namespace 'admin' isn't unique
on trying to run C:\Python34/python manage.py makemigrations, I get the following error: Error WARNINGS: ?: (urls.w005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLS in this namespace What precisely do I need to change and where do I need to look? teachers/url.py from django.contrib import admin from django.urls import path from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.teachers, name='teachers'), ] url.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('teachers/', include('teachers.urls')), ] main/url.py urlpatterns = [ path('admin/', admin.site.urls), path('header/', views.header, name='header'), path('', views.index, name='index'), ] I've pasted the various url.py files above and imagine it's a problem somewhere there. could anyone please point me in the right direction, with an explanation please? I've considered that I could/should remove path('admin/', admin.site.urls), from all but the urls.py file (root) .....when I do remove this, I don't get the same error, but I don't know if that will cause other problems and if this is the right thing to do? -
Django display a value from a dictionary within dictionary
I'm trying to display values from a dictionary within a dictionary in a template using django. I have a dictionary like this in my views: characters = { "char1": {'name': "David", 'stars': 4, 'series': "All star"}, "char2": {'name': "Patrick", 'stars': 3, 'series': "Demi god"} } I can display the whole dictionary on the page, however I want to display only the 'name' and 'David' key:value pairs. I wrote the following in the template: {% for char in characters %} {% for key, value in char %} {{ key }}: {{ value }} {% endfor %} {% endfor %} However this doesn't show me anything. What is wrong with this double loop? Thanks -
How to render Django flat pages as plain text with line breaks (no html tags allowed)
We have a continuing need to update an ads.txt file that lives at the root of a Django project. The current method to update this file is ftp it and a “service nginx restart” performed by a developer. We want to now do this with a flat page and template and simply have a “non-developer” cut and paste the contents of the ads.txt file into the Content: field via the Django administration app, save and all should be well. The issue is the line breaks do not render unless we add html tags. This causes the ads.txt file to not pass validation tests since no html is allowed, only plain text. How can we accomplish this? The template is simply {{ flatpage.content }} Trying {{ flatpage.content|linebreaks }} causes html tags to be inserted into the rendered page and fails the ads.txt test. We’ve tried various combinations such as (r'^ads_txt/$', 'media.views.custom_header') in urls.py and def custom_header(self): self.response.headers['Content-Type'] = 'text/plain' in views.py to no avail. -
(1048, "Column 'user_id' cannot be null") when submitting form - Django
When I try and upload an image, I am getting an error (1048, "Column 'user_id' cannot be null") however, there is no user_id column. I tried setting user = models.OneToOneField(null=False), but it did not work. models.py class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=140, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') image = models.ImageField(upload_to='profile_image', default='profile_image/Default.jpg') def __str__(self): return self.user.username forms.py class UpdateBioForm(forms.ModelForm): image = forms.ImageField() class Meta: model = UserProfile fields = ( 'image', 'city', 'website', 'description', ) widgets = { 'description': forms.Textarea(attrs={'rows': 4, 'cols': 15}), } def save(self, commit=True): savedBio = super(UpdateBioForm, self).save(commit=False) savedBio.image = self.cleaned_data['image'] savedBio.city = self.cleaned_data['city'] savedBio.website = self.cleaned_data['website'] savedBio.description = self.cleaned_data['description'] if commit: savedBio.save() return savedBio views.py def update_bio(request): if request.method == 'POST': form = UpdateBioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else: form = UpdateBioForm(instance=request.user) args = {'form': form} return render(request, 'accounts/update_bio.html', context=args) -
Is it possible to isolate side effects in a python web framework (django, pyramid, flask) view? If so, how?
I usually try to keep all my business logic outside of the view and let the view only deal with view specific things. However, this still doesn't help in isolating side effects. For example, if I set up a view that accepts a POST request to create an item, I usually do a few things Validate incoming request data Transform any arguments if necessary Create the item and save it to the db I have seen the effect library but I don't love the syntax and it hasn't been updated in 3 years. On the front end, Redux does a pretty good job at isolating side effects with middleware. -
Virtualenv have multiple possible locations
A colleague of mine implement a shell script with the following line output="$(venv/bin/python manage.py has_missing_migrations --quiet --settings=project.tests_settings 2>&1)" Here is the full code : # Check missing migrations output="$(venv/bin/python manage.py has_missing_migrations --quiet --settings=project.tests_settings 2>&1)" [ $? -ne 0 ] \ && ipoopoomypants "Migrations" "$output" \ || irock "Migrations" If I run the script, I obtain Running pre-commit checks: [OK] anonymize_db ORM queries [OK] Forbidden Python keywords [OK] Forbidden JavaScript keywords [OK] Forbidden HTML keywords [FAIL] Migrations COMMIT REJECTED: .git/hooks/pre-commit: line 88: venv/bin/python: No such file or directory The problem with the above line is it takes into account that the virtual environment has been created inside the project itself. However, it is not always the case. From what I am concerned, I work with virtualenvwrapper. Hence, my virtualenv is not ./venv, but well in ~/.virtualenvs/venv. Question : How could I modify the above line in such a way it will consider both path ./venv and ~/.virtualenvs/venv? -
DRF login generate token and session at the same time
My site uses Django Rest Framework with an angular frontend and knox tokens for login. I want to add django-wiki to my site and right now it works, except users that login to my site who want to visit the wiki have to login again because django-wiki uses session authentication and my site uses tokens. Is there a way for a DRF login action to return both a token and a session? -
Django/Python - Error: That port is already in use
I'm trying to host my Django website for the first time, but it appears that the port is already in use. I haven't hosted anything before and I get the following result with netstat -ntlp: I would like to keep the standard port if possible... does anyone know a solution? I'm not sudo user. -
Django not rendering anchor tags childs properly
I have this and Django is rendering this One anchor tag child was rendered outside its parent. I did the same with a div instead of anchor tag and it worked just fine. That code block was inside a {% for %}. removed the for and deleted every template tag. Django still doesn't render properly. -
django related field exists after delete
I've an Order model and others models which related with it. An user can delete any of this items and I must perform a check if the order is empty after deletion and set as active False in case true. Some basic code to ilustrate it class Order(models.Model): paid = models.BooleanField(default=False) active = models.BooleanField(default=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) def empty_order(): """ I must implement it """ class HomeOrder(models.Model): ... order = models.OneToOneField(Order, related_name='primary_home') class TourOrder(models.Model): ... order = models.ForeignKey(Order, related_name='tours') I have a post_delete signals that are connected with every of this Models related to Order: post_delete.connect(delete_order_if_empty, sender=HomeOrder) post_delete.connect(delete_order_if_empty, sender=TourOrder) def delete_order_if_empty(sender, instance, **kwargs): if instance.order.empty_order(): instance.order.active = False instance.order.save() An Order can have one Home, so if the Home exists I can do order.primary_home, if Home does not exist it will raise an AttributeError because it is an OneToOne relationship. An Order can have many Tours, so in the empty_order method I thought to do some checks as following. def empty_order(): home = hasattr(self, 'primary_home') # Avoid AttributeError exception tours = self.tours.exists() this_order_has_something = primary_home or tours return not this_order_has_something Now, when I delete an HomeOrder the signal is raised but the empty_method never realized that this HomeOrder does not … -
Distinct in Django model, not the view?
If I have a database table that has a list of ID's and a description I need without the additional attributes. How can I do a group by in my Django model to limit my data set to the first two columns below as shown in the results, similar to a group by in SQL? id name attribute 1 a a 1 a b 1 a c 1 a d 2 b a 2 b b 2 b c 3 c a 3 c b desired result: id name 1 a 2 b 3 c Again i'm looking to do this in my model and not the view using .distinct() and order by.. Here is my current model: class QVDSSSecurityDimension(models.Model): id = models.CharField(db_column='CM_Data_Restriction', serialize=False, max_length=10, primary_key = True) # Field name made lowercase. name = models.CharField(db_column='CM_Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'QV_DSS_Security_Dimension' The reason i'd like to do it in my model is because I get the following error because there are 8 attributes associated with QVDSSSecurityDimension for most users id's and this relates to the User table as a foreignkey MultipleObjectsReturned at /account/profile/ get() returned more than one QVDSSSecurityDimension … -
Custom Workflow?
I need to implement a standard workflow with three linear steps to handle, i.e. Select Plan & Preference, Personal Information, and Review & Payment. I know three available workflows with python3 and Django, but I think it is overkill for what I am going to do. Select Plan & Preferences: A client may choose one plan as well as some craft products. Personal Information: A client will fill fields related to where he lives, phone number, first name, last name, email, ... Review & Payment : Create an account if necessary, Review his/her order and make the payment related to the current order. Availabe Workflow - With Python 3 Maybe the solution is to implement a custom workflow, but I am a bit confused how to do it. I need a user follows some views step by step. Could someone explain to me roughly how can I do it? P.S. I am working with Django 1.11 and python 3.4. -
Django ldap module error "AttributeError: module 'ldap' has no attribute 'OPT_X_TLS_REQUIRE_CERT'"
I try to start my Djngo project and I catch this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/erastov/PycharmProjects/auction/auc_env/lib/python3.5/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/erastov/PycharmProjects/auction/auction/backend/auction/settings/dev.py", line 1, in <module> from .base import * File "/home/erastov/PycharmProjects/auction/auction/backend/auction/settings/base.py", line 86, in <module> ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER AttributeError: module 'ldap' has no attribute 'OPT_X_TLS_REQUIRE_CERT' I use Python 3.5, Django 1.11.7, ldap 1.0.2 It's happend when I remove my local project and clone from github again. I installed all requirements as usual. -
Get queryset data of django by ajax
I am trying to sending a json response from django views. Using below code. msg_obj=Message.objects.all() msg_list=list(msg_obj.values()) print(msg_list) return JsonResponse(msg_list,safe=False) Then on success in ajax I am doing like this:- success: function (data) { alert(data['id']) $('#msg-list').append("<p> he" + data['id'] + "</p>"); } if I print msg_list in django it gives me result like this: [{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'},{'id': 1, 'username_id': 2, 'fusername_id': 3, 'text': 'hello friends'}] I have tried many combinations but unable to get or print the data back at client side(ajax on success function). Thanks in advance for any help. -
Updating Python without sudo commands?
I'm currently on Python 2.7, I want to update to 3.6.3 and also install Django afterwards. However I'm not super user, so I can't use Sudo commands. -
Child model field values when Parent Class is deleted
I have a lot of models in my database that inherit from a BaseModel. The Base model only has a few fields on it though, for creation/expiration dates etc. If I deleted the parent class altogether, moved those inherited class fields to its child, and than remigrated the schema of my database, what will happen to those field values ? Will they stay there, or be deleted ? If I did delete the parent class, i'm sure order of operations would matter. Base class BaseModel(models.Model): class Meta: abstract = True created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) @classmethod def model_field_exists(cls, field): try: cls._meta.get_field(field) return True except models.FieldDoesNotExist: return False class ChildModel() name = models.Charfield(max_length=255) age = models.IntegerField(default=1) New ChildModel class after deleting BaseModel class ChildModel() name = models.Charfield(max_length=255) age = models.IntegerField(default=1) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.SET_NULL) -
Can't use any sudo commands on linux?
I'm trying to update python and install django on my linux server, but I can't get sudo commands to work. Whenever I type a command with sudo, I get the following >>> $ sudo apt-get update File "<stdin>", line 1 $ sudo apt-get update ^ SyntaxError: invalid syntax Server info Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 I don't know what type of linux this is unfortunately. -
django-rest-auth: Reverse for 'account_reset_password_from_key' not found
I have been trying to setup password reset functionality in DRF using django-rest-auth. Earlier I was getting error TemplateDoesNotExist:registration/password_reset_email.html which I resolved by adding the following code code serializer.py - from rest_auth.serializers import PasswordResetSerializer from allauth.account.forms import ResetPasswordForm class PasswordSerializer(PasswordResetSerializer): password_reset_form_class = ResetPasswordForm settings.py - REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'api.serializers.PasswordSerializer', } However, Now I am getting into another issue - "NoReverseMatch: Reverse for 'account_reset_password_from_key' not found. 'account_reset_password_from_key' is not a valid view function or pattern name.". And haven't found any solution or workaround for this. Any help would be appreciated. -
"Your credentials aren't allowed" - Google+ API - Production
I recently implanted the connection with facebook and google on my local server, and everything worked. But, when I tried to do it in production, the connection with google returns: "Your credentials aren't allowed". (Facebook works) I don't know why, because i'm pretty sure that my application is confirmed by Google. Do you have some ideas ? Thanks in advance ! -
Group_by in Django Database | Most efficient query order
I'm working on an old django app which unfortunately has one giant table in the database, meaning conventionally our queries are very slow. We cannot migrate the DB nor re-factor it into multiple tables for reasons beyond my control. I would like to make sure that these queries are as efficient as possible because they are a bit more complex than the queries that are typically being done in this app. For the following questions consider the following table schema: Table Orders: name: string price: integer order_date: date Django version = 1.6.5 Question 1 I'm coming from Rails, in which I would typically use the groupdate gem to group output as such: >> Orders.group_by_day() >> >> { 2013-1-1: {<all orders taking place on Jan 1st, 2013>}, 2013-1-2: {<Jan 2nd 2013>}, ... } Is there something built into Django that does something similar efficiently? I found https://docs.djangoproject.com/en/2.0/topics/db/aggregation/ but it doesn't appear as though it outputs in a similar manner. Question 2 Does the order in which you stack queries affect the speed at which it is executed? For example given the same query written in 3 different ways: Orders.where(price > 5).group_by_day() Orders.group_by_day().where(price > 5) { partial_orders = Orders.where(price > 5) partial_orders … -
using request.user in templatetags in Django
I am using Django 2.0 I have three tables notes, starred and shared notes model def Notes(models.Model): title = models.CharField() def Starred(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def Shared(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) the note can be shared with multiple users and multiple users can star the note which will be listed in their /starred notes views.py has class SharedNotes(ListView): template_name = 'notes/shared.html' model = Shared context_object_name = 'shared_notes' def get_queryset(self): shared_notes = Shared.objects.filter(user=self.request.user) return shared_notes @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) I have written a separate template snippets to display list of notes and add * (star) if it is starred by logged in user using {% if note.starred_set.all %} <span class="card-star"> <i class="material-icons">star</i> </span> {% endif %} But this way star is showing with other users the note has been shared with even when they have not starred the note but has been starred by someone else. How to filter the starred only to logged in user? I thought of to write a tag to be used like {% if star.pk|starred %} <!-- add html star code here --> {% endif %} and filter tag in … -
Returning distinct objects sorted by SearchRank involving multiple tables
I have a model class called Poll which has title, description, and tags fields. I also have a PollEntry class (related_name=entries) which also has title, description, and tags. I am trying to implement text search (using contrib.postgres.search) module. There are apparently issues with returning a search ordered by rank returning duplicate objects and the Django documentation says basically "You have to be careful", but does not give any examples of how to deal with this, and I have had basically no luck finding examples online (on SO or elsewhere). The following code snippet appears to solve this problem, but I don't know if it is the most efficient way to do this. Any suggestions or references would be much appreciated! Also, note I am using DRF here. @list_route(methods=['get']) def search(self, request): search_query_terms = request.query_params.get('searchQuery').split(' ') search_vector = SearchVector('entries__tags__name')+\ SearchVector('title')+\ SearchVector('description')+\ SearchVector('tags__name')+\ SearchVector('entries__title')+\ SearchVector('entries__description') search_query = SearchQuery(search_query_terms[0]) for term in search_query_terms[1:]: search_query = SearchQuery(term) | search_query ids = Poll.objects\ .annotate(rank=SearchRank(search_vector, search_query))\ .order_by('-rank')\ .filter(rank__gt=0)\ .values_list('id') polls = Poll.objects.filter(id__in=ids) serializer = self.get_serializer(polls, many=True) return Response( data=serializer.data ) -
How to increment a numeric string in Python
I've spent the last two days trying to figure out how to increment a numeric string in Python. I am trying to increment a sequence number when a record is created. I spent all day yesterday trying to do this as an Integer, and it works fine, but I could never get database to store leading zeros. I did extensive research on this topic in StackOverflow, and while there are several examples of how to do this as an Integer and store leading zeros, none of the examples worked for me. Many of the examples were from 2014, so perhaps the methodology has changed. I then switched over to a String and changed my attribute to a CharField, and can get the function to work with leading zeros, but now I can't seem to get it to increment. Again, the examples that I found on SO were from 2014, so maybe things have changed a bit. Here is the function that works, but every time I call it, it doesn't increment. It just returns 00000001. I'm sure it's something simple I'm not doing, but I'm out of ideas. Thanks in advance for your help. Here is the function that works … -
ObtainAuthToken fails with 404 when using local network IP
I'm trying to connect an Android device to my ObtainAuthToken endpoint from the django-rest-framework. If I just call it with http://localhost/api-token-auth it works fine: [21/Dec/2017 16:04:34] "POST /api-token-auth HTTP/1.1" 400 68 But if I change that to http://192.168.1.4/api-token-auth my dev server throws me a 404, like so: [21/Dec/2017 16:05:00] "POST /api-token-auth HTTP/1.1" 404 0 I've tried adding my IP number 192.168.1.4 to ALLOWED_HOSTS but no dice. Trying to Google this issue just brings up a bunch of unrelated stuff. Anyone knows what might be causing this?