Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to model this table correctly?
Following the suggestions from my last post I got this far: Post model: class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() Group model: class Group(models.Model): title = models.CharField(max_length=200) url = models.URLField(unique=True) contact_updated = models.DateField(auto_now=False, auto_now_add=True) group_status = models.CharField(max_length=20) admin = models.CharField(max_length=20) admin_status = models.CharField(max_length=20) frequency = models.IntegerField() # allowed post frequency frq_scale = models.CharField(max_length=20, blank=True) obs = models.TextField(blank=True) posts = models.ManyToManyField(Post, through='control.Control') Control model: class Control(models.Model): published = models.DateField(auto_now=False, auto_now_add=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE) group = models.ForeignKey('groups.Group', on_delete=models.CASCADE) This is control for posts in groups. I can have 1 post published in many groups controlled from Control model. It is possible for a Post to be published in one group and not in another. How can I produce the table (link above) with those models? Or perhaps there is something I need to change? The table I want to produce -
Can't create a working elasticsearch-py instance
I've got an Amazon ElasticSearch Service running and I can connect fine using a curl/postman, but when I try to create a elasticsearch-py instance my ide hangs indefinitely. endpoints = ['http://XXX.us-east-1.es.amazonaws.com', 'http://XXX.us-east-1.es.amazonaws.com:443', 'http://XXX.us-east-1.es.amazonaws.com:9200'] for endpoint in endpoints: try: es = Elasticsearch([endpoint]) print es.count('analytics_v4') except: print endpoint + " didn't work" this is my current test set up, my IDE (pycharm) completely stops at this point and I need to end the run to be able to try again, I've tried each endpoint individually and none of them work. My access policy is : { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "es:*", "Resource": "arn:aws:es:us-east-1:MYIDdomain/analytics/*", "Condition": { "IpAddress": { "aws:SourceIp": [ "MYIP" ] } } } ] } -
Email verification and password reset - django rest framework and angularjs
How do I implement the built in views for password-reset in the django.rest.auth and how do I create an email verification system for registration using the django rest framework and angularjs? I have been searching for a tutorial or some good documentation that on how to implement django's send_email function in a website using the django rest framework and angular js but I haven't been able to find any. What I need... when a new user registers a url must be generated for them to confirm their email address this url must be automatically sent to the user's given email after the user is sent to this link and confirms their email address their status must be changed from new_user.is_active = False to new_user.is_active = True What I have... registration form that sends a post request to my register endpoint the new user data is then unpacked, validated, and saved in my register view in settings.py i have added this... EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 in my urls.py i have added this... /block of code/ from django.conf.urls import url from rest_auth.views import PasswordResetView, PasswordResetConfirmView urlpatterns = [ url(r'^password/reset/$', PasswordResetView.as_view(), name='password_reset'), … -
Representing a django model with a variable name in a django query
I am trying to create a query set where the model name is stored in a variable as a string. modelName = 'SomeModel' #storing model in variable name modelName.objects.all() #django query When I run the query I get the following error AttributeError: 'str' object has no attribute 'objects' How can I use a variable name to represent the model in the query. -
Django allauth not rendering appropriate model and field names for username field
I am getting this rendered from django-allauth for unique username check. %(model_name)s with this %(field_label)s already exists. A quick search on online shows the email error was resolved and can be overridden with from django.utils.translation import ugettext_lazy as _ from allauth.account.adapter import DefaultAccountAdapter class CustomAccountAdapter(DefaultAccountAdapter): # Overrides default adapter def __init__(self, request=None): super(CustomAccountAdapter, self).__init__(request) self.error_messages['email_taken'] = _('A user is already registered with this e-mail address.') However, overriding the adapter this way cannot isn't working for username. -
Django Admin Actions on single object
The admin actions seem to work on several items selected in the list view of django admin interface: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/actions/ In my case I would like to have a simple action button on the change (one item) view. Is there a way to make the django admin actions available there? I know that I can walk around this problem by going to the list view, and select one item there. But it would be more nice to have it directly available. -
Django - Creating a DOCX and saving to model fileField
I have a model with two fileFields. One fileField is used to save a users uploaded docx. That works great. The other fileField needs to be used to save a docx that the server generates. The generatedDocx works great and is openable. That being said I am having some issues when trying to save it to the fileField. Here is the Code that is giving me trouble. #Generate and Save Docx file_path = path_of_docx name = name of_docx file = open(file_path) ob.generatedTemplate.save(name, File(file)) It results in a UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9a in position 15 Surely what I am trying to do is possible since a docx can be saved via upload right? I was using this Django - how to create a file and save it to a model's FileField? as a reference. -
Django HTTP delete method returns 405
I have create a Django REST Webservice. If I run the following method (delete), I run into an 405 error my view.py @detail_route(methods="delete") def remove(self, request, id): logger.debug("REST " + request.get_full_path()) result = HeatingMappingModel.objects.filter(id=id).delete() self.response = {"result": True, "data":result} return JsonResponse(self.response, safe=False) urls.py ... url(r'^detail/(?P<id>\d+)/$', views.HeatingMapping.as_view({'delete': 'remove'})), ... This is the URL I call http://localhost:8000/heating/detail/6/ But I don't understand why, i read the documentation, but find no clear explanation why. Does someone can give me a hint about this issue? -
Where to find django.contrib.admin.ModelAdmin class source code
I was interested in reading source code of django.contrib.auth.admin.UserAdmin and have found it in django github repo in straightforward corresponding file. But it inherits django.contrib.admin.ModelAdmin which couldn't be located this simple because django.contrib.admin has __init__.py file which internally uses autodiscover_modules utility and I completely misunderstand how it works. The question is: How could I guess in which file is source code of django.contrib.admin.ModelAdmin situated? -
ImportError: No module named 'material'
(venv) ┌─╼ [~/Projects/Work_Projects/credit-24-django] └────╼ django runserver_plus Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/jeremie/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/jeremie/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/jeremie/.local/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jeremie/.local/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/jeremie/.local/lib/python3.5/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) 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 956, in _find_and_load_unlocked ImportError: No module named 'material' This error is a bit weird, since I am connected on my virtualenv venv, and it says that django-material is already installed. (venv) ┌─╼ [~/Projects/Work_Projects/credit-24-django] └────╼ pip install django-material Requirement already satisfied: django-material in /home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages Yet, it is installed install INSTALLED_APPS. How could I fix this error? Be aware that I installed the virtualenv in a virtualenvwrapper. -
Manipulate Image and store at local disk python/django
I'm learning django/python.so i'm totally new to django. i would like to implement image manipulation. I have some images on my local disk(in media folder) on which i want to put watermark image(which is image url/web link). After manipulation i want to store new image on my local folder. Also,i don't want to store updated new image in database. Please suggest me any library or ideas which can serve my purpose. -
How can i save a data on database using django views?
I tried saving data on database using django views but it return a error. def get_enroll(request, pk): user = request.user users = User.objects.filter(username=user) course = Course.objects.filter(pk=pk) chapter = ChapterModel.objects.filter(course = course) abc = Enroll() abc.save_enroll(users, course, chapter) template_name = 'dashboard.html' context = {'users':user,'course':course} return render(request, template_name, context) -
django filter many-to-many with given list
I would like to filter a django model that is connected to an second model via a many-to-many intermediate relationship. class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) design and expected result The result should be to select only Person A because he is connected to Groups with entries 1 AND 2 through the membership. I'd like to use Q objects for this kind of task. Can anyone give me a hint? -
Django is_valid() returns false
I am new to Django. Whenever I submit my Sign Up form form.is_valid() in my view function returns false. I can't figure out where I am going wrong. I use SignUpForm class for additional fields. signup.html is my template. signup is my view function. Is my SignUpForm class in my forms.py is wrong? Any help would be great. I also filled all the details in my signup form but still form.is_valid() returns false in my case. my view function def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() return render(request, 'signup.html', {'message': 'Signed Up successfully'}) return render(request, 'signup.html') my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=255) last_name = forms.CharField(max_length=255) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) phone_number = forms.CharField(max_length=100) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password', 'confirm_password', 'phone_number'] my base.html <body style = "margin: 0;"> <div class="row" style="padding-left: 2%;padding-top:1%;"> <div class="col-md-9"> <h2>Welcome to my site</h2> </div> <div class="col-md-2"> <a href="{% url 'login' %}" class="btn btn-primary" style="margin-right: 6%;">Login</a><br><br><br> </div> </div> <div class="row" style="margin-left: 4%"> <form class="form-group" name="form1" id="form1" method="post" style="padding-top: 1%" action = "{% url 'signup' %}"> {% csrf_token %} <h3>Sign up</h3><br> <div … -
Django model creation with multithreading
My Django app requires a background thread which executes every 60 seconds and reads entries from a model called "rawdata" then runs some calculations based on the data and generates a new record in another model called "results". After doing some research I realize this can be done with celery however I feel a full async task framework is a bit of overkill for what I need. I am new to Django and am trying to determine if my implementation below is safe. My app launches the background process using the "ready" hook of Django like this: class Myapp(AppConfig): name = 'Myapp' ready_done = False def ready(self): if os.environ.get('RUN_MAIN') and Myapp.ready_done==False: from scripts.recordgen import RecordGenerator Myapp.ready_done=True Myapp.record_generator = RecordGenerator() In the app directory I have a /scripts/recordgen.py which spawns a basic independent thread adding new data to the database every 60 seconds. Something like this: import threading import time from Myapp.models import results,rawdata class RecordGenerator(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.start() def run(self): while (1): time.sleep(60) #Query the rawdata here and do some calculations #Just filling with dummy data for this example dummydata = "dummy data" new_record = results() new_record.data = dummydata new_record.save() If records are only added to the results table … -
Getting information of subprocess execution to update a progress bar in django
I'm trying to do a loading page with a progress bar in my django app while a process is running in background. This is my view: def getor(request): # get video var = Video.objects.order_by('id').last() v = '/home/myproject/media/'+ str(var) # process p = subprocess.Popen("./process.sh %s" % (str(v)),stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) return render(request, 'progressbar.html') I have done the progress bar frontend part. How I can get this percentages generated by the execution of process.sh in my django view so that i can give it to my template for the evolution of the progress bar ? -
Django REST Framework: Integrity error on not null column when posting data
I have these two related models: class EndPoint(TimeStampedModel): name = models.CharField(max_length=100) url = models.CharField(max_length=100) description = models.CharField(max_length=100) class Parameter(TimeStampedModel): name = models.CharField(max_length=100) label = models.CharField(max_length=100) required = models.BooleanField() type = models.CharField(max_length=100) format = models.CharField(max_length=100, null = True) endpoint = models.ForeignKey(EndPoint, related_name="parameters",null = True, on_delete=models.CASCADE) Which map to these seralizers: class ParameterRelationSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = ('id', 'name', 'label', 'required','type','format') class EndPointSerializer(serializers.ModelSerializer): parameters = ParameterRelationSerializer(many = True, read_only=False) class Meta: model = EndPoint fields = ('id', 'name', 'url', 'description', 'parameters') def create(self, validated_data): parameters = validated_data.pop('parameters') endPoint = EndPoint.objects.create(**validated_data) for parameter_relation in parameters: Parameter.objects.create(endpoint=endPoint, **parameter_relation) return endPoint Now, when I try to POST a new endpoint with this data: { "url": "http://the.url.com", "name": "Dummy url", "description":"This is a dummy url", "parameters": [ { "name":"dummyparam", "type":"dummy", "label": "dummy_parameter" } ] } I get a 500 error saying this: IntegrityError at /catalogs/endpoints/ null value in column "required" violates not-null constraint DETAIL: Failing row contains (6, 2017-08-14 12:01:52.857902+00, 2017-08-14 12:01:52.857984+00, dummyparam, dummy_parameter, null, dummy, null, 6). Basically, it is complaining about the not-null 'required' attribute (in the Parameter model) being missing thus causing a DB error. My question is, shouldn't this be handled by the serializer validator instead of throwing a … -
PDFs are being generated without default CSS, but print works
When I try to convert my html to PDF (using wkthmltopdf) it ignores my css code. As the picture shows it work perfectly fine when I print, then it use the css styles. PDF (no css) : PRINT (css works): -
Create model object in django admin using save_model method
I am coming from php background so python-django is totally new to me. I am trying to insert a new record in account_emailaddress table from admin.py using save_model method , whenever a new user is created from admin section. Following are the partial contents from models.py class EmailAddress(models.Model): user = models.OneToOneField(User, unique=True, related_name ='address') email = models.EmailField() verified = models.BooleanField(verbose_name=_('verified'), default=True) primary = models.BooleanField(verbose_name=_('primary'), default=True) class Meta: db_table = 'account_emailaddress' From admin.py from django.contrib import admin from django.contrib.auth import admin as upstream from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group, User from django.utils.translation import ugettext, ugettext_lazy as _ from .models import EmailAddress class CustomUserAdmin(UserAdmin): list_display = ('email', 'first_name', 'last_name', 'is_staff') list_select_related = ( 'profile', ) #exclude = ('username',) fieldsets = ( ('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ('None', { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2')} ), ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) def get_ordering(self, request): return ['-date_joined'] def save_model(self, request, obj, form, change): obj.EmailAddress.save() obj.save() admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) I am getting an error -- 'User' object has no attribute 'EmailAddress' Any help or … -
Including a ModelForm in admin.py from forms.py
I want to add a custom field to admin.py "extra_field" which is defined in YourModelForm class in forms.py forms.py ***class YourModelForm(forms.ModelForm):*** extra_field = forms.CharField() def save(self, commit=True): extra_field = self.cleaned_data.get('extra_field', None) # ...do something with extra_field here... return super(YourModelForm, self).save(commit=commit) class Meta: model = movie fields = '__all__' admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . models import movie, genre from . import forms class movieAdmin(admin.ModelAdmin): form = YourModelForm list_display=('movie_name', 'movie_rating','Date','count',) search_fields=('movie_name',) filter_horizontal=('movie_genres',) list_filter=('Date',) date_hierarchy='Date' ordering=('-movie_name',) fields=('movie_name','movie_rating','movie_genres', 'extra_field',) class genreAdmin(admin.ModelAdmin): list_display=('genre_name',) admin.site.register(movie, movieAdmin) admin.site.register(genre, genreAdmin) NameError: name 'YourModelForm' is not defined -
Django-MarkItUp: Exception while starting tests (AttributeError: 'str' object has no attribute 'raw')
I can't find the solution for an exception when I start my tests which suddenly accured while coding. The website still works fine with runserver. Here is the full traceback: Traceback (most recent call last): File "manage.py", line 10, in <module execute_from_command_line(sys.argv) File "…/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "…/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "…/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "…/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "…/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "…/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "…/lib/python3.5/site-packages/django/test/runner.py", line 549, in run_tests old_config = self.setup_databases() File "…/lib/python3.5/site-packages/django/test/runner.py", line 499, in setup_databases self.parallel, **kwargs File "…/lib/python3.5/site-packages/django/test/runner.py", line 743, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "…/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() File "…/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 122, in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) File "…/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 129, in serialize s.serialize(queryset, **options) File "…/lib/python3.5/site-packages/django/core/serializers/base.py", line 88, in serialize self.handle_field(obj, field) File "…/lib/python3.5/site-packages/django/core/serializers/python.py", line 55, in handle_field self._current[field.name] = field.value_to_string(obj) File "…/lib/python3.5/site-packages/markitup/fields.py", line 103, in value_to_string return value.raw AttributeError: 'str' object has no attribute 'raw' Normally I try to narrow the issue down myself. But in this case I don't get anywhere. I didn't update any packages. These are … -
The foreign key has value, but do not shows up in template
This code is the templates html: <table border="1"> <thead> <tr> <th>1</th> <th>1</th> <th>1</th> <th>1</th> <th>1</th> <th>1</th> </tr> </thead> <tbody> {% for row in hosts %} <tr> <td>{{row.nid}}</td> <td>{{row.hostname}}</td> <td>{{row.ip}}</td> <td>{{row.port}}</td> <td>{{row.bussiness_ip}}</td> <td>{{row.bussiness.caption}}</td> </tr> {% endfor %} </tbody> </table> bussiness_ip is a foreign key of the host table, and in the sqlite3 it has value: But the row.bussiness_ip did not shows up, nor the row.bussiness.ip in the browser: -
django order_by not working on server but works fine on local machine
i have a requests model class Leave(models.Model): from_date = models.DateField(verbose_name='From') to_date = models.DateField(verbose_name='To') leave_type = models.ForeignKey(TotalLeave,verbose_name='Type',null=True) message = models.CharField(max_length=1000,verbose_name='Message to your Manager regarding your leave',null=True) created_by = models.ForeignKey(User,related_name='created_user',null=True) created_datetime = models.DateTimeField(null=True,blank=True) last_modified_by = models.ForeignKey('auth.user',null=True) last_modified_date = models.DateTimeField(default=datetime.now,null=True) emp = models.ForeignKey('Employee',null=True) approval_status = models.BooleanField(default=False,verbose_name='Leaves approved or not ?') view: @login_required def all_requests(request): inner_qs = Employee.objects.filter(email=request.user.email) entries = Employee.objects.filter(reporting_manager__in=inner_qs) if (request.user.is_staff): if request.method == 'POST': month = request.POST.get('month') leaves = Leave.objects.filter(from_date__month=month).order_by('approval_status') else: leaves = Leave.objects.all().order_by('approval_status') else: leaves = Leave.objects.filter(emp__in=entries).order_by('approval_status') from django.db.models.functions import TruncMonth months = Leave.objects.annotate(month=TruncMonth('from_date')).values('month').annotate(c=Count('id')).values('month', 'c') am trying order leaves based on approval status this works fine on localhost but if i pull on server its not working in the sense the order_by not at all working on server am using MYSQL both on server and local machine -
if not rest style, should I use ModelSerializer check user input?
Some situation, we just need to use normal APIView write normal view, and Serializer just check user input, it won't be save as database object. But sometimes, I want to use the convenient of ModelSerializer, for example: class User(models.Model): phone = models.CharField(_("phone number"), max_length=11, unique=True, validators=[ validators.RegexValidator(r'^1[34578]\d{9}$', _("phone format error")) ]) class PhoneCodeSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('phone',) But you know, modelSerializer not only check the phone format, and check unique. But here I just want to use the format validator of phone field, otherwise I have to copy the validator to serializer, I dislike it. Is there any more better way. -
Django loop and accessing the objects and dictionary items in template
So I came across this problem with django templates and I thought the solution might be useful for others: here I will assume a pretty complicated situation so it also can be used in simpler cases: let's assume we need to access a list of articles and their id and title in the template. additionally we want to pass some extra data about each article (like publisher) using a dictionary since they are not in the class attributes. what makes it even harder is when you want to access this articles two by two. meaning a for loop iterating over range of 0 to index of last item and being able to access item number i and i+1 at the same time. this was particularly hard because as you might know if you want to use a dictionary in django template you can't do: {{ publishers[article.id] }} because [] are not supported in the template. no big deal you can treat fields as attributes like {{ publishers.0 }} but django template won't let you do {{ publishers.article.id }} let alone using a for loop and accessing articles through a list and index like : {{ publishers.articles.i.id }} so what do …