Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update form not work after using custom clean method
My model form: class MemberForm(ModelForm): birth_date = forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y")) class Meta: model = Person exclude =('user',) def clean(self): user = get_user(self.request) name = self.cleaned_data.get('name') birth_date = self.cleaned_data.get('birth_date') if Person.objects.filter(user=user).exists(): self.add_error('name', "You already submitted data") elif Person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "Person with this Name and Birth date already exists.") return self.cleaned_data def save(self, commit=True): person = super().save(commit=False) if not person.pk: person.user = get_user(self.request) if commit: person.save() self.save_m2m() return person my views: class PersonCreate(CreateView): template_name = 'member/person_form.html' model = Person success_url = '/person/' form_class = MemberForm def get_form(self, form_class=None): form = super().get_form(form_class) form.request = self.request return form class PersonUpdate(UpdateView): template_name = 'member/person_form.html' model = Person success_url = '/person/' form_class = MemberForm My MemberForm worked fine when I create a person. It also give validation errors in the form when user is not unique and user name and birth date are combinedly not unique. But when I tried to update the saved form it gives error and say: "'MemberForm' object has no attribute 'request'" If I use def get_form(self, form_class=None): form = super().get_form(form_class) form.request = self.request return form in UpdateView it raises my custom validation errors like CreateForm. Since the same person already in the database. Could anyone suggest me the way how do I … -
How to make a many-to-many relationship act like a foreign key relationship?
I am trying to get a TabularInline working with a many-to-many relationship, but I can only get the relationship object to display. It works fine if I use a foreign key relationship. So let's say this is my many-to-many relationship: # Jobs have many workers, and workers can be assigned to many jobs class Job(models.Model): workers = models.ManyToManyField(Worker, related_name='jobs') class Worker(models.Model): name = models.CharField(max_length=255) # workers relationships with other models insurance = models.ForeignKey(Insurance, null=True, blank=True, default=None) location = models.ForeignKey(Location, null=True, blank=True, default=None) This doesn't play nicely with a TabularInline as it will only display the Job_Worker object. So I'm wondering is there some way to make the relationship seem like a foreign key relationship? For example, worker gets a foreign key to an intermediate table, and "through" is used. The end result being it "works out of the box" for a TabularInline. Thank you. -
How do upload an Image to django from angularjs client using django rest framework?
I can't figure out how I should post an Image from angularjs. I'm a newbie in django and django-rest-framework. Thanks in advance. models.py class UserImages(models.Model): owner = models.ForeignKey('auth.User', related_name='UserImages') user=models.ForeignKey(Profile) # highlighted = models.TextField(default=None,blank=True,null=True) likes=JSONField(null=True,blank=True) image=models.ImageField() pub_date=models.DateTimeField(default=now) def __str__(self): return str(self.owner) serializers.py class ImageSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='user.username') image_url = serializers.SerializerMethodField('gett_image_url') class Meta: model=UserImages fields=('id','owner','image','likes','image','image_url','owner') def gett_image_url(self,obj): return obj.image.url I can't figure out how i should design the view, I read something about FileUploadParser but its going way over my head a code snippet of the view would be nice. Thank you. -
python - how exactly does django validates its cookie?
Excuse me if this is a newbie question. I was reading up on cookie validation and came across with the question of how exactly does Django validates its cookie? If I remember correctly, Django stores session id in the cookie for later use. Does that mean that anyone who fakes the cookie will be able to use arbitrary session data? -
Unique_together and OneToOne field constraints error catching in django form
I have a model: class Person(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') birth_date = models.DateField(null=True, blank=True) blood_group = models.CharField(max_length=5) present_address = models.CharField(max_length=250, blank=True) permanent_address = models.CharField(max_length=250, blank=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='member_persons') class Meta: ordering = ['name'] unique_together = ['name', 'birth_date'] You see above model has two constraints: one is unique user and another is unique_together with name and birth_date fields. I want to when I submit create form it simultaneously check both unique user as well as same name and birth date people can't submit this form. When it happens it should show appropriate errors in the form fields. With the help of other thread of SO so far I write my clean method as follows: def clean(self): user = get_user(self.request) name = self.cleaned_data.get('name') birth_date = self.cleaned_data.get('birth_date') if Person.objects.filter(user=user).exists(): self.add_error('name', "You already submitted data") elif Person.objects.filter(name=name, birth_date=birth_date).exists(): self.add_error('name', "This name and birth date already exists") return self.cleaned_data It worked fine and responding both of my field constraints. My question is does my method is efficient? If not could anyone suggest better method to do that. I am using class-based view. -
Can't set expire header on images with Apache
I am trying to tell browsers to cache any type of image files (png/jpg/gif/etc) from my application, by setting up an .htaccess file in the root of my Django application. .htaccess <IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 seconds" ExpiresByType image/gif "access plus 365 days" ExpiresByType image/jpeg "access plus 365 days" ExpiresByType image/png "access plus 365 days" </IfModule> Apache LoadModule authz_core_module modules/mod_authz_core.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule wsgi_module modules/mod_wsgi.so LoadModule unixd_module modules/mod_unixd.so LoadModule expires_module modules/mod_expires.so LoadModule headers_module modules/mod_headers.so <Directory />s AllowOverride All </Directory> LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /home/timbaney1989/logs/user/access_baneydev.log combined ErrorLog /home/timbaney1989/logs/user/error_baneydev.log Before adding the AllowOverride All option, I was getting an internal server error, but now my app is running fine. When I check the network however and see images being loaded, I don't see the expire header anywhere on that image. Also the server says it is Nginx ? Is this a normal thing to be running your application on an Apache serve, and have an Nginx server loading your static files ? Is there somewhere in my Django application or Apache httpd.conf file that I … -
Django just sort ListView by date
I'm dealing with some Django code I inherited from a dev and need to make a very simple change urgently. In the code, there is a list of jobs displayed through a Django ListView. My problem is really simple. When I go to the page, I see the jobs sorted by date with earliest one first. I want to sort the jobs in the opposite order. I don't need any filtering, passing parameters in the URL, etc for now. Here are the relevant parts of the files - #models.py from django.db import models class Job(models.Model): created = models.DateTimeField(auto_now_add=True) position = models.ManyToManyField(Position) title = models.CharField(max_length=100) #views.py from .models import Job class JobListView(ListView): template_name="jobs/list.html" model = Job paginate_by = 10 #list.html {% for job in object_list %} <li class="display-list-item"> <h4><strong><a href="{% url 'job_detail' pk=job.pk %}">{{job.title}}</a></strong></h4> <ul class="list-inline job-info-list"> <span>{{job.created | timesince}} ago</span> </ul> </li> {% endfor %} #urls.py urlpatterns = [ url('^$', views.JobListView.as_view(), name='job_list') ] As mentioned, this causes the jobs to be displayed sorted by 'created' field. The ones created earlier are displayed first. What is the quickest way to make the ones created later display first? -
Can't seem to leverage browser caching for site optimization
I am trying to increase the load speed of my Django app by using Google page-speed insights, but can't seem to get past their recommendation to leverage browser caching by caching my site images. I have set Cache-Control to a week long age, and Expire headers on the response object that comes from the home page request. Does setting Cache-Control and Expire automatically cache everything static (js, css, images), or is it something you have to set automatically ? Im being told I haven't set an expiration date, but I know I have because I am logging the response headers to the console, and can see it is there. Is there something I am missing ? View where I am setting the response def view_home(request): expiry_date = datetime.datetime.now() + datetime.timedelta(days=7) response = render(request, "index.html", {}) response['Cache-Control'] = 'max-age=602000' response['Expires'] = expiry_date return response -
Django template with 2 'inputs'
I have this simple Django view, where I can (correctly) get map coordinates (lat, lng) from the URL, and wish to pass them onto a template named 'test.html'. Right now I just pass the latitude along: #views.py ... def testview(request, lat, lng): return render(request, 'polls/test.html', {'lat':lat}) And it works fine. My issue is how to also pass the longitude (lng) along. I have learned how to pass a solo input from the official Django documentation, but can't find any mention on how to do it for multiple inputs. -
how to incorporate parallel python with django
I was wondering if there is a way to incorporate pp (Parallel Python) with django. This would be great because I have multiple computers and I want to use them to better handle the requests. -
IE will not open my website instead trying to download it
Chrome, Safari, and Firefox all display my website normally. Yet, it seems that IE does not see my website as an HTML file and instead asks to download it when I input the URL. When I select open it downloads the file and asks which program to open it as. When I select IE it displays like a normal webpage. If there is any code that would help answer this question I am happy to share, but I am not sure where to even begin. I am on a AWS/Ubuntu/Django stack. -
Create identical model in django
I am using django 1.10 with mysql db. I am willing to have two tables in my db with the same fields. What is the best way to do it in django? -
Where to store model information django?
In my Django project I need to access constantly the object of the user`s character, where should I store the value of this object ? since I will be using it in multiple views to display content in the template. Should I store in the session, retrieve from the database every time or some other alternative? -
Customize non form errors with django crispy form
I would like to customize the way django crispy shows the non form error. I know how to change the text, but I don't know where to change the css. This is the image: My login area forms.py class LoginForm(forms.Form): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') username = forms.CharField(label='', required=True, widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) name = forms.CharField(label='', required=True , validators=[alphanumeric], widget=forms.TextInput(attrs={'placeholder': 'Name'})) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user or not user.is_active: raise forms.ValidationError('Invalid Login : I want to change this CSS') return self.cleaned_data def login(self, request): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) return user template - html <form method="POST" action="">{% csrf_token %} <!--{% if form.non_field_errors %} testing {% endif %}--> {{form|crispy}} <div class="form-info"> <label class="hvr-sweep-to-right"> <input class="create btn" type="submit" value="Submit"> </label> </div> </form> -
Installing django-userena: userena.compat.SiteProfileNotAvailable when trying to create accounts app
Running Django 1.9 I'm trying to follow the install instructions for django-userena, to add it to an existing django project. When I try to create the Accounts app: python manage.py startapp accounts I get this error: userena.compat.SiteProfileNotAvailable Other questions indicate that I need to set AUTH_PROFILE_MODULE, as directed in the installation instructions. However, these assume I already have an Accounts app created, within which I've created a Profile model. So I seem like I'm stuck in a circular dependancy where I can't create the Accounts app without a Profile model, but I can't create the Profile model without the Accounts app! Also, from the instructions, it doesn't appear the AUTH_PROFILE_MODULE should be required yet at this step, in order to create the Accounts app. How do I solve this? -
Why does CMD never work in my Dockerfiles?
I have a few Dockerfiles where CMD doesn't seem to run. Here is an example (all the way at the bottom). ########################################################## # Set the base image to Ansible FROM ubuntu:16.10 # Install Ansible, Python and Related Deps # RUN apt-get -y update && \ apt-get install -y python-yaml python-jinja2 python-httplib2 python-keyczar python-paramiko python-setuptools python-pkg-resources git python-pip RUN mkdir /etc/ansible/ RUN echo '[local]\nlocalhost\n' > /etc/ansible/hosts RUN mkdir /opt/ansible/ RUN git clone http://github.com/ansible/ansible.git /opt/ansible/ansible WORKDIR /opt/ansible/ansible RUN git submodule update --init ENV PATH /opt/ansible/ansible/bin:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin ENV PYTHONPATH /opt/ansible/ansible/lib ENV ANSIBLE_LIBRARY /opt/ansible/ansible/library RUN apt-get update -y RUN apt-get install python -y RUN apt-get install python-dev -y RUN apt-get install python-setuptools -y RUN apt-get install python-pip RUN mkdir /ansible/ WORKDIR /ansible COPY ./ansible ./ WORKDIR / RUN ansible-playbook -c local ansible/playbooks/installdjango.yml ENV PROJECTNAME testwebsite ################## SETUP DIRECTORY STRUCTURE ###################### WORKDIR /home CMD ["django-admin" "startproject" "$PROJECTNAME"] EXPOSE 8000 If I build and run the container, I can manually run Django-admin startproject $PROJECTNAME and it will create a new project as expected, but the CMD in my Dockerfile does not seem to be doing anything and this is happening with all my other Dockerfiles so there's something I must not be getting. -
Heroku not running collectstatic with Django
So I have a Django app, I've turn off DISABLE_COLLECTSTATIC but there's no mention of collect static happening. Some research showed that Heroku would fail silently if collect static fail, but would write out during the build log when collect static succeeds. I did heroku run python manage.py collectstatic and it ran correctly. No errors. However, collect static still isn't running on build -
How can I curl 127.0.0.1/8000 while django development server is running?
I have never ran into this before because I can always just run the dev server, open up a new tab in terminal and curl from there. I can't do this now because I am running the Django Development server from a Docker container and so if I open a new tab, I will be in the local shell and not the docker container. How can I leave the development server running and still be able to curl or run other commands? When I run the development server I'm left with this message: Django version 1.10.3, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. and so unable to type any commands. -
Django Rest Docs Show Wrong Urls
I'm using the Django Rest Docs to describe my API built in the Django Rest Framework, but the urls it's displaying are incorrect. Specifically, they prepend /admin/ to everything: These paths should be /session-auth/, /session/, etc. I don't know why the /admin/ is being preprended. Here's my urls.py file: # URLs for serving static media and user uploaded media urlpatterns = patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_URL, 'show_indexes': True}), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += patterns('myapp.views', #Home page (r'^$', 'home'), url(r'^docs/', include('rest_framework_docs.urls')), # Refresh all locations (r'^admin/refresh-all-locations/$', 'refresh_all_locations'), # Admin all locations page (r'^admin/all-locations/$', admin.site.admin_view(all_locations)), # Admin (r'^admin/', include(admin.site.urls)), ####API urls#### # Authenticate a user url(r'^session-auth/$', API.Session.SessionAuth.as_view(), name='authenticate'), # Update user password or email url(r'^session/$', API.Session.SessionDetail.as_view()), # Get the detail on one entity url(r'^entities/(?P<entity_id>[0-9]+)/$', API.Entity.EntityDetail.as_view()), -
Django many to many relations
I currently have three models, but I'm not really sure how to design this the best. One is the Song model, one is the Artist and finally the Show model class Artist(models.Model): name = models.CharField(max_length=255) label = models.CharField(max_length=255, null=True) def __str__(self): return self.name class Show(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Song(models.Model): title = models.CharField(max_length=255) artist = models.ManyToManyField('Artist') show = models.ManyToManyField('Show') duration = models.FloatField() def __str__(self): return '%s - %s (%s)' % (self.title, [artist.name for artist in self.artist.all()], self.duration) The things I wasn't sure about are the relations. A artist has songs, but a song can also have multiple artists, and a show can (or always has) multiple songs. What would be the right design here with the ManyToMany fields? -
django-admin error with decoding
I have a problem with " django-admin startproject mysite . " command. When I try to execute it, Cygwin returns me an error: Traceback (most recent call last): File "/usr/bin/django-admin", line 9, in load_entry_point('Django==1.10.2', 'console_scripts', 'django-admin')() File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/commands/startproject.py", line 34, in handle super(Command, self).handle('project', project_name, target, **options) File "/usr/lib/python2.7/site-packages/Django-1.10.2-py2.7.egg/django/core/management/templates.py", line 164, in handle if new_path.endswith(extensions) or filename in extra_files: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 22: ordinal not in range(128) I am running this command in Cygwin 6.3 Python version: 3.5.2 Django version: 1.10.2 Maybe it's important: I had a serious issue with django-admin.py file (django installer didn't install it) but I found a following content of that file and maybe it's incorrect? #!/usr/bin/env python from django.core import management if __name__ == "__main__": management.execute_from_command_line() I was reading about that problem in Python 2.x but not in 3.x and I can't find the answer. Please, somebody help me with that. -
How to delete a certain model instance in django after a given date
class Mess(models.Model): muser = models.OneToOneField(User) MESS_NAME = (('GH','girls hostel top mess'), ('IH','girls hostel down mess'), ('MM','Mega mess'), ('FB','First Block mess'), ('SB','Second Block mess'), ('TB','Third Block mess'), ) mess_name = models.CharField(max_length=25, choices =MESS_NAME,primary_key=True) per_day_cost = models.IntegerField() def __str__(self): return self.mess_name class MessMenu(models.Model): mess_name = models.ForeignKey(Mess) day = models.DateField() morning = models.TextField() afternoon = models.TextField() snacks = models.TextField() dinner = models.TextField() def __str__(self): return self.mess_name Once i create an object in MessMenu I want django to delete that object after 7 days. Please let me know how to delete a certain object after a given period of time. -
Adding an object attribute value to an array Django
I am new to Django and this is my first project using it. I have run into an issue I don't understand and (perhaps I'm not using the right search terms) I'm not finding any relevant results in searching for solutions. I was trying to get an array of distinct entries in the 'topic' field of my model. I was playing about in the shell, trying to figure this out when I got the following result which I didn't expect. This is what I entered in the shell: >>> from pomodoro.models import Chunk, Result >>> Chunk.objects.all() <QuerySet [<Chunk: Onboard State Estimation>, <Chunk: Newton's 2nd Law of Motion>, <Chunk: IF>]> >>> a = [] >>> for q in Chunk.objects.all(): a += q.topic ... >>> a ['R', 'o', 'b', 'o', 't', 'i', 'c', 's', 'M', 'e', 'c', 'h', 'a', 'n', 'i', 'c', 's', 'L', 'o', 'g', 'i', 'c'] >>> ose = Chunk.objects.get(pk=1) >>> ose.topic 'Robotics' I don't understand why I ended up with an array of individual letters rather than an array of the 'topic' strings. Can someone explain why this happened? I'm also aware that there are much better ways of doing what I'm trying to do but, as a beginner, … -
Linux Only 'ascii' codec can't encode character u'\u0161' in position 3: ordinal not in range(128)
I encountered an error, which only happens on linux server with apache2 running wsgi on django. I do development in Windows then I copy it over to Linux server. I see the problem is in the string: (Bold part is marked by Django) Društvo tabornikov - Rod Srnjak Logatec But this error happens only on one page. The same string is also used on settings page but it displays properly. Also same error pops on the admin page. In the views.py file I have already set the utf-8 encoding. The error doesn't happen if I start server without apache with: python3 manage.py runserver 0.0.0.0:8000 Trace: Environment: Request Method: GET Request URL: https://***.***.**/vodnik/eposta/?cid=17 Django Version: 1.10.3 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vodnik', 'schedule', 'djangobower'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /var/www/etaborniki/templates/vodnik/eposta.html, error at line 59 ascii 49 : <small style="text-align: justify"><strong>Opomba:</strong> Na dno sporočila bodo avtomatsko dodani podatki roda in 50 : obrazložitev namena 51 : sporočila, ker je naša aplikacija skladna z zakonom <a href="https://www.uradni-list.si/1/content?id=111442">ZEKom-1</a>. 52 : </small> 53 : <br/> 54 : <small style="text-align: justify"><strong>Soglasje:</strong> S pritiskom na gumb pošlji se z navedenim popolnoma 55 … -
Django Rest queryset inside APIview
I have two serializers for two models but I want to combine those two serializers into one view class ProductRequestView(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get(self, request): cat_serializer = CategoryCompactSerializer models = ModelsNestedSerializer data = {'cities':{'city data'}, 'models': {'models data'}} return Response(data, status=HTTP_200_OK) I think I have to pass queryset to both serializers to get the data. How can I do it inside this view. I am new to DRF. Help ? Thanks