Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GenericRelation join columns in view
Tryina to create dynamic content for site pages. My database stores adjacent data for different domains. Some models needs current site domain and subdomain and current language relations. I decide to create ContentType table which stores lang,site,content and content_type relations. Now, when I trying get data from GenericRelation field in templates: {{model.genericrelation.first.field_value}} of course have too much sql queries and loading page 40sec, also I don't have filter by language. So, what I need is just: SELECT a.id,b.name FROM table a LEFT JOIN content_type_table b ON a.id = b.object_id AND b.content_type = 16 AND b.language = current_language AND b.site = current_site how can I join two columns django view with just one query? And have simple code in templates like: {{model.field_value}} Any suggestions? Thx for help. -
How to set a separate proxy for Wagtail to fetch YouTube embed video?
I tried to add a YouTube video in article content, but it alway failed to upload the video link because YouTube is blocked in my country. So I built a HTTP proxy to watch YouTube, how could I tell the wagtail application to use my HTTP proxy while fetching YouTube embed metadata? -
How do I iterate through a ManyToManyField in django-jinja project?
I am trying to create a blog app which has posts and each posts have title, date, link and tags. This is my models.py # models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: ordering = ('name',) class Post(models.Model): title = models.CharField(max_length=300) date = models.DateTimeField() link = models.URLField() tags = models.ManyToManyField(Tag) def __str__(self): return self.title @property def tags_name(self): return [x.name for x in self.tags] class Meta: ordering = ('date',) This is my views.py # views.py from django.conf.urls import url, include from django.views.generic import ListView from blog.models import Post urlpatterns = [ url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date"), template_name="blog/blog_list.html")), ] This is my blog_list.html <!-- blog_list.html --> {% extends "mysite/layout.html" %} {% block content %} <h1>my blog posts</h1> <ul> {% for post in object_list %} <li><span class="title"><a href="{{ post.link }}">{{ post.title }}</a></span></li> <p>{{ post.date|date:"d-m-Y" }}</p> {% endfor %} </ul> {% endblock %} {% block sidebar %} <h4 id="sidenav">tags</h4> {% for post in object_list %} <ul> <!-- I want to show the tags here --> </ul> {% endfor %} {% endblock %} In the blog_list.html, I am showing all the post details and on the sidebar, I want to show all the tags present from all the blog posts … -
django-swift-storage unit tests
I am trying to make tests with django and swift.storage.SwiftStorage as my DEFAULT_FILE_STORAGE. Would like to avoid uploading files into the cloud while testing, rather that make some mock or store files in temporary directory. I checked S3BotoStorage and Unit Testing question, and made a test.py settings with hardcoded MEDIA_ROOT, but not quite sure how can I assing MEDIA_ROOT as a temp directory during test lifetime. Tried something like that in my test_view.py: def setUp(self): self.client = APIClient() self.media_folder = mkdtemp() def tearDown(self): rmtree(self.media_folder) def test_upload(self): data = {'file_location': photo_data} with override_settings(MEDIA_ROOT=self.media_folder): response = self.clien.post(reverse(my_endpont), data) assert response.status_code = status.HTTP_201_CREATED This approach creates me MEDIA directory in my project. Question is, how can I change it's behavior to be temp or how is the best approach to that king of tests? -
How To Peform asynchronous task in django?
I am a bit lost here. I want to send email using django on a post request. But I don't want the user to wait for a reply so I am sending it in a background thread. Also the emails are to be send every 30 seconds in a sequential order provided by the user. But there is a option for the user to cancel sending the emails i.e a different post request to handle the cancel input. How do I listen for cancel operation in the thread sending the email? How do I implement the 30 second delay? I thought of using sleep but if I do that then will it skip the cancel signal? Please Help. -
Makemagrations - django.db.utils.ProgrammingError: column does not exist
I can't understand what is wrong. I can't add new fields to a model, every time I run makemigrations I get this error: django.db.utils.ProgrammingError: column "..." does not exist Yes the column doesn't exist. That is why I want to run a migration. 'ENGINE': 'django.contrib.gis.db.backends.postgis', -
Run view in command
I have a view to download a file. I want to create a command to be able to call this view and download the file in a certain folder. class DownloadFile(View): def get(self, request, pk): ... How can I run this view in a custom command and save the file locally? -
Django-admin linked column issue
Following this answer I wanted to add a linked column to my admin page, class AnswerAdmin(admin.ModelAdmin): list_display = ('__str__', 'link_to_question', 'time_created', 'time_updated', 'created_by', 'down_vote', 'up_vote') def link_to_question(self, obj): link = urlresolvers.reverse("admin:QnA_question_change", args=[obj.question.id]) # model name has to be lowercase text = obj.question.__str__ str = format_html("{}", text) return mark_safe(u'<a href="%s">%s</a>' % (link, str)) class Meta: model = Answer but what I get in return is this: <bound method Entry.__str__ of <Question: This is a question about technology?>> I only want the "This is a question ..." part shown in my admin. Sidenote: when I use something like obj.question.text instead of a function it works smoothly. -
How to use custom field for search in django admin
i have a model and is registered to the admin and i have used custom field to display in the list class ReportsAdmin(admin.ModelAdmin): def investment(self, inst): return models.OrderDetail.objects.filter(user=inst.user).distinct().count() list_display = ['investment'] search_fields = ['investment'] i want to search using the investment field in django admin but always getting Cannot resolve keyword 'investment' into field. choices are the Model fields. is there any way by which i can search using the investment field? -
Urls for updating and viewing extended django profile model
How will the URL for for updating extended user model look like .I have good through the web ,but i have not found hint on URL for updating and viewing of extended django profile models .Please give a hint on how to go about creating a good url for my updating and viewing users information when other users click on their photo or name -
Django Makemessages CommandError ASCII Encoding
the locale/django.po file has 7868 lines. Sometimes the makemessages command works and sometimes it throws this error: Its strange because in the error is always a different line of django.pot mentioned. And don't forget that it sometimes works with the same code, so the code should be fine manage.py makemessages -l de CommandError: errors happened while running msguniq /app/xxx/locale/django.pot:1871: /app/xxx/locale/django.pot: input is not valid in "ASCII" encoding -
forbidden 403 error in 'PUT' request Ajax in django rest framwork
I am using django-rest framework while sending put ajax request got error 403 forbidden. user-details.html <form action="{% url 'user-detail' pk=object.pk %}" id="use1"> {% csrf_token %} {% for key,value in serializer.items %} {{key}} <input value="{{value}}" type="text" class="form-control" /><br> {% endfor %} <button class="btn btn-warning edit_record" type="button" >Update</button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button> </form> when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here. As far as I know we get this error when csrftoken is missing but I have csrf_token in my form. $(".edit_record").on("click",function() { var url = document.location.pathname form = $(this).closest("form")[0], formData = new FormData(form); $.ajax({ type:'PUT', url: url, data: formData, success: function (data) { }, headers: {'X_METHODOVERRIDE': 'PUT'}, }); }); I used ModelViewset in views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserProfileSerializer def update(self, request, *args, **kwargs): import pdb;pdb.set_trace() response = super(UserViewSet, self).update(request, *args, **kwargs) success = True if response.status_code in [200,201] else False return Response({'object':response.data, 'success':success}) def partial_update(self, request, *args, **kwargs): import pdb;pdb.set_trace() def destroy(self, request,*args, **kwargs): response = super(UserViewSet, self).destroy(request, *args, **kwargs) success = True if response.status_code … -
django rest framework RetrieveUpdateAPIView
I come from vietnamese. I want to update User by Django Rest FrameWork. I can update User by 'pk'. But I can't update User by 'username'. I hope that everyone help me. Thank you so much. serializers.py class UserDetailSerializer(serializers.ModelSerializer): url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username') class Meta: model = User fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login') class UserUpdateSerialier(serializers.ModelSerializer): password = serializers.CharField( style={'input_type': 'password'} ) class Meta: model = User fields = ('pk', 'username', 'password') def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.set_password(validated_data.get('password', instance.password)) instance.save() return instance views.py class UserDetailAPIView(generics.RetrieveAPIView): permission_classes = (permissions.IsAdminUser,) serializer_class = UserDetailSerializer #queryset = User.objects.all() lookup_field = 'username' def get_object(self): username = self.kwargs["username"] return get_object_or_404(User, username=username) class UserUpdateAPIView(generics.RetrieveUpdateAPIView): permission_classes = (permissions.IsAdminUser,) #queryset = User.objects.all() serializer_class = UserUpdateSerialier def get_object(self): username = self.kwargs["username"] return get_object_or_404(User, username=username) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) urls.py url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'), url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'), url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'), HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } -
Django-paypal Heroku VS Local ? PAYPAL IPN
In my development locally the django-paypal plugin is amazing and have had ZERO issues attempting paypal and the developer account. After pushing to heroku, i cant seem to contact the paypal server doing the exact same steps.... for example when in local development i am getting the Payment Accepted and the IPN to return to my localhost with ngrok. once i pushed the app to heroku everything loaded and it was looking good, my problem is not i am getting a 500 error from paypal when attempting to connect to the sandbox in from heroku?? Please help, Ryan -
django 405 method not allowed
The error occurs when I request via post method. views.py class ConceptForkView(ConceptBaseView, mixins.CreateModelMixin): print 'oclapi ConceptForkView111' def dispatch(self, request, *args, **kwargs): print 'oclapi ConceptForkView dispatch' return super(ConceptForkView, self).dispatch(request, *args, **kwargs) def post(self, request): print 'oclapi ConceptForkView post' urls.py url(r'^forking/$', ConceptForkView.as_view(), name='concept-forking'), ConceptBaseView class ConceptBaseView(ChildResourceMixin): lookup_field = 'concept' pk_field = 'mnemonic' model = Concept permission_classes = (CanViewParentDictionary,) child_list_attribute = 'concepts' The command print 'oclapi ConceptForkView111' can run, but the method dispatch and post don't run. What is the reason? I have searched many solutions, but they don't work to me. How can I solve this problem? Thank you. -
override delete_selected to check for records that exist in other tables in django 1.10
I am using the default admin dashboard of django. Basically, i want to override the delete_selected method on a model by model basis so I can check for records before allowing the deletion to take place. My models.py is: class Kind(models.Model): name=models.CharField(max_length=50, unique=True) addedby=models.ForeignKey(User,related_name='admin_kind') createdon=models.DateTimeField(auto_now_add=True) updatedon=models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering=('name',) class Item(models.Model): name=models.CharField(max_length=50) kind=models.ForeignKey(Kind,related_name="item_kind") createdon=models.DateTimeField(auto_now_add=True) updatedon=models.DateTimeField(auto_now=True) def __str__(self): return ' , '.join([self.kind.name,self.name]) class Meta: ordering=('kind','name',) unique_together=(('name','kind')) Now what I want is before a kind could be deleted, I want to check if there is a related record in items. If there is, dont delete it. But i am stuck at how to go about overriding delete_selected method in admin.py. def delete_selected(self, request, obj): ''' Delete Kind only if there are no items under it. ''' for o in obj.all(): featuredItems =Item.objects.filter(kind=o).count() if featuredItems==0: o.delete() However, django shows the warning and when i click yes, it deletes the kind even though there are records for it. I want to absolutely block the deletion. -
Providing initial data django unit test
I working on a Django application which have a lot of unit tests. Some of those test functionalities on unmanaged models (Manage = False). In order to test them, there are in setUpClass the execution of some sql files. Now, after upgrading at Django 1.11.2, some warnings are raised during the execution of sql files. The warning is the following: Warning: Unknown table '<table name>' return self.cursor.execute(query, args) I searched the reason of this warning and seems it is linked to the sql file that check if the table exists before create or drop it. I would remove this warnings, and to do this, I thought of drop the table in tearDownClass, in order to remove the IF EXISTS statements in sql files. I think that this approach makes unit tests slower and I don't know if it is a best practice. Furthermore, I found in Django documentation that is possible use fixtures to providing initial data. Since documentation is not very clear (from my point of view) on how use fixtures in unit tests, I'm asking this question to understand how is the best practice/approach to solve this problem. Thanks in advance -
Django i have many problems with get_absolute_url
First problem: When i create new post i see this message (Reverse for 'details' with keyword arguments '{'pk': 1, 'slug': ''}' not found. 1 pattern(s) tried: (['post/(?P<pk>\\d+)(?:/(?P<slug>[\\w\\d-]+))?/$']) Secound problem: When i call get_absolute_url in readmore botton i see this message ('PostCreate' object has no attribute 'get_absolute_url') tow days i try to fix this problem I tried all the solutions but im failed here is my code views.py class PostCreate(CreateView): model = Post template_name = "posts/create.html" query_pk_and_slug = True fields = ['title','body','category'] def form_valid(self, form): form = form.save(commit=False) form.user = self.request.user return super(PostCreate, self).form_valid(form) def get_success_url(self): return self.get_absolute_url models.py class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True, default="") def __str__(self): return self.name class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False, default="") body = models.TextField(max_length=1000,blank=False, null=False, default="") category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(blank=True,default="-",unique=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self,): return reverse('post:details', kwargs={'pk': self.id, 'slug': self.slug}) urls.py from django.conf.urls import url from .views import (PostList, PostDetail, PostCreate, PostUpdate, ArticleDetailRedirect) from django.urls import reverse urlpatterns = [ url(r'^$', PostList.as_view(), name="index"), url(r'^create/$', PostCreate.as_view(), name="create" ), url(r'^(?P<pk>[0-9]+)/update/$', PostUpdate.as_view(), ), url(r'^(?P<pk>\d+)/$', PostDetail.as_view()), url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', PostDetail.as_view(), name = 'details'), url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', ArticleDetailRedirect.as_view(), name = 'article_details'), index.html <a href="{{ list.get_absolute_url … -
how to write the search function to search the file name only?
I have a folder which name company, and inside the company folder I got 3 folders which is c1,c2,c3 and inside c1 I have 2 folder which name c1.1 and c1,2. Now I want to search the company folder and my output only want the 3 folder which is c1, c2 and c2 and this 3 folder name will be store in an array without store the c1.1 and c1.2. Anyone can share me idea? Thanks -
django.core.exceptions.ValidationError: [u"'' value has an invalid
models.py # -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class moption(models.Model): pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True) when I command"python manage.py migrate" Operations to perform: Apply all migrations: Price, admin, auth, contenttypes, sessions Running migrations: Applying Price.0006_moption_pub_date...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql default_value = self.effective_default(field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default default = field.get_db_prep_save(default, self.connection) File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py", line 755, in get_db_prep_save prepared=False) File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py", line 1440, in get_db_prep_value … -
Can't run crontask in django project
I have django problem and I have problem with run the .sh file on server but not on local machine. My .sh file: #!/bin/bash source $HOME/.profile cd /home/myproject/test source venv/bin/activate cd www python manage.py make_import I want to run this .sh file and run import with this line in crontab (Ubuntu): 10 8 * * * /home/myproject/test/www/crontab/test/make_import.sh But this isn't working. When I do this on my local computer via python manage.py make_import everything is fine. Thanks for any hint. -
Preventing django object using daylight time saving
I have datetime variable and I have changed its timezone from UTC to any other time_zone. Time_zone has been changed correctly but daylight saving is applied while changing timezone on date_time. How can I prevent daylight not to apply on date_time. from_time_zone = tz.gettz('UTC') to_time_zone = tz.gettz(str(tzinfo)) date_time = 2016-11-17 03:00:00+05 date_time = date_time.replace(tzinfo=from_zone).astimezone(to_zone) -
How to send wav file recorded from microphone to django?
I'm using RecordRTC.js to record from microphone and to convert into a wav file. I want to send the wav file to django, through ajax. HTML page: {% extends 'base.html' %} {% block content %} <body> <div style="display: block; margin-top: 10%; margin-left:25%; margin-right:25%"> <form id="non_default" action="/demo/" class="form-group" enctype="multipart/form-data" method="post" name="fileinfo">{% csrf_token %} <button id="btn-start-recording">Start Recording</button> <button id="btn-stop-recording" disabled>Stop Recording</button> <input type="file" id="storage" value="" name=value accept="audio/*"> <input type="submit" > <audio controls autoplay></audio> </form> </div> <script> var form = document.forms.namedItem("fileinfo"); form.addEventListener('submit', function(ev) { var oOutput = document.querySelector("audio"), oData = new FormData(form); oData.append(); var oReq = new XMLHttpRequest(); oReq.open("POST", "/demo/", true); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!"; } else { oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>"; } }; oReq.send(oData); ev.preventDefault(); }, false); var audio = document.querySelector('audio'); function captureMicrophone(callback) { navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia; navigator.getUserMedia({audio: true}, callback, function(error) { alert('Unable to access your microphone.'); console.error(error); }); } function stopRecordingCallback() { var blob = recorder.getBlob(); audio.src = URL.createObjectURL(blob); console.log(audio.src) recorder.microphone.stop(); //document.getElementById('non_default').submit() var fileType = 'audio'; // or "audio" var fileName = 'ABCDEF.wav'; // or "wav" var formData = new FormData(); formData.append(fileType + '-filename', fileName); formData.append(fileType + … -
Can't run django tests by tag
I have problem because I wanted to tag some test in django but when I type in console from django.test import tag, TestCase @tag('fast', 'something') class SomeTestCase(TestCase): def setUp(self): # do something def test_something(self): # do something when I type in console: ./manage.py test --tag=fast -k I got: Using existing test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Preserving test database for alias 'default'... -
HTTP/1.1" 200 0 Blank Screen on template - Django
i am trying to fix this problem with my code. admin is working but my template is not showing anything and i mean the file is not empty. there's no error occured but in my terminal it says: HTTP/1.1" 200 0 template: landingpage.html <div class="col-md-5 pull-right"> <div class="col-md-offset-2 col-md-offset-8 col-md-offset-2"> <form class="form-horizontal contact_form" method="POST">{% csrf_token %} <p class="form_message"> <span>LEARN MORE ABOUT THE BUSINESS</span><br/> <span>BY SIGNING IN</span> </p> <div class="form_fields form_space"> {% crispy form %} </div> </form> </div> </div> views.py def landingpage(request, subdomain=None): form = ProspectForm(request.POST or None) if form.is_valid(): query = Prospect() form.save(commit=False) form.full_name = form.cleaned_data.get("full_name") form.email = form.cleaned_data.get("email") form.contact_number = form.cleaned_data.get("contact_number") webdetail = WebDetail.objects.get(domain=subdomain) vendicsuser = VendicsUser.objects.get(webdetail=webdetail) query.full_name = form.full_name query.email = form.email query.contact_number = form.contact_number query.user = vendicsuser # query.ip_address = get_client_ip(request) query.save() redirect('/' + subdomain + '') else: return HttpResponse('Error, form is not valid' + request) context = { 'subdomain': subdomain, 'form': form, } user = get_object_or_404(WebDetail, domain=subdomain) return render(request, "landingpage/landingpage.html", context) forms.py class ProspectForm(forms.ModelForm): full_name = forms.CharField( label="Full Name", max_length=120, required=False, ) email = forms.EmailField( label="E-mail", max_length=120, required=False, ) contact_number = forms.CharField( label="Contact Number", max_length=14, required=False, ) def clean_email(self): email = self.cleaned_data.get('email') try: Prospect.objects.get(email=email) raise forms.ValidationError('This email is taken') except Prospect.DoesNotExist: return email def clean_number(self): number …