Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How make an admin action enabled or works just one time a year?
I need to make an admin action enabled or works just one time a year is this possible Here is the action : def update_vacations(modeladmin, request, queryset): for item in queryset: item.calculconge = item.calculVacation + item.VacationDays item.save() update_vacations.short_description = "Update Vacations" -
Merging multiple querysets in Django Rest Framework
How can you merge querysets in Django? I use the Django Rest Framework. I work with the following model: class City(models.Model): ... class House(models.Model): city = models.ForeignKey(City, ...) ... class Resident(models.Model): house = models.Foreignkey(House, ...) ... I now want to have a view that lists all the residents of a given city (slug is the slug of the city). Here is how I wrote it: class ResidentList(generics.ListAPIView): lookup_field = 'slug' serializer_class = ResidentSerializer permission_classes = (IsAuthenticated, IsMayor) def get_queryset(self): residents = Resident.objects.filter(house__city__slug=self.kwargs['slug']) return residents As you can see I create the list of residents for a city by iterating through all the citizens and filter those who life in a home that lifes in the right city. I just feel like this is pretty bad and inefficient, since the database has to loop through ALL the citizens. It would be better to have something like City.objects.get(slug=<cityslug>).houses.residents Then I would only have to loop through the smaller amount of cities. The problem with this obviously is that the above query returns a queryset. Therefore I can't chain houses and residents like that. Any help would be much appreciated! :) PS: If you have other suggestions how I can improve my view … -
AllowAny for get method in djangorestframework
I use django rest framework, example code class TestApiView(APIView): def get(self, request): return Response({'text': 'allow any'}) def post(self, request): return Response({'text': 'IsAuthenticated'}) how to make method get allow any, method post only authenticated thank you in advance -
WebSocket connection to 'ws:url' failed: WebSocket is closed before the connection is established
I am pretty new to Django Channels and when i went through some tutorials i came across this project Channels Examples.When i run the project in my system, i get the following error. 127.0.0.1:56653 - - [20/Feb/2018:17:18:37] "GET /new/" 302 - 127.0.0.1:56653 - - [20/Feb/2018:17:18:38] "GET /royal-dawn-8676/" 200 1865 127.0.0.1:56653 - - [20/Feb/2018:17:18:38] "GET /static/chat.js" 304 - 127.0.0.1:56669 - - [20/Feb/2018:17:18:38] "WSCONNECTING /chat/royal-dawn-8676/" - - 127.0.0.1:56669 - - [20/Feb/2018:17:18:40] "WSDISCONNECT /chat/royal-dawn-8676/" - - 127.0.0.1:56677 - - [20/Feb/2018:17:18:41] "WSCONNECTING /chat/royal-dawn-8676/" - - 127.0.0.1:56677 - - [20/Feb/2018:17:18:43] "WSDISCONNECT /chat/royal-dawn-8676/" - - 127.0.0.1:56680 - - [20/Feb/2018:17:18:45] "WSCONNECTING /chat/royal-dawn-8676/" - - 127.0.0.1:56680 - - [20/Feb/2018:17:18:47] "WSDISCONNECT /chat/royal-dawn-8676/" - - Note: My Django Version -1.11.8, Channels Version-1.1.6 -
How do I invoke a lambda function inside a views function in Django?
I have a Django views to create a sort of AWS pack (contains account and new vpc creation), I am trying to invoke a lambda function in between that will delete the default vpc in the newly created account. Here is my snippet : def createlab(request): if request.method == 'POST': lab_name = request.POST.get('labname') cidr = request.POST.get('cidr') bill = request.POST.get('budget') email = request.POST.get('email') #CREATE ACCOUNT org = boto3.client('organizations') acc = org.create_account( Email=email, AccountName=lab_name, IamUserAccessToBilling='ALLOW' ) time.sleep(35) cid = acc['CreateAccountStatus']['Id'] #GET ACCOUNT DETAILS status = org.describe_create_account_status( CreateAccountRequestId=cid ) print(status) time.sleep(17) while True: status = org.describe_create_account_status(CreateAccountRequestId=cid) try: accid = status['CreateAccountStatus']['AccountId'] break except KeyError: time.sleep(40) accid = status['CreateAccountStatus']['State'] #CREATE VPC session = boto3.Session (aws_access_key_id=acc_key, aws_secret_access_key=sec_key,aws_session_token=token) ec2 = session.resource('ec2',region_name=region_ec2_sub) vpc = ec2.create_vpc(CidrBlock=cidr) id = vpc.id #DELETE DEFAULT VPC client = boto3.client('lambda',region_name='us-west-2') deletevpc= client.invoke(FunctionName='default_vpc', InvocationType='RequestResponse') print (deletevpc) I have included a portion of my views function. I have added the #DELETE DEFAULT VPC snippet in the end. The lambda function is not getting executed. What am I doing wrong here ? -
Django, Markdown and SageCell
I am building a blog with Django. This blog is made up by posts whose content would benefit a lot from using Markdown syntax. But some of this posts also include SageMath cells, which process some Python-Sage Code enclosed in some special divs, as in this tutorial. Now every Markdown engine parses the Python code, and both tools (Markdown and SageMath) come into conflict. Which would be smartest approach for implementing these posts? -
Error in installing pypiwin32
I wanted to parse *.msg file with python and I need to import win32com.client in python programming. Then it is giving me that this module is not defined then I am trying to install pip install pypiwin32 I am using ubuntu 17.10 and it is giving me error import _winreg ImportError: No module named _winreg I am also attaching the screenshot for a better understanding of the problem. is this only for windows, I am highly confused. Some other way of parsing the .msg file with python would also be appreciated. Please help me out.First attachment of code Error screenshot -
Add non-model field in Serializer DRF
I trying to combine rasters model field with non-model config_version field into my serializer which looks like: class RasterPostSerializer(serializers.ModelSerializer): class Meta: model = Raster fields = ( 'name', 'description', 'filepath' ) class ConfigurationSerializer(serializers.Serializer): config_version = serializers.CharField() rasters = RasterPostSerializer(many=True) def create(self, validated_data): data_field = validated_data['rasters'] for raster in data_field['rasters']: return Raster(name=raster['name'], description=raster['description'], filepath=raster['filepath']) Before utilize serializer.save() method I would like to check config_version in my view.py, but after that the .save() gives me: The serializer field might be named incorrectly and not match any attribute or key on the `Raster` instance. Original exception text was: 'Raster' object has no attribute 'config_version'. What is going on, and is there a solution for that? -
PostgreSQL ArrayField is too slow in Django
I'm performing the following query in my Django project: for obj in Path.objects.filter(Q(server_name__exact=name), Q(keywords__overlap=all_words)): The field keywords is an ArrayField and I'm using the overlap filter which is equivalent to something like following in python: keywords.intersection(all_words) # if keywords is a set Now the problem is that when all_words is a small list, less than 10, it does the job very fast but when all_words is a larger array, more than 20-30, it takes so much time. Is there any way around this? I tested other ways like the following but it's didn't make any different. for obj in Path.objects.filter(server_name=name): if all_words.intersection(keywords__overlap): -
Django don't create new sqlite table for new app model
pretty new to Django, i'm encountering an issue with a new model (and a new app 'blog' i made). The table blog_post didn't exist after configuring the model and makemigration. Here is the all process i did. I'm following official tutorial: Here is my blog/models.py: from django.db import models class Post(models.Model): title = models.CharField(max_length=80) text = models.TextField() author = models.ForeignKey('auth.User', on_delete= models.CASCADE) created_date = models.DateTimeField() pub_date = models.DateTimeField() def publish(): self.pub_date = timezone.now() self.save() mysite/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', ] After the first python manage.py makemigrations blog Migrations for 'blog': blog\migrations\0001_initial.py - Create model Post python manage.py sqlmigrate blog 0001 BEGIN; -- -- Create model Post -- CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(80) NOT NULL, "text" text NOT NULL, "created_date" datetime NOT NULL, "pub_date" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id"); COMMIT; python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: No migrations to apply. So, here it is. The new table didn't seem to be created. I check with a SqLite utility and the is no such table: … -
Django channel vs node socket.io
I want to develop a real time chat application and also want to show real time graph/chart.I am confused to choose technology.I heard a lot of good things about nodejs socket.io and also heard about django channel.Can you suggest me to choose from one of them for my project? There need a special feature though.I need to run a cron job to get data from external web service and broadcast it to all clients. Thanks in advance -
How to change table object name in django?
I have a table named Product. Every time I create a object using the table django automatically names it as Product object(1), Product object(2) and so forth. Instead of Project object(1) I want to name it something creative. In my Product Table I have a field called Product Name. Whatever I insert into this field I want that to be the name of the object. If I insert Pen, it should simply show Pen not Product object(1) or anything like that. I am attaching a picture so you guys can understand my problem clearly. -
ImportError: No module named 'basic' in Python
First of all, I am a Django rookie, so pls get that. I am trying to set up local enviroment, so I can run a web page locally on a VM. But I am getting ImportError: No module named 'basic' in Python error, no matter if I'm trying to run as su or not. Django version is 2.0.2 Python is 3.4.3 This is my output -
OTP authentication in Django and Populate model data with Sql data
I am working on assignment given to me, and this is the requirement: Customise the Django User Table Instructions: Modify the default Django user table and the custom user table should consist of the following fields. First Name Last Name Gender Email ID (Primary Key) Phone Number There is no “password” field. The password to login will be an OTP either sent to their mail or Phone Number. Write Rest APIs for Signup, Login, Logout. Create HTML pages for the same. Every time a user tries to Login, OTP is sent and he has to use that OTP to login. Use the given sql dump (world.sql) to create the other models and to populate the data. This will give you the data to display once the user logs in. On login, the dashboard with just one search bar and search button should be displayed. (refer google home page) As user starts typing in the search bar, the system should autosuggest options available in the system. The user will search by city or country or language. Once search button is pressed, list of relevant information should be displayed in the next screen. Where ever the name of a country appears, it … -
On two related models, which one should contain the definition of the relationship?
First of all, yes: I've read Django's foreign key and many-to-many documentation, but I'm still not 100% clear on how to implement relationships on a practical level, especially regarding the hierarchy of the relationships. One-to-one I am aware of how to form one-to-one relationships. However, on a more conceptual level, which model should contain that reference to the other one? Let's say I have a Citizen, and a Passport. Now, it's obvious that one Citizen can only have a single Passport and viceversa, but, ideally, should the Citizen contain a field referencing his Passport, or should the Passport model contain a reference to the Citizen it belongs to? Many-to-many For the sake of simplicity, let's say I have a Person model and a Trip model (Trip as in going out on a trip somewhere). Many Persons can participate in a single Trip. Or in other words: a Person can participate in many Trips and in any single Trip, a lot of Persons can participate. This looks a like a many-to-many relationship, but, again, ideally, which model should contain the definition for the relationship, the Person with a trips field or the Trip with a participants field? And why? Does it … -
supervisor.config giving ERROR [unix_http_server]: command not found
I am using supervisor in my django project. Here is my supervisor.config file looks like [unix_http_server] file=/tmp/supervisor.sock [supervisord] logfile=/tmp/supervisord.log logfile_maxbytes=50MB logfile_backups=10 loglevel=info pidfile=/tmp/supervisord.pid nodaemon=false minfds=1024 minprocs=200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock [program:run_django] environment=DJANGO_SETTINGS_MODULE=%(ENV_DJANGO_SETTINGS_MODULE) command=/home/ubuntu/www/project-venv/bin/gunicorn project.wsgi:application -w 1 -b 127.0.0.1:8000 -t 300 --max-requests=100 directory=/home/ubuntu/www/project/ user=ubuntu stdout_logfile=/home/ubuntu/www/project/logs/django_stdout.log stderr_logfile=/home/ubuntu/www/project/logs/django_stderr.log autorestart=true redirect_stderr=true But I am getting the following error I try to deploy onto AWS EC2 instance through CodeDeploy [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 1: [unix_http_server]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 3: [supervisord]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 13: [rpcinterface:supervisor]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 14: supervisor.rpcinterface_factory: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 16: [supervisorctl]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 19: [program:run_django]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 20: syntax error near unexpected token (' [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 20: environment=DJANGO_SETTINGS_MODULE=%(ENV_DJANGO_SETTINGS_MODULE)' What did I miss here? -
Is there a way to autocomplete a field respective to another field?
template.html <div class="form-group col-sm-12 col-md-12"> <label for="id_amount_in_figure">Amount in figure:</label> <input type="number" name="amount_in_figure" id="id_amount_in_figure"> </div> <div class="form-group col-sm-12 col-md-12"> <label for="id_amount_in_word">Amount in word:</label> <input type="text" name="amount_in_word" id="id_amount_in_word"> </div> This is my code to convert number to words using python. def figures_to_words(figure, join=True): units = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] ens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] hundreds = ['thousand', 'lakh', 'crore'] words = [] if figure == 0: return '' else: figureStr = str(figure) # 232194622 figureStrLen = len(figureStr) # 9 thouLen = figureStrLen - 3 # 6 thou = figureStr[0:thouLen] # 232194 groups = (thouLen+1)//2 # 3 thouStr = thou.zfill(groups*2) # 232194 for i in range(0,groups*2,2): a, b = int(thouStr[i]), int(thouStr[i+1]) # i=0 a=2 b=3 # i=1 a=2 b=1 g = groups-(i//2+1) # g=2 g=1 j = g if (a>1) and (g==j): words.append(tens[a-1]) if b>=1: words.append(units[b-1]) words.append(hundreds[g]) elif a==1 and g==j: if b>=1: words.append(ens[b-1]) else: words.append(tens[a-1]) words.append(hundreds[g]) else: if b>=1: words.append(units[b-1]) words.append(hundreds[g]) j -= 1 huns = figureStr[-3:] hunsStrLen = len(huns) gro = (hunsStrLen + 2) // 3 huns = huns.zfill(gro*3) if len(huns) <= 3: h, t, u = int(huns[0]), int(huns[1]), … -
Django: Adding an instance of object to all ForeignKey related models
I have model Chamber: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) And related model ChamberProperty: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100, default=None) Right now a Chamber can have many ChamberProperty. The requirements were just changed to make it so that if a ChamberProperty is added to a Chamber, it gets added to all future Chamber instances as well, with an empty property_value (default=None), so that the next time the form for creating a new Chamber instance is loaded, all previous ChamberProperty.property_name are loaded in the form, and empty. Example forms: First time a Chamber instance is created: Chamber.chamber_name: Foo ChamberProperty.property_name: Bar ChamberProperty.property_value: Baz Second time a Chamber instance is created: Chamber.chamber_name: Qux ChamberProperty.property_name: Bar # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Quux # New property, added by a button ChamberProperty.property_value: 700 # New property, value filled with input box Third time a Chamber instance is created: Chamber.chamber_name: Corge ChamberProperty.property_name: Bar # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Quux # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Ouier # New property, added by a button ChamberProperty.property_value: Grault … -
Where does user-uploaded content go in my AWS S3 storage?
I've set up my AWS S3 storage for my Django project. My static folder in my S3 Bucket has all my static files. However where do the files which would usually go in media go? i.e files uploaded from users? -
Django rest-framework; show different content to authetificated and anonymous users
I try to implement rest_framework for Django 2. I have a URL that should show diffrent content for authentificated users. Anonymous users just will get a limited view, authentificated will see everything. In the documentation I can only methods that will deny everything, but not a if else clause. Basicly I try something like this: class StoryViewSet(viewsets.ModelViewSet): if IsAuthenticated == True: queryset = Story.objects.all() else: queryset = Story.objects.filter(story_is_save=True) serializer_class = StorySerializer Obviously IsAuthenticated is not a True/False statement i can query. Any ideas how I could do this easily? Thanks -
django customizing admin interface
i have added ADD SUPPORT USER button to django admin interface like this by overriding admin change_list template. when i click ADD USER it takes me to 127.0.0.1:8000/admin/auth/user/add . if i click ADD SUPPORT USER button it should take me to 127.0.0.1:8000/admin/auth/user/add_support_user rather than 127.0.0.1:8000/add_support_user. however i get error like this . how do i achieve this? URLS.PY url(r"^add_support_user/", AddSupportUserView.as_view(), name = 'support_user'), CHANGE_LIST.HTML {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li> <a href="/admin/auth/user/add_support_user/" class="grp-state-focus addlink">Add Support User</a> </li> {% endblock %} TREE templates ├── add_support_user.html ├── admin │ └── auth │ └── user │ └── change_list.html └── index.html -
Django reading pdf files content
I'm trying to find a plugin that reads text from PDF files. I found an old post about this issue and the answer was to use the following plugin : pdfminer pluggin However, this does not support python 3. Any suggestions ? -
Django 2.0: combine path and re_path got NoReverseMatch error
Using path in project's urls.py, and using re_path in app's urls.py, I got the NoReverseMatch error, my project's urls.py: from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('user/', include('user.urls', namespace='user')) ] My app's urls.py: urlpatterns = [ re_path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', views.activate_account, name='activate'), ] I can't get the correct url, the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': b'Mjc', 'token': '4tv-d4250012f57297ad82a6'}' not found. 1 pattern(s) tried: ['user\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/'] -
Django Form won't display errors
I am trying to diplay error messages for my registration page. But unfortunetly it does not work at all. When I submit, it just goes to the login page. Here is my register.hmtl {% load widget_tweaks %} <form method="post"> {% csrf_token %} {{ form.as_p }} <div style="margin-top: 1em;"> <button class="btn btn-success btn-sm" type="submit">Konto erstellen</button> <a style="margin-left: 1em;" href="{% url 'accounts:login' %}" id="cancel" name="cancel" class="btn btn-default">Zurück</button></a> </div> </form> </div> </div> {% endblock %} And this is my forms.py (RegistrationForm) class RegistrationForm(UserCreationForm): username = forms.CharField(max_length=30, required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'username', 'autofocus': 'autofocus' } ) ) first_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'first_name', } ) ) last_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'last_name', } ) ) email = forms.EmailField(max_length=30, required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'email', 'name': 'email', } ) ) password1 = forms.CharField(label=("Passwort*"), required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) password2 = forms.CharField(label=("Passwort bestaetigen*"), required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password2', } ) ) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def clean_username(self): existing = User.objects.filter(username__iexact=self.cleaned_data['username']) if existing.exists(): raise forms.ValidationError(("A user with that … -
Django user model username (unique=False)
I have seen many of the solution but none of it seems to be answering the question. My user model is using AbstractUser right now. Is there a way to make username(unique = False) Since i wanted to allow user to ba able to have duplication of same username, as the login im am using is by email address and password