Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize folder name when compilemessages in website insternationalization
For website Internationalization when run this command django-admin compilemessages -l de it produce the .po file under the locale folder like locale/de/LC_MESSAGES/django.po I want to rename LC_MESSAGES How can I do this ??? Please help me -
A best practice referring to if and else condition
I am following the Django project in book "Python Crash Course", In "views.py", the author defines a 'new_topic' def new_topic(request): """Add a new topic""" if request.method != "POST": # No data submitted, create a blank form. form = TopicForm() else: # Post data submitted, process data. form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form':form} return render(request, 'learning_logs/new_topic.html', context) I think it's more readable and clean if refactored as: def new_topic(request): """Add a new topic""" if request.method != "POST": # No data submitted, create a blank form. form = TopicForm() context = {'form':form} return render(request, 'learning_logs/new_topic.html', context) else: # Post data submitted, process data. form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) It works. I wonder if the author's the style is a best practice I should follow? What's kind of guidelines he follows? -
Set the primary_key after overriding the save() method in Django
I have the following model in which one the fields is based on other fields (similar to this): from django.db import models class Model_Model01(models.Model): code_01 = models.CharField(max_length = 2, null = False, blank = False) code_02 = models.CharField(max_length = 3, null = False, blank = False) code_combined = models.CharField(max_length = 5, null = True, blank = False, primary_key = False) def save(self, *args, **kwargs): self.code_combined = "{}{}".format(self.code_01, self.code_02) super(Model_Model01, self).save(*args, **kwargs) def __unicode__(self): return self.code_combined I would like to set the primary_key of code_combined field as True after overriding the save method. Is there a way to do this? -
Django filter queryset list a match list b
I have the following models: class Skill(models.Model): name = models.CharField(max_length=100, default="") class Permit(models.Model): name = models.CharField(max_length=50) skill_course = models.ManyToManyField( Skill, related_name="+", blank=True, ) class Course(models.Model): name = models.CharField(max_length=50) skills = models.ManyToManyField( Skill, related_name="courses",blank=True, ) In a view I have a list with active filters called skills. course = Course.objects.filter(students=self.request.user, date__lt=datetime.datetime.today()) skills = list(Skill.objects.filter(courses__in=course).distinct()) I want to filter Permit objects which have all skills present in courses. I tried: queryset = Permit.objects.filter(skill_course__in=skills) But this matches any item in skills, not all skills. For example: permit_a = [A, B, C, D] user.skill_a = [B, C, F] what I wanted is ONLY IF user.skill_a = [A, B, C, D], then that user get permit_a, but now is fuzzy matching, not exact matching. Really appreciate for any help, thanks so much in advance. -
django 2.0 force download downloading blank files
the code below seems to work for python 3.6 and django version 2.0, the problem is that after the download, the downloaded files are blank. here is the code: class ProductDownloadView(MultiSlugMixin, DetailView): model = Product def get(self, request, *args, **kwargs): obj = self.get_object() filepath = os.path.join(settings.PROTECTED_ROOT, obj.media.path) print(filepath) guessed_type = guess_type(filepath)[0] wrapper = FileWrapper(open(filepath, encoding='latin-1')) mimetype = 'application/force-download' if guessed_type: mimetype = guessed_type response = HttpResponse(wrapper, content_type=mimetype) if request.GET.get("preview"): response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(obj.media.name) response['X-Sendfile'] = smart_str(obj.media.name) return response -
Error when attempting loaddata on django database dump
I started a new Django project, the database I had before was still relevant so I want to merge it over to the new one using dumpdata & loaddata. I am using the out of the box database django comes with: sqllite. The problem is when I use loaddata I get this error: "bad_row[1], referenced_table_name, referenced_column_name, django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'django_admin_log' with primary key '1' has an invalid foreign key: django_admin_log.content_type_id contains a value '7' that does not have a corresponding value in django_content_type.id." The steps I followed to get here are: Copied and migrated the models page from my first project to my new one. python3 manage.py dumpdata admin > db.json --indent 2 python3 manage.py loaddata db.json tldr; My goal is to take the data from the old database in another project and put it in the new project's database. -
Django How to paginate a list of dicts
I have this function where I get data from the Stackoverflow Api as you can see below and I display them in an html table. Is there a way to have pagination for this list of dicts so that 10 results appear on each page? views.py: def get_questions(request): context = {} url = 'https://api.stackexchange.com/2.2/questions' params = { 'fromdate':'1525858177', 'todate':'1525904006', 'order':'desc', 'sort':'activity', 'tagged':'python', 'site':'stackoverflow' } r = requests.get(url, params=params).json() dataList = [] for item in r['items']: dataList.append({ 'owner': item['owner']['display_name'], 'title': item['title'], 'creation_date': datetime.datetime.fromtimestamp(float(item['creation_date'])), 'is_answered': item['is_answered'], # (yes / no) 'view_count': item['view_count'], 'score':item['score'], 'link':item['link'], 'answer_count':item['answer_count'] }) template = 'questions/questions_list.html' context['data'] = dataList return render(request,template,context) questions_list.html: <table id="myTable" class="table table-hover"> <thead> <tr> <th scope="col">Owner</th> <th scope="col">Title</th> <th scope="col">Creation date</th> <th scope="col">Is answered</th> <th scope="col">View count</th> <th scope="col">Score</th> </tr> </thead> <tbody> {% for d in data %} <tr> <td>{{ d.owner }}</td> <td><a href="{{ d.link }}" target="blank">{{ d.title }}</a></td> <td>{{ d.creation_date }}</td> <td>{{ d.is_answered|yesno:"yes,no" }}</td> <td>{{ d.view_count }}</td> <td>{{ d.score }}</td> </tr> {% endfor %} </tbody> </table> -
Combine the fields definations through "import *"
Combine the fields definations through "import *" There are definitions of field in /models and /forms django/db/init.py __all__ = [ 'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField', 'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField', 'DateField', 'DateTimeField', 'DecimalField', 'DurationField', ... ] django/fields.py at master · django/django __all__ = ( 'Field', 'CharField', 'IntegerField', 'DateField', 'TimeField', 'DateTimeField', 'DurationField', 'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField', 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField', ... ) I wonder if it's possible to combine the fields definations through "import *", What's the instinct difference between them ? -
Django URLs - make 'cleaner'?
Hi I have a django application, and I was wondering if there was a better way to display my URLS after submitting a GET request. urlpatterns = [ ... re_path(r'^reporting/$', ReportView.as_view(), name='report'), ] When I got to localhost:8000/reporting which displays a form, and click on a radio button and submit, it takes me to: http://localhost:8000/reporting/?run=2&submit=Search+for+run I would prefer it if it was something like: http://localhost:8000/reporting/run=2/ because this page displays another form, which I would like to 'add on' to this: http://localhost:8000/reporting/run=2/choice=primary/ Is this possible - would I have to have several different URLS relating to different views? -
django with gunicorn persistent database connection not reused
Recently I have encounter an issue about django web site served by gunicorn and the worker_class is gevent. The PostgreSQL database often complain too many connections, In django's settings.py I have set the database CONN_MAX_AGE to 6, so django will reuse the database connection within 6 seconds. But I found that django is not reusing them. after some digging I found someone say that the async worker of gunicorn will cause this problem: Persistent database connections with async workers on Django >= 1.6 fails Don't use Gunicorn to host your Django sites on Heroku But I guess that's the correct reason, but I don't know why. Is there anyone can analysis this problem from the principle of async worker or the source code of gunicorn and explain this? After reviewing the source code of django db module, I know that django save the database connection in ConnectionHandler()._connections which is a theading.local(), and will reuse it if it is not out of date. because of theading.local(), so it is thread separated. But I think the async worker handle the request asynchronously and is within one single thread, so I don't know why async worker would cause this problem. any suggestion will … -
Can I use the default media path when I distribute my project?
Can I use the default media path when I distribute my project? I have a Django project, you see my media directory: myProject/ | media/ | myProject/ When I distribute my project, whether I can use the media path as the default ? I mean put the media directory in the upper place. as we know when we distribute our project, such as we can config the nginx.conf for media path: localtion /media { alias /path/to/your/website/media; } -
How to delete all data for one and only one app in Django
I have a set up (Django 1.11) with several apps including OOK, EEK, and others irrelevant ones. I want to delete all the data for OOK while leaving EEK (and the rest) untouched. Ideally, I want all the primary keys to be reset as well so the first new OOK model will get 1 and so on… Is this possible? All I can find is reset and sqlclear which are both deprecated. -
Unable to share product details in facebook from angular 5
I am doing a project in angular 5 for front-end side and Django for back-end side. I am facing a problem to share something from front-end by changing meta contents from component. Meta tag contents are updated, that's not an issue but Facebook can't catch updated meta tag contents. I have searched a lot in google and getting suggestion that Facebook sharing is only possible only for server side html rendering. So is there any policy to solve my problem, please help asap if you have any idea. -
Not able to initialise choice fields in Unit test for django form where choice field is getting populated from db
I have one django form where a choice field is getting populated from db. class TestForm(forms.Form): CLASS_CHOICE = [] classes = Class.objects.filter(std__gte=4) for cls in classes: CLASS_CHOICE.append((cls.code, "{} - {}".format(cls.code,cls.std))) name = forms.CharField() class = forms.ChoiceField(choices = CLASS_CHOICE) def _post_clean(self): # some validation pass When writing its unit test as: class SampleTest(TestCase): @classmethod def setUpClass(cls): super(SampleTest, cls).setUpClass() cls.class = Class.objects.create(std=10,code='A') def test_valid_form(self): post_data = {'name':'testing', 'class':'A' } f = TestForm(data=post_data) self.assertTrue(f.is_valid()) Now the problem is, when running test, the application is loaded first before initializing db hence the setUpClass for unit test is not getting called and CLASS_CHOICE remains blank and form validation is getting failed. How can I avoid this or reinitialize choice field after i create one entry in Class table. -
While trying to fetch accept language from header of API in django I am getting error
from django.utils.translation.trans_real import parse_accept_lang_header header_locales=parse_accept_lang_header(request.META.get('HTTP_ACCEPT_LANGUAGE')) error: AttributeError: type object 'request' has no attribute META. I tried importing from django.http.request import HttpRequest from django.http.request But I am getting same error. I am using this code in serializer.py as I need to validate fields based on Accept-language value. Any other way to fetch the information will also be okay. Thanks in advance. -
Error using DjangoFramework in template
new try of dev here. Im trying to make a project and I alredy having some issues that i dont know why dont work... I put my code and explain it... url.py app_name = 'opotest' urlpatterns = [ url(r'^$', views.indexView, name='index'), url(r'^inicio/$', views.ListaView.as_view(), name='inicio'), url(r'^test/(?P<tipo>.+)/$', views.TestList.as_view(), name='test'), this--> url(r'^test/(?P<tipo>.+)/run/$', views.TestDetail.as_view(), name='run'), View.py class TestDetail(generic.DetailView): model = Pregunta context_object_name = 'lista' def get_queryset(self): return Pregunta.objects.all() HTML template {% for test in lista %} <br/> <p>Pregunta: {{ pregunta.textopregunta }}</p> {% endfor %} This code should bring me some 'pregunta' that i have alredy created but it doesnt work... can you please tell me what im doing wrong? the for bring me Pregunta: the textopregunta do not appears... Thanks everyone D... -
pip error on running pip freeze
I was trying to check packages installed using pip, But getting this. Traceback (most recent call last): File "/home/chhuti/projects/venv/chhuti/bin/pip", line 7, in <module> from pip import main File "/home/chhuti/projects/venv/chhuti/lib/python3.6/site- packages/pip/__init__.py", line 26, in <module> from pip.utils import get_installed_distributions, get_prog File "/home/chhuti/projects/venv/chhuti/lib/python3.6/site- packages/pip/utils/__init__.py", line 23, in <module> from pip.locations import ( File "/home/chhuti/projects/venv/chhuti/lib/python3.6/site- packages/pip/locations.py", line 9, in <module> from distutils import sysconfig File "/home/chhuti/projects/venv/chhuti/lib/python3.6/distutils/__init__.py", line 25, in <module> from distutils import dist, sysconfig ImportError: cannot import name 'dist' Have been stuck here for a long time now, couldn't solve it. -
Download excel. Different between <a> and POST
Django/xlwt. Hi. I want the user download excel file from my site. I have the view: VIEW def xls(request): wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('test', cell_overwrite_ok=True) ws.write(0, 0, 'Test cell') response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=test.xls' wb.save(response) return response It's works, if user click the link, but i want to sent post request with params, so i added the function with angular. HTML <a ng-click='getExcel()'>TEST</a> JS $http({ method: 'POST', url: '/motion/deviations/api/xls/', data: {'1': 1}, }).then(function(response){ console.log('response', response); }) But the file didn't download. The response is:response How I can send a POST request to the server with params, create the excel file, and send back to the user. Help pls) -
Conditional related model on Django Many to Many Field
I'm wondering how to achieve this behavior, any help would be appreciate class ModelA(models.Model): pass class ModelB(models.Model): pass class ModelC(models.Model): pass TYPE = (('A', 'ModelA'), ('B', 'ModelB')) type = models.CharField("model type", choices=TYPE, max_length=2, unique=True) field = models.ManyToManyField(ConditionalModel) I want to do something like this in ModelC definition -> if type="A": field = models.ManyToManyField(ModelA) if type="B": field = models.ManyToManyField(ModelB) -
What are Django context processors?
I am struggling with these concepts. For example, I have this view function def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post,status='published',p__year=year,p__month=month,p__day=day,status='published',) return render(request,'blog/post/detail.html',{'post': post}) As I understand, function will take request object as parameter, the template path and the variables to render the given template. Until now it is OK. But now comes template context processor and the magic behind the scene. From djangoproject The TEMPLATE_CONTEXT_PROCESSORS setting is a tuple of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context What are they actually doing? They will expose data inside templates, are there any limitations regarding the input data? -
Trying to get image from static folder Django
I'm trying to display an image located in my static directory. Here is my code : My directories My static settings And finally, my template Please let me know if you've found the answer to my problem. Thanks! -
Django SQLite foreign key mismatch error
class item_sort_info(models.Model): sort = models.CharField(max_length=100, primary_key=True, null=False) class items(models.Model): name = models.CharField(max_length=15, null=False, primary_key=True) inventory = models.PositiveSmallIntegerField(null=False) price = models.PositiveIntegerField(null=False) sort = models.ForeignKey(item_sort_info, on_delete=models.CASCADE) class item_info(models.Model): serial_num = models.PositiveIntegerField(null=False, primary_key=True) items = models.ForeignKey(items, on_delete=models.CASCADE) inbound_date = models.DateField(auto_now_add=True) class pur_history(models.Model): customer = models.ForeignKey(customer_info, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True) item = models.OneToOneField(item_info, on_delete=models.CASCADE) Why am I getting a Django SQLite "foreign key mismatch" error when executing that script? compiler said foreign key mismatch - "pur_history" referencing "item_info" -
Flower pulling in all celery worker information
I have a common codebase with 2 tasks (Task A and Task B).I have 2 ec2 instances (Instance A and Instance B). Celery Beat is configured using env variables so that on Instance A, it runs only Task A and on Instance B, it runs only task B. Each instance has its own Redis Queue.I'm using flower on both instances but flower on instance A is also able get data of celery worker running on Instance B. How is this happening ? -
How to print all tags by using taggit?
I have a small problem, namely I would like to be able to print all taggit tags in my Django project, but I can't seem to be able to make it work. Here's what I came up with until now: views.py from taggit.models import Tag tags_all = Tag.objects.all() and then I'm returning tags_all by using the return function. Then I add the following into my template: {{ tags_all }} However, the result I'm getting after rendering the template looks as follows: <QuerySet [<Tag: security>, <Tag: Internet>]> I would like to be able to get just tags, without the QuerySet bits. How can I achieve this? Just to remind you, I would like to be able to obtain all tags within the project. I have tried using taggit-templatetags and taggit-templatetags2, but they don't see to work properly with Django 2+. Your help would be much appreciated. Thank you in advance. -
Stripe custom payment form isn't shwoing properly
The custom forms is not showing properly. The output is in the link. https://screenshots.firefox.com/Esrmcoq8LUIzgVWB/127.0.0.1 Please help me out. I have simply copied and pasted the 3 codes that Stripe gives in its elements page. The html in an html file, The CSS in the css file, connected to the html and the js in a js file, connected to the html The result is disappointing and not showing at all what's in their "result" section. I can only see the text : Credit or debit card and the button Submit Payment, with no styling at all, Am I missing something ? Obviously yes :p base.html {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Starter Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/starter-template.css' %}" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> </head> <body> {% block content %} {% endblock%} {% block default %} {% endblock%} <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="{% static 'js/slim.min.js' …