Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login page redirecting to different django project
I have two django projects that are identical. The login for my first project work fine. But for my second one it doesn't. When I try to login on the second one it redirects to the first project and throws a 403 Forbidden page at me saying CSRF verification failed. Request aborted. Essentially the host is changing. How do I fix this so I don't have this problem? -
Cannot import six.python_2_unicode_compatible in Django application
Due a new requirement on my Django app, I started using zeep. I installed it as usual throught an existing virtualenv. The problem is that, when i tried to deploy my app, using Apache and mod_wsgi, it doesn't work, returning the following error: ImportError at /prwn/ cannot import name python_2_unicode_compatible /home/prwn/env/lib/python2.7/site-packages/zeep/wsdl/definitions.py in <module> from six import python_2_unicode_compatible The weirdest thing is that when my app is ran using runserver and the same virtualenv, it runs fine. I tried creating a new virtualenv, a new Apache's virtualhost, even changing the permisions to 777 to the whole virtualenv, and still not working. I use the versions 0.23.0 of zeep, 1.10.0 of six and python 2.7 -
How to share data between django server and continuously running python script?
Basically I have a django app and a process which fetches some data from net and perform some computation and save output in a variable. Now whenever a request is made to server i want those data to be retreived and returned in response. How do I go about it? Saving in database ia an option but since this task will be running every second, I don't want to update database every time. -
Disable Delete for specific records of inline form Django Admin
I have a stacked inline form in my admin.py: class XYZInline(admin.TabularInline): model = XYZ readonly_fields = ['modify', 'approver_page'] form = XYZForm extra = 0 And I have it initialized in another model on the admin.py: class SomeOhterModelAdmin(admin.ModelAdmin): inlines = [XYZInline] What I want to do is disable the Delete checkbox in the Inline form for specific form records after checking the value of some of the inputs on the records of the form. If a certain input value matches, we disable the checkbox, otherwise we don't. How can we do this? And how can we check for input values of some of the fields of the form? Some stackoverflow examples suggest adding a self.can_delete=False to the form initializer method. However, that would disable delete for all the form records of the Inline model. -
Returning NONE when selecting from MySQL in python3-Django web application
i have a Django web application running in webfaction sherd host. There is a python file inside it that retrieve the gender of the user based on his/ her name. This is the python3 code: #!/usr/bin/python3 # -*- coding: utf-8 -*- import re,string,sys import sqlite3 import codecs import types import nltk import MySQLdb from nltk import pos_tag from nltk.tokenize import regexp_tokenize from nltk.tokenize import word_tokenize def regexp(expr, item): reg = re.compile(expr) return reg.search(item) is not None # initialize the connection to the database connection= MySQLdb.connect(host="127.0**0.1", user="**", passwd="**",db="db") cursor = connection.cursor() connection.text_factory = str #-----------------------------------------------# #function for catching the user Gender: def findGender(Input): cursor.execute('SELECT Gender FROM Arabic_Names WHERE Name=?',(Input,)) row=cursor.fetchall() if row[0] == 'F': gender= 'F' return gender else: if row[0] == 'M': gender= 'M' return gender else: gender= 'N' return gender #----------------------------------------------# def run_gender_scrip(): cursor.execute('SELECT MAX(id) FROM chat_user_info') ID=cursor.fetchall() cursor.execute('SELECT user_name FROM chat_user_info ORDER BY id DESC LIMIT 1') row=cursor.fetchall() user_name =row[0] user_gender = findGender(user_name) cursor.execute("UPDATE chat_user_info SET user_gender=? WHERE id=?", (user_gender , ID[0])) connection.commit() i have checked the DB Information and the Table and column name, before i was using sqlite3 and it was working fine but after i changed the DB and the made some changes in the … -
Referencing foreing key's name in query
I have model that is related with foreign key and i want to see foreign key model default name instead of PK number class Choice(models.Model): question = models.ForeignKey(Question, related_name='choice', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_textenter code here class ChoiceWithTime(models.Model): choiceTime = models.ForeignKey(Choice,related_name='choiceTime', on_delete=models.CASCADE) choice_date=models.DateField() viev code modelFeatures=ChoiceWithTime.objects.values('choice_date','choiceTime').annotate(datecount=Count('choice_date')).order_by('choiceTime','choice_date') dates=json.dumps(list(modelFeatures), cls=DjangoJSONEncoder) Output from this code is {\"choice_date\": \"2017-04-11\", \"choiceTime\": 7, \"datecount\": 1} I wan't \"choiceTime\": 7 to be \"choiceTime\": Sahara i can't figure out how to put in query with get() function. I wan't to familiarize myself to native abilities of django ORM. I know there is easy way to make it with Django Rest Framework serializer classes. Database should perform count on the query field not just choiceTime_set -
Django rest framework cannot deal with multple objects in model viewset
I have a very simple model and its related serializer and views: class Page(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=255) pub_date = models.DateTimeField(default=timezone.now) class PageSerializer(serializers.ModelSerializer): class Meta: model = Page fields = ('user', 'title', 'pub_date') class PageViewSet(viewsets.ModelViewSet): queryset = Page.objects.all() serializer_class = PageSerializer Now I can post like this: { "user": 1, "title": "Lorem ipsum" } This works fine. But I would like to post multiple objects like this: [ { "user": 1, "title": "Lorem ipsum one" }, { "user": 1, "title": "Lorem ipsum two" } ] So to accept multple objects I modified the view as per the doc: class PageViewSet(viewsets.ModelViewSet): queryset = Page.objects.all() serializer_class = PageSerializer(queryset, many=True) But I am getting an error: TypeError at /api/blog/pages/ 'ListSerializer' object is not callable What am I missing here? -
Django ContextMixin 'super' object has no attribute 'get_context_data'
I need to pass some context to templates in several views. Context is obtained from the BD using some user's info, so I've implemented a Specific ContextMixin class: class CampaignContextMixin(ContextMixin): """ This mixin returns context with info related to user's campaign. It can be used in any view that needs campaign-related info to a template. """ def get_campaigns(self): # Get the first campaign related to user, can be more in the future return self.request.user.campaign_set.all() # Method Overwritten to pass campaign data to template context def get_context_data(self, **kwargs): context = super(CampaignContextMixin).get_context_data(**kwargs) campaign = self.get_campaigns()[0] context['campaign_name'] = campaign.name context['campaign_start_date'] = campaign.start_date context['campaign_end_date'] = campaign.end_date context['org_name'] = self.request.user.organization.name context['campaign_image'] = campaign.image.url context['campaign_details'] = campaign.details return context Then I'm trying to use it in my views, but I'm getting an error: 'super' object has no attribute 'get_context_data' class VoucherExchangeView(CampaignContextMixin, TemplateView): """ This view Handles the exchange of vouchers. """ template_name = "voucher_exchange.html" def get_context_data(self, **kwargs): ctx = super(VoucherExchangeView).get_context_data(**kwargs) # add specific stuff if needed return ctx I' not sure if is caused because inheritance error, or because TemplateView inherits also from ContextMixin. My goal is to reuse the code that adds the campaigns info to the context. Thanks -
Upload a shapefile, generate model and save it to database
I like to create a site where users upload their shapefiles (1 or many) and use the platform to query the data anytime they login. So can someone help how can i do the below: Generating a new model automatically for the uploaded shapefile Then maintain the ORM to serve the data from database to that user when ever required. What is the best strategy to recieve many shapfiles and storing in the database ? -
elasticsearch-dsl - Ingest Node how to build a pipeline
I am pretty new to elasticsearch and am trying to index some pdfs/ppts to my es index. The app is written in python/Django. I am confused as to how exactly pipelines and processors are defined in the es model using elasticsearch-dsl. I need the structure defined here. Could someone please me out here? The persistence example in the docs does not state any such example. Thanks in advance! -
Django add attributes to SelectMultiple <option> tags
There's a great explanation here on adding attributes to <option> tags within a django form field. But this is only for a Select widget. I want to do the same for a SelectMultiple widget. I tried the following (subclass Select and SelectMultiple and reference MySelectMultiple when creating the Model form field employees): class MySelect(forms.Select): def __init__(self, *args, **kwargs): super(MySelect, self).__init__(*args, **kwargs) def render_option(self, selected_choices, option_value, option_label): # original forms.Select code # return u'<option custom_attribute="foo">...</option>' class MySelectMultiple(MySelect): def __init__(self, *args, **kwargs): super(MySelectMultiple, self).__init__(*args, **kwargs) employees = forms.ModelMultipleChoiceField( widget=MySelectMultiple(attrs={}), queryset=Employee.objects.all(), ) But the rendered form is still showing as a Select widget, not a SelectMultiple widget. I can provide attrs={'multiple':'multiple'} to MySelectMultiple to make the form field render as a multiple select widget - but when the form is saved, only a single value is saved (not multiple values)! How can I have the form render as a multiple choice field AND save all of the selected values? Thank you. -
Using object fields in view
I have the following view function: def DetailView(request, category_id): try: items = Photos.objects.filter(name=category_id) context = {'items': items} except Photos.DoesNotExist: raise Http404("Category unavailable") return render(request, 'urcle/details.html', context) So in 'items' there is a field userID I would like to do the following: users = Users.objects.filter(id=userID) How can I get the userID from items (there is only one item in 'items') Thanks -
Django project deployment on cPanel
I am trying to deploy django project on c Panel. Is there any way to deploy projects on c Panel? I have seen no script installation in c Panel server. Thanks in advance -
Where to use Django's templates and where AngularJS?
Where to use Django's templates and where AngularJS? And a second related question is how development faster with using django-angular package instead of pure AngularJS? -
Serving static and media files on a distant server with Django and Nginx
I am configuring a server with Nginx that redirect subdomains to websites (made with Django) on distant servers (on the same local network). It is working fine to serve the content of each site, but I have trouble to serve static and media files (for instance css). Here is the content of the configuration file : server { listen 80; server_name myaddress.fr location / { proxy_pass http://192.168.0.85:8000; } } And here is the end of settings.py in the Django website (which listen at 192.168.0.85:8000) : STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' Usually, when my websites are on the same server than nginx, I just have to add these lines to the nginx conf file: location /media/ { alias /local/path/to/media/; } location /static/ { alias /local/path/to/static/; } How can I generalize this config to serve media and static files on a distant server (here at 192.168.0.85)? Should I install another webserver on the distant machine? Thanks in advance for your help! -
Django Channels [multichat example]: how do I set up admin to enable adding user(s) to a room?
I am attempting to build a custom chat server, based on the following example: channels-examples/multichat/ So far, I have got the basic code working but now I wish to modify the /admin page(s) to permit one or more users to be added to a room, rather than just have users 'join' a room. I am experienced with Python 2/3 and Flask but fairly new to Django and I have spent hours trying to find clues or relevant code but without much success so far. It seems that "Admin actions" would be useful, to invoke chat.consumers.chat_join(), also I presume that I need to add a 'user' field to the Room class of chat.models but now I am not sure what to do next. I have studied the offical Django documentation, the example/Channels code itself and many other sites but I would appreciate some help. There are couple of point to note in case anyone else is in a similar situation: Django Groups (admin) have nothing to do with the channel.Group, A user can currently 'join' a room but that is a very loosely-coupled relationship, that is not recorded in the DB (postgres). I hope to add such persistence later on. I … -
what's the postfix configuration to allow smtp automatic django emails
On my last server i could send smtp automatic emails on port 25 but after migrating the server on virtualmin install, i can't make it work Here's the old working postfix config myhostname = ##REVERSE_DNS_IPV4## myorigin = ##REVERSE_DNS_IPV4## mydestination = localhost.localdomain, localhost, ##REVERSE_DNS_IPV4## relayhost = mynetworks = 127.0.0.0/8, ##IPV4_PUBLIQUE_SERVEUR## mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = all inet_protocols = ipv4 virtual_alias_maps = mysql:/etc/postfix/mysql-virtual_aliases.cf,mysql:/etc/postfix/mysql-virtual_aliases_comptes.cf virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual_domaines.cf virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual_comptes.cf virtual_mailbox_base = /var/spool/vmail/ virtual_uid_maps = static:5000 virtual_gid_maps = static:5000 virtual_create_maildirsize = yes virtual_mailbox_extended = yes virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql-virtual_quotas.cf virtual_mailbox_limit_override = yes virtual_maildir_limit_message = "La boite mail de votre destinataire est pleine, merci de reessayez plus tard." virtual_overquota_bounce = yes # adresses d'expedition smtpd_sender_restrictions = permit_mynetworks, warn_if_reject reject_unverified_sender # adresses de destination smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, reject_non_fqdn_recipient # client smtpd_client_restrictions = permit_mynetworks Here is the current not working configuration smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU) biff = no # appending .domain is the MUA's job. append_dot_mydomain = no # Uncomment the next line to generate "delayed mail" warnings #delay_warning_time = 4h readme_directory = no append_dot_mydomain = no smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination # TLS parameters smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key smtpd_use_tls=yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache myhostname = vsweb03.help-amor.be alias_maps = hash:/etc/aliases alias_database … -
django meny-to-meny show human-readable in form
I have these models: CURSES=(('python','Python'),('django','Django'),...) class Asig(models.Model): ... name = models.CharField(max_length=100, choices=CURSES) class Profesor(AbstractUser): ... asigs = models.ManyToManyField(Asig) Then, when I render the form using ModelForm the many-to-meny field shows itself with 'python' string instead 'Python', also, when I look the rendered html coded the multiselect options look like: <option value='1'>python</option> instead of <option value='python'>Python</option> -
Django nested aggregates with group_by
I have a query select avg(total) from (select date, sum(value) as total from table group by some_field, date) as res group by week(date) This is the way I'm getting sum of metrics for each date and show average result grouped by week. How could I get the same result with Django ORM not using raw query. -
django rest frame work : oscarapi authentication is not working
I am facing a weired issue when I call oscarapi calls through ios. It is working fine with POSTMAN. But when I call through xcode, it shows the following error. HTTP/1.1 401 Authorization Required Connection: Keep-Alive Content-Type: application/json Server: Apache/2.4.7 (Ubuntu) Allow: GET, HEAD, OPTIONS Vary: Accept,Authorization,Cookie Date: Thu, 20 Apr 2017 13:55:13 GMT X-Frame-Options: SAMEORIGIN Www-Authenticate: Bearer realm="api" Keep-Alive: timeout=5, max=100 Transfer-Encoding: Identity {"detail":"Authentication credentials were not provided."} I sending the heading authrization as follows. This is working fine in postman. Authorization: Bearer iw7cGIz4uF036j7VbpGCXbceCCbbD1 My urls.py url(r'^api/v1/categories/', views.CategoryListCustom.as_view(), name='category-list') views.py class CategoryListCustomd(generics.ListAPIView): def get_queryset(self): queryset = Category.objects.all() return queryset serializer_class = CustomCategorySerializer -
Freezing database for testing new features in Django
In my Django app, I want to add a couple of fields to my existing models and possibly create a new class. I just want to test the new feature and approve if it works. I can revert the code using git easily. But if I make a makemigrations+migrate then my MySQL database will change and reversing the changes looks like manual deletion of tables and reverting to an old state using a command like django-admin migrate [app_label] [migration_name] (In some cases it looks really cumbersome, example). I'm wondering if there is any safe practice to try manipulating the database and revert it back to it's initial state safely. -
Application layer strategies against HTTP floods (web app is a Django forum)
A Django-based web forum I maintain is seeing application level DDOS attacks daily. Essentially, it seems to be an HTTP flood hitting the home page, causing the server to execute a large number of internal requests and load various files to create the page. The flood peaks at ~4000 requests per minute (typical throughput being around 500 rpm), bringing down my server in the process. My webserver is nginx serving as reverse proxy for a gunicorn application server. I have fail2ban installed on my VM, and have two jails in my jail.local to ensure HTTP floods are thwarted: [nginx-postflood] enabled = true filter = nginx-postflood port = http,https logpath = /var/log/nginx/access.log findtime = 60 maxretry = 13 bantime = 300 [nginx-getflood] enabled = true filter = nginx-getflood port = http,https logpath = /var/log/nginx/access.log findtime = 5 maxretry = 6 bantime = 600 This setting has not helped, and I can't figure out why. When I test it, I'm able to block my IP, so it's definitely functional. Perhaps the HTTP flood has randomized IPs. What tactics can I employ to thwart this kind of application layer DDOS? Being a newbie, I'm still wrapping my head around all this. Expert help … -
Django media folder range request + pileup genome browser
I am trying to use the pileup genome browser (https://github.com/hammerlab/pileup.js), which is already based on range requests, to read from some files placed on the media folder. Do anyone know how to enable range requests in Django on the media folder? Do anyone have any workaround to solve this issue? Thank you -
In django: Problems with loading jquery with multiple plugins - or: How to load jQuery only once?
I use django (1.8.16) with a ton of plugins ("apps"). Some are: django-ckeditor==4.5.1 django-image-cropping==1.0.3 django.contrib.admin django-jquery==3.1.0 I want to use django autocomplete-light (dal for short) (3.2.1, current version) in the admin interface. Now I have the following jquery struggle. dal uses jquery but does not load it itself. It leaves it up to the developer. dal comes with a script "select2.js" registering a function under $.select2. Now the problem. When a plugin like ckeditor or image-cropping loads jquery the function $.select2 is not reachable any more. I have created a bug report over at dal but one dev says it is my responsability to load jquery first. So, how do I load jquery, load it before dal needs it and load it only once? -
Django admin page combobox, possible?
I have a simple model in django with a field using choices. As it is now, I am forced to use one of the available choices, how can I be able to use those choices and also be able to enter text manually? WHERE_CHOICES = ( ('CHL', 'Center HL'), ('CHD', 'Center HD') ) class Event(models.Model): ev_start = models.DateTimeField() ev_end = models.DateTimeField() where = models.CharField(max_length=3, default='CHL', choices=WHERE_CHOICES) Thanks