Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Iterating through an object set with unique_together and no pk
I am trying to iterate through an object set passed to a for template tag. # Views.py def index(request): content_list = Content.objects.all() return render(request, 'orders/index.html', {'content_list': content_list}) However, Content's model has a unique_together pk, so I can't give it an ID pk. # Models.py class Content(models.Model): content_id = models.AutoField(primary_key=True, unique=True) order_id = models.ForeignKey(OrderInfo, db_column='order_id') class Meta: unique_together = (('order_id', 'product_id'),) Since Content doesn't have an ID pk, i'm getting the error when passing the context and trying to loop through it: OperationalError at /orders/ (1054, "Unknown column 'content.id' in 'field list'") The loop code is just {% for content in content_list %} I know that the error here is that Content has no id (which Django needs to loop through something, if i'm correct), but since the unique_together is already the PK, I can't give Content an ID. Is there a way to fix this or get around it? Or am I just missing something? Thank you! -
Can i deploy a Django project using Apache that is not located in /var/www?
I have a Django project which is working in development on my local machine. I am confused whether or not I am able to have my django project in another directory other than /var/www/. Do I just need to change the DocumentRoot in the apache config file? Thanks -
502 error with django, gunicorn and Nginx
Been trying to set up django to work with nginx and gunicorn for a few days, followed a digital ocean guide for the setup, tried numerous solutions found in this forum but none worked for me. This is my first stackoverflow post, if it's miss-formated or poorly written based on how you like to read the posts I'd like to hear it so that I can improve. Starting gunicorn from the folder /home/django/virtualenv/sio/SiO running the command gunicorn --bind 0.0.0.0:8000 SiO.wsgi:application works just fine, I've tried setting this to be the sock-folder. But my latest try has been for /home/django/virtualenv/sio/SiO/SiO where the wsgi.py file resides. when looking at the nginx error log I find 2017/05/03 15:02:00 [crit] 1069#1069: *1 connect() to unix:/home/django/virtualenv/sio/SiO/SiO.sock failed (2: No such file or directory) while connecting to upstream, client: 158.39.197.123, server: 67.207.75.163, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/virtualenv/sio/SiO/SiO.sock:/", host: "67.207.75.163" Tree view of the project structure: |-- SiO | |-- calapp | | |-- migrations | | | |-- __pycache__ | | | | `-- __init__.cpython-35.pyc | | | `-- __init__.py | | |-- __pycache__ | | | |-- admin.cpython-35.pyc | | | |-- __init__.cpython-35.pyc | | | |-- models.cpython-35.pyc | | | |-- urls.cpython-35.pyc | … -
Grouping in django query set
I have an query set object with has two attributes: words, number_of_letters. I would like to group the words by the no of letters in them. For example, all the words with 4 letters should be grouped together. How do I do this when I don't know the maximum number of letters the grouping has? Will I be able to put the grouping into separate objects? Also, is there a way to modify all the words in the object in one go? For example, if I need to prefix a string to all the words in the object? -
UpdateAPIView not working: Method "PATCH" not allowed
I use Django along with Django REST Framework to implement a RESTful API. What I have right now: A ContentEntry model A ContentEntryCreateUpdateSerializer serializer for my ContentEntry model A ContentEntryCreate view to create some ContentEntryies A ContentEntryUpdate view to update the ContentEntryies Here is the code: from django.db import models from rest_framework import serializers from rest_framework import generics from rest_framework.views import APIView from my_api_app import views # models.py class ContentEntry(models.Model): content = models.ForeignKey(Content) quantity = models.IntegerField() container = models.ForeignKey(Container, related_name='content_entries') # serializers.py class ContentEntryCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = ContentEntry fields = ('id', 'content', 'quantity', 'container') # views.py class ContentEntryCreate(generics.CreateAPIView): queryset = ContentEntry.objects.all() serializer_class = ContentEntryCreateUpdateSerializer # views.py class ContentEntryUpdate(generics.UpdateAPIView): queryset = ContentEntry.objects.all() lookup_field = 'id' serializer_class = ContentEntryCreateUpdateSerializer # urls.py urlpatterns = [ url(r'content-entry', views.ContentEntryCreate.as_view()), url(r'content-entry/(?P<id>\d+)$', views.ContentEntryUpdate.as_view()), ] Everything is working fine except the ContentEntryUpdate which always returns an error: HTTP/1.1 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Date: Wed, 03 May 2017 14:40:03 GMT Server: WSGIServer/0.2 CPython/3.6.1 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN {"detail":"Method \"PATCH\" not allowed."} As you can see in the Allow attribute, it seems that only the POST and OPTIONS methods are allowed by the server. It's very strange since generics.UpdateAPIView defines the put and … -
Working on two branches for two different 'local servers' simultaneously
I am current working on a Django project. I would need to work on two branches simultaneously. To be precise, I'd like to work on two local server for two different branches. How could I use git worktree ... to to such thing? An example would be appreciated... I know I could work with two 'local servers' with python manage.py runserver and python manage.py runserver 127.0.0.1:8001. The reason why I need to do that is I need to move back in forth systematically in different branches. It'll be more convenient to work with two different branches in the same time. Thanks in advance! -
django - with transaction.atomic()
I'm trying to log database errors using the transation.commit() context manager. This is the code chunk: def _process_batch(_lower_limit, _upper_limit, step, **kwargs): skipped_rows_mapping = kwargs.pop('skipped_rows_mapping') form_errors = kwargs.pop('form_errors') process_rows_object_list = _process_rows( _lower_limit, _upper_limit, **process_rows_kwargs ) try: with transaction.atomic(): Transcript.objects.bulk_create(process_rows_object_list, batch_size=2000) if verbose: print('processed {} rows; {} transcripts created...'.format( upper_limit, len(process_rows_object_list)) ) print_timestamp() # periodically log errors to logfiles for _key, _vals in skipped_rows_mapping.items(): with open(_vals['logfile'], 'a+') as logfile: _writer = csv.writer(logfile, delimiter=str('|')) _writer.writerows( [r + (_vals['msg'],) for r in _vals['lst']] ) skipped_rows_mapping[_key]['lst'] = [] if form_errors.keys(): with open("/tmp/process_transcripts_with_temp_db_table_form_errors", 'a+') as log_file: for _form_err, _rows_ in form_errors.items(): _writer = csv.writer(log_file, delimiter=str('|')) _writer.writerows( [_r + (_form_err,) for _r in _rows_] ) form_errors[_form_err] = list() except (IntegrityError, DatabaseError) as db_exception: errors_list.append( ErrorDetails( err_type=db_exception.__class__.__name__, msg=db_exception.message, id_interval=(_lower_limit, _upper_limit) ) ) finally: _lower_limit = _upper_limit _upper_limit += step if _upper_limit > max_id: _upper_limit = max_id return _lower_limit, _upper_limit However IntegrityError and DatabaseError are not catched, probably due to the with transaction.atomic() block that already handle the exceptions. How I have to modify the code to catch and log those errors? -
How do you make django admin diplay a table of information to HTML Table.
I have a HTML table but I would like to update the table of information using the DJango admin so i do not have to go in using HTML to put in in my self. I just want the users to see the information but not input anything. SO then each week i could change the information using the Django admin piece. -
how to highlight json files as django templates in pycharm
I am generating JSON files with django templates like so: { "media_objects": [ {% for media in media_list %} "{{ media.title }}" {% if not forloop.last %} , {% endif %} {% endfor %} ] } This works fine, but I have trouble with syntax highlighting in Pycharm, because if Pycharm thinks this is JSON file it highlights it like so: How do I add django template support for JSON files to enable auto-completion? -
How to add post/content reading time in a django blog?
I am trying to add content read time in django app (posts) but its not working properly don't know whats going wrong. posts/models.py : from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.db.models.signals import pre_save from django.utils import timezone from markdown_deux import markdown from django.utils.safestring import mark_safe from .utils import get_read_time #from comments.models import Comment #from django.contrib.contenttypes.models import ContentType #to specify image upload location we define a function #def upload_location(instance, filename): # return "%s/%s" % (instance.pk, filename) class PostManager(models.Manager): def active(self, *args, **kwargs): return super(PostManager,self).filter(draft=False).filter(publish__lte=timezone.now()) class Post(object): pass class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True,) #upload_to=upload_location) content = models.TextField() draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) read_time = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) objects = PostManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={'pk': self.pk}) # for latest posts on top of page class Meta: ordering = ['-timestamp', 'updated'] def get_markdown(self): content = self.content markdown_text = markdown(content) return mark_safe(markdown_text) # @property #def comments(self): # instance = self # qs = Comment.objects.filter_by_instance(instance) # return qs # @property #def get_content_type(self): # instance = self # content_type = ContentType.objects.get_for_models(instance.__class__) # return content_type def pre_save_post_receiver(sender, instance, *args, **kwargs): … -
How do I set up a development version of an inherited Django site?
A new client has asked us to help with their site, my boss said yes without asking or consulting me. It's a Django site and I have very little experience with Python. I've spent the past few days trying to figure out the directory structure and how it all pieces together but have come up with nothing. I can get all the files in place, make sure all the directories are the same but nothing works. I've installed Django locally and on a live server, I've downloaded the whole site as is, plugged them all in with a requirements.txt (that I had to make as the original site didn't have one) but I'm now at a loss. All research tells me that the static files should be separated from the rest of the files but they're inside a _cms folder. Having worked with CMS's I'm fairly familiar with how they work but this structure makes no sense to me. It goes ~/home/deploy/envs/eo/www/eo/eo_cms/templates for all the template pages and all the static files are also within the eo_cms page. But all the /bin /lib /src directories are within ~/home/deploy/envs/eo/ and there is no straight public_html folder and pages aren't being served … -
Django sending password reset emails
I am using this package for resetting user passwords. When I am sending an email using the recover url, sometimes it works but sometimes there is an error: Exception Type: SMTPRecipientsRefused Exception Value: {'': (555, '5.5.2 Syntax error. m24sm5544702pfi.129 - gsmtp')} My Settings.py file EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 -
Is it the right way to customize Twitter Bootstrap 3? [duplicate]
This question already has an answer here: Customizing Bootstrap CSS template 7 answers I read many articles, but it seems like they are all lack of clearence of some point. I am trying to make a website with Django, and now I want to customize Bootsrap(changing colors, font, grids, etc.), so: I copied the bootstrap.min.css file and named it as custom.css I typed this code after declaring bootstrap.min.css: <link rel="stylesheet" href="{% static 'home/css/custom.css' %}" type="text/css"> I started to coding in css at the end of the custom.css file. I managed to change the color with this method in the beginning, but now I can't change even the color I changed before. It sometimes works, sometimes doesn't and it also drives me crazy that I couldn't find enough proper resources to define the whole process clearly. Is it the right way? Is there any thing I need to add to the process? What is the most reliable method for fast prototyping? Thank you! -
uploading a file using django
I am developing an application with django for uploading a file on the server. I have defined a form and a model in forms.py and models.py files separately as below(respectively): from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='' ) and in models.py: from django.db import models # Create your models here. class Document(models.Model): docfile = models.FileField(upload_to='targetdir') in my HTML file and in a form I have defined a tag such as below for my file tag: <p> {{ form.docfile.errors }} {{ form.docfile }} </p> now, whenever I submit my form and I wanna to receive my uploaded file on the server via below codes, I got " raise MultiValueDictKeyError(repr(key)) MultiValueDictKeyError: "'docfile'"" error. data = request.FILES('docfile') -
How to use the attrs in forms.CharField(widget=forms.PasswordInput()
I'm trying to create a custom fields in Django I'm not sure this is the right approach, but I keep getting an error I can't understandenter code here AttributeError: 'CharField' object has no attribute 'attrs' Here is my code. Can anyone explain what's going on? class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password', 'confirm_password') widgets = { 'username': forms.TextInput(attrs={'class': "form-control input-lg", 'placeholder': "نام کاربری *", 'name': 'display_name', 'required': "required", 'tabindex': "3", 'data-error': "password is required"}), 'email': forms.EmailInput(attrs={'class': "form-control input-lg", 'placeholder': 'ایمیل *', 'name': 'email', 'required': "required", 'tabindex': "4", 'data-error': "email is required"}), 'confirm_password': forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control input-lg", 'placeholder': "تکرار رمز *", 'name': 'confirm_password', 'required': "required", 'tabindex': "6", 'data-error': "confirm password is required"})), 'password': forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control input-lg", 'placeholder': " رمز *", 'name': 'password', 'required': "required", 'tabindex': "5", 'data-error': " password is required"})), } -
Most efficient data source for generating dygraphs?
We have CSV data sources that are of size in MBs and which can reach GBs and from which, we want to load data into dygraphs. I am thinking of setting up postgres database and use it as backend for dygraphs. Which frameworks can I use here for high efficiency? I find this where reports from postgres database itself are plotted using dygraph. But I wonder on seeing the source code, why the data is hardcoded. Is it really a hardcoded data or could it be loaded automatically. I don't think it is loaded automatically, as it is as static html page. http://pgstatsinfo.projects.pgfoundry.org/files/report_sample.html In short, I need most efficient way and ideas for useful frameworks for implementing this. Thanks! -
error in setuptools after installation
I've installed the last version of setuptools successfully but when i run it there are a lot of errors which i don't know what they are!: Traceback (most recent call last): File "C:\python33new\Scripts\easy_install-script.py", line 11, in <module> load_entry_point('setuptools==33.1.1', 'console_scripts', 'easy_install')() File "C:\Python33new\lib\pkg_resources\__init__.py", line 560, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "C:\Python33new\lib\pkg_resources\__init__.py", line 2648, in load_entry_point return ep.load() File "C:\Python33new\lib\pkg_resources\__init__.py", line 2302, in load return self.resolve() File "C:\Python33new\lib\pkg_resources\__init__.py", line 2308, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "c:\python33new\lib\site-packages\setuptools-33.1.1-py3.3.egg\setuptools\__init__.py", line 10, in <module> from setuptools.extern.six.moves import filter, map File "c:\python33new\lib\site-packages\setuptools-33.1.1-py3.3.egg\setuptools\extern\__init__.py", line 1, in <module> ImportError: No module named 'pkg_resources.extern' also you can see the picture: http://s9.picofile.com/file/8293884318/Untitled.jpg note:i ran the setuptools.py which is in the scripts folder how can i fix it(i want to install jango and now this is a big problem!) -
Working on two branches for two different 'local servers' simultaneously
I am current working on a Django project. I would need to work on two branches simultaneously. To be precise, I'd like to work on two local server for two different branches. What is the best way to do that? Could I use git worktree ...? I know I could work with two 'local servers' with python manage.py runserver and python manage.py runserver 127.0.0.1:8001. Thanks! -
Convert Genbank to FASTA sorting by locus
I want to convert my genbank file into fasta file. But I have a form too who give me locus_tag and I want to sort my fasta file with it. I'm using Django and BioPython. To explain this, my code : def export_to_fasta(request): if request.method == "POST": locus_tag = request.POST.getlist("select") souche = request.POST['souche'] choix = request.POST['choix'] if choix == "prot": urlIn = "/home/user/Data/" + souche + "/test.fasta" urlOut = "/home/user/Site_test/site_test/media/export.faa" with open(urlIn, 'r') as fichier_gene: with open(urlOut, 'w') as out: for record in SeqIO.parse(fichier_gene, 'fasta'): id_gene = record.id list_id = id_gene.split('__') locus = list_id[1] for l in locus_tag: if l == locus: SeqIO.write(record, out, "fasta") if choix == "adn": urlIn = "/home/user/Data/" + souche + "/test.gbk" urlOut = "/home/user/Site_test/site_test/media/export.fna" with open(urlIn, 'r') as fichier_gene: with open(urlOut, 'w') as out: for record in SeqIO.parse(fichier_gene, 'genbank'): for feature in record.features: if feature.type == 'CDS': locus = feature.qualifiers["locus_tag"][0] for l in locus_tag: if locus == l: SeqIO.write(record, out, "fasta") #break return render(request, "contig/exportFasta.html", {'choix': choix}) I have a form who permit to do the choice. When choice is prot I have no problem. But when is adn I have the whole sequence and I want only the part which interests me, which correspond … -
Invalid HTTP_HOST header: 'localhost:90,localhost:90'. The domain name provided is not valid according to RFC 1034/1035
I am trying to configure nginx along with gunicorn for a django project.But nginx is not serving , the following error occuring DisallowedHost at / Invalid HTTP_HOST header: 'localhost:90,localhost:90'. The domain name provided is not valid according to RFC 1034/1035. This is my nginx configuration server { listen 90; listen [::]:90; server_name xxxx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/djangopro/djangoapp; } location / { include proxy_params; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_buffering off; proxy_redirect off; proxy_pass http://localhost:8200/; } } Gunicron servering properly at localhost 8200.Anyone tell me what is the actual error in nginx? -
NoReverseMatch with UUIDField
Django 1.11 Could you give me a kick here (traceback below)? models.py class Image(CommonUrlMethodsMixin, GeneralModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Traceback: {NoReverseMatch}Reverse for 'detail' with keyword arguments '{'pk': UUID('718d5ff1-702c-4a81-a2a8-5cf59f1605e6')}' not found. 1 pattern(s) tried: ['images/(?P<pk>\\[\\w-]+)/$'] urls.py urlpatterns = [ url(r'^images/', include('images.urls.show_modify', namespace='images')), ] images.urls.show_modify.py urlpatterns = [ url(r'^(?P<pk>\[\w-]+)/$', ImageDetailView.as_view(), name="detail"), ] By the way, this works: >>> im = Image.objects.get(pk='718d5ff1-702c-4a81-a2a8-5cf59f1605e6') >>> im <Image: ID 718d5ff1: , title sdfsadf> -
Djstripe AttributeError
I am getting the following error every time a new user is created. Once the card info is entered into the stripe.js popup and shortly after the card appears to be accepted the error occurs. I am using djstrip 0.8.0 python 3.5 django 1.9.7. I have been using djstripe successfully for some time now. I am unsure of what has gone wrong. Here is my traceback: Internal Server Error: /payments/confirm/monthly AttributeError at /payments/confirm/monthly active_card 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'] Traceback: File "/usr/local/lib/python3.5/site-packages/stripe/resource.py" in __getattr__ 135. return self[k] File "/usr/local/lib/python3.5/site-packages/stripe/resource.py" in __getitem__ 176. raise err File "/usr/local/lib/python3.5/site-packages/stripe/resource.py" in __getitem__ 165. return super(StripeObject, self).__getitem__(k) During handling of the above exception ('active_card'), another exception occurred: File "/home/techsight/public_html/lib/python/Django-1.9.7- py3.5.egg/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/techsight/public_html/lib/python/Django-1.9.7- py3.5.egg/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/techsight/public_html/lib/python/Django-1.9.7- py3.5.egg/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/braces/views/_access.py" in dispatch 102. request, *args, **kwargs) File "/home/techsight/public_html/lib/python/Django-1.9.7- py3.5.egg/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/djstripe/views.py" in post 175. customer.update_card(self.request.POST.get("stripe_token")) File "/usr/local/lib/python3.5/site-packages/djstripe/models.py" in update_card 269. self.sync_card() File "/usr/local/lib/python3.5/site-packages/djstripe/stripe_objects.py" in sync_card 270. self.card_fingerprint = stripe_customer.active_card.fingerprint File "/usr/local/lib/python3.5/site-packages/stripe/resource.py" in __getattr__ 137. raise AttributeError(*err.args) Exception Type: AttributeError at /payments/confirm/monthly Exception Value: … -
How to translate a country list in a django views.py?
I am using django and the standard internationalization package as showed in the : excellent marina mele tuto. In a user's form on web and mobile i have to show a list of country names in the user's language. To create the country list, i intend to use django-country it seems easy and well documented. I could do one API, no template, to request the list of countries. But How to translate this country list in the views.py ? Any example would be welcome. Thanks -
CSS not rendering in Django
I am trying to use a css stylesheet and I have followed https://docs.djangoproject.com/en/1.11/intro/tutorial06/ tutorial to the end to setup my css files. Still they are not rendering when I am running it on localhost. This is my project structure: Project Structure And this is the code I am currently using: {% load static %} <link href="{% static 'pwash/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'pwash/css/datepicker3.css' %}" rel="stylesheet"> <link href="{% static 'pwash/css/bootstrap-table.css' %}" rel="stylesheet"> <link href="{% static 'pwash/css/styles.css' %}" rel="stylesheet"> <!--Icons--> <script src="{% static 'pwash/js/lumino.glyphs.js' %}"></script> I have added my app in setting.py file. I have followed the norms. -
How to make Postgresql query with JQuery in Django?
I need to dynamically change a forum based on a selection of a drop down menu. The forum will have a menu and two textboxes. All the information is in a Postgresql database, like so: | Dropdown | Text1 | Text 2 | --------------------------------- | 1 | red | blue | | 2 | dog | cat | This this choice_table. Now, in my HTML code I have put the following to figure out which choice has been selected: <script> $("#id_drop_down").on('change', function() { if ($(this).val() !== ""){ $choice = $(this).val() alert($choice + " has been selected!") }; }); </script> My next step is to use $choice to use as an identifier to query into the choice_table and populate Text1 and Text2. How can I use $choice to query my database?