Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django python: best algorithm to plot 2*2 arrary into excel
I have the following postgres db class Prescription(TimeStampedModel): name = models.CharField() patient_name = models.CharField() class PrescriptionLine(TimeStampedModel): prescription = models.ForeignKey(Prescription, related_name="prescriptionlines") pill = models.ForeignKey(Pill, related_name='prescriptionlines') quantity = models.IntegerField() class Pill(TimeStampedModel): pill_category = models.ForeignKey(PillCategory, related_name='pills') class PillCategory(TimeStampedModel): name = models.CharField() Suppose I have 3 different prescriptions(A,B,C) with different number of prescriptionlines. Prescriptions = { Prescription A : {'name': 'A', 'patient_name': 'David', 'pill X': '4g', 'pill Y': '6g', 'pill Z': '10g'}, Prescription B : {'name': 'B', 'patient_name': 'James', 'pill U': '2g', 'pill X': '6g', 'pill Z': '3g'}, Prescription C : {'name': 'C', 'patient_name': 'Mary', 'pill S': '2g', 'pill T': '6g', 'pill Y': '3g', 'pill Z': '4g'} } Above data should be plotted into excel file as following table with the following code df = pd.DataFrame(prescriptions).fillna('') df.to_excel('prescriptions.xls') Table | | Prescription A| Prescription B | Prescription C | | patient_name | David | James | Mary | | -------- |:-------------:| --------------:|----------------| | Pill S | | | 2g | | Pill T | | | 6g | | Pill U | | 2g | | | Pill X | 4g | 6g | | | Pill Y | 6g | | 3g | | Pill Z | 10g | 3g | 4g | -
How to filterfalse pandas dataframe from django queryset
This is to add a to a postgres table data from an html table, without having to recreate the table, but simply insert new data. I need to remove some row from a pandas dataset, those data are already inside the django db and would trow an error triyng to reinsert them in the db. So first I look for the rows in the df already archived in the db: items_to_be_removed_from_df=MyModel.objects.filter(id=df['id']).annotate().values(id) Now I need to get the other rows from the df, would it be possible something like this? filtered_df=df.filterfalse(id=items_to_be_removed_from_df) -
Django-Allauth not allowing me to access the login with facebook Python2.7 Django
I have tried to login with django-Allauth application in Django 1.11.5. I am using python 2.7. The problem is: when I logged in with my account I got a clean chit ... successful login. I have submitted the application but the review failed as there was flaw in the login of the application using the other user. Then I sent that application to my friend to test it and he found the same issue. I wonder why I do not see anything and I get a successful login, while my friend or the facebook app reviewer didn't. See the following codes and please let me know what I might need to improve to make the application work accordingly. settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos', 'user_about_me', 'user_likes', 'user_friends'], 'METHOD': 'oauth2', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', 'posts', 'about', 'picture.type(large)', 'likes', 'cover', 'taggable_friends.limit(1){name,picture.type(large){url},first_name}', ], 'LIKED_FIELD': [ 'link', 'name', # 'picture.type(normal){url}', ], # 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } INSTALLED_APPS = ( 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.request', 'allauth.account.context_processors.account', 'allauth.socialaccount.context_processors.socialaccount', ) … -
Deploy Django 1.10 app with python 3.6 on Google Computer Engine
I have created a project using with Django 1.10.5 and python 3.6, now I need to deploy this project on google compute engine.I have googled a lot but couldn't find any clear guide to deploy my Django app on compute engine. What I have tried: Create a compute engine instance Install python 3.6 (But not succeded that's why using pre-installed python 3.5.2) Setup pip and virtualenv Create a virtualenv and clone my project from GitHub Install all requirements from requirements.txt now when I try to run my app as python manage.py runserver from my directory, it says : Django version 1.10.5, using settings 'brain.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. when I visit http://127.0.0.1:8000/ doesn't load any page. How can I deploy my Django 1.10 & Python 3.6 app on google compute engine? Help me, please! Thanks in advance! -
django rest framework reverse foreign field doesn't updated, return empty list
I have following model structure, class Bill(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='bill_created_by') total_bill_amount = models.IntegerField(blank=True, null=True) class Route(models.Model): start_time = models.DateTimeField(auto_now=False,blank=True, null=True) end_time = models.DateTimeField(auto_now=False,blank=True, null=True) start_lat = models.FloatField(default=0.0,blank=True, null=True) start_lon = models.FloatField(default=0.0,blank=True, null=True) end_lat = models.FloatField(default=0.0,blank=True, null=True) end_lon = models.FloatField(default=0.0,blank=True, null=True) distance = models.FloatField(default=0.0,blank=True, null=True) transport = models.CharField(max_length=300,blank=True, null=True, choices=ROUTE_MODE, default=ROUTE_MODE[0]) fare = models.IntegerField(blank=True, null=True) purpose = models.CharField(max_length=1000, blank=True, null=True) bill = models.ForeignKey(Bill, related_name="routes",on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, related_name='routes', max_length=255) and the serializers, class BillSerializer(ModelSerializer): routes = RouteSerializer(many=True, read_only=True) class Meta: model = Bill fields = ('id','created_on','created_by','total_bill_amount','routes') lass RouteSerializer(ModelSerializer): all_directions = AllDirectionSerializer(many=True, read_only=True) user = ReadOnlyField(source='user.email') bill = ReadOnlyField(source='bill.id') class Meta: model = Route fields = ('id','start_time','end_time','start_lat','start_lon','fare', 'end_lat','end_lon','distance','transport','all_directions','user', 'bill') and Bill api using viewset, class BillViewSet(viewsets.ModelViewSet): queryset = Bill.objects.all() serializer_class = BillSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) now if i want to update Bill api with list of Routes according to the serializer structure, like this **calling put method on Bill api where Bill id is 29** { "id": 29, "created_on": "2017-10-15T10:05:19.786057Z", "created_by": 4, "total_bill_amount": 301, "routes": [ { "id": 31, "start_time": null, "end_time": null, "start_lat": 23.77201, "start_lon": 90.3602333333333, "fare": 0, "end_lat": 0.0, "end_lon": 0.0, "distance": 0.0, "transport": "BUS", "all_directions": [], "user": "tanvir@gmal.com", "bill": 29 }, { … -
Add aldryn categories and tags to aldryn newsblog
I installed Aldryn NewsBlog on my Django CMS project. Aldryn NewsBlog documentation on content creation states I should be seeing the following meta options for each blog post: (1) Tags, (2) Categories, (3) Application configuration. But I don't see (1) and (2). Using (2) as example: I understand Aldryn NewsBlog uses Aldryn Categories app. I further referred to Aldryn Categories documentation and visited its github. Question: As Aldryn's documentation is silent, am I supposed to add the files in github to my project? If yes, where do I add them? Thanks very much. -
Spyne lxml validation error soap11env:Client.SchemaValidationError
This is the xml I need to parse https://codepad.co/snippet/nob995lf#= Here is my models: https://codepad.co/snippet/VsqZTQ2i But I got this error: :83:0:ERROR:SCHEMASV:SCHEMAV_ELEMENT_CONTENT: Element '{http://www.opentravel.org/OTA/2003/05}RestrictionStatus': This element is not expected. Any help would be appreciated. Thank you. -
Win10 Django: NoReverseMatch at / Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am new to python and Django and use win10 system. Django Version:1.9.4. and Python Version:3.6.3. In template D:\Music\music\templates\music\index.html, error at line 29 19 <div class="caption"> 20 <h2>{{ album.album_title }}</h2> 21 <h4>{{ album.artist }}</h4> 22 23 <!-- View Details --> 24 <a href="{% url 'detail' album.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> 25 26 <!-- Delete Album --> 27 <form action="{% url 'delete_album' album.id %}" method="post" style="display: inline;"> 28 {% csrf_token %} 29 <input type="hidden" name="album_id" value="{{ album.id }}" /> 30 <button type="submit" class="btn btn-default btn-sm"> 31 <span class="glyphicon glyphicon-trash"></span> 32 </button> 33 </form> 34 35 <!-- Favorite Album --> 36 <a href="{% url 'favorite_album' album.id %}" class="btn btn-default btn-sm btn-favorite" role="button"> 37 <span class="glyphicon glyphicon-star {% if album.is_favorite %}active{% endif %}"></span> 38 </a> It's my music\urls.py: from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), url(r'^songs/(?P<filter_by>[a-zA_Z]+)/$', views.songs, name='songs'), url(r'^create_album/$', views.create_album, name='create_album'), url(r'^(?P<album_id>[0-9]+)/create_song/$', views.create_song, name='create_song'), url(r'^(?P<album_id>[0-9]+)/delete_song/(?P<song_id>[0-9]+)/$', views.delete_song, name='delete_song'), url(r'^(?P<album_id>[0-9]+)/favorite_album/$', views.favorite_album, name='favorite_album'), url(r'^(?P<album_id>[0-9]+)/delete_album/$', views.delete_album, name='delete_album'), ] urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', … -
Celery got neo4j connecting error when run worker on vagrant
I'm using vagrant box ubuntu 14.04 to develop at local. But in vagrant environment, when run celery worker, I got this error: [2017-10-17 10:33:15,188: ERROR/MainProcess] Task insurance.tasks.neo_update_insurance_package[6713980d-1b76-4dc0-9a58-d2ef4ed7f68a] raised unexpected: ServiceUnavailable("Cannot acquire connection to Address(host='127.0.0.1', port=7687)",) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/vagrant/my_project/my_app/tasks.py", line 78, in neo_update_package save_general_node(pk, Package, NeoPackage) File "/vagrant/meddy_site/core/neo4j_utils.py", line 27, in save_general_node neo_obj = neo_object_type.nodes.get_or_none(id=pk) File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 523, in get_or_none return self.get(**kwargs) File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 507, in get result = self.query_cls(self).build_ast()._execute() File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 411, in _execute results, _ = db.cypher_query(query, self._query_params) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 28, in wrapper return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 90, in cypher_query self.set_connection(self.url) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 61, in set_connection max_pool_size=config.MAX_POOL_SIZE) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/api.py", line 124, in driver return driver_class(uri, **config) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/direct.py", line 65, in __init__ pool.release(pool.acquire()) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/direct.py", line 44, in acquire raise ServiceUnavailable("Cannot acquire connection to {!r}".format(self.address)) ServiceUnavailable: Cannot acquire connection to Address(host='127.0.0.1', port=7687) I tried to edit the Vagrantfile and neo4j.conf settings like below but it didn't work: Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" client_vagrantfile = File.expand_path('../Vagrantfile.custom', __FILE__) if … -
Django: No m2m_changed signal when one side of a many-to-many is deleted?
I want to trigger some behaviour whenever a many-to-many relationship changes, but I'm unsure what signal setup is best for capturing changes to that relationship that come about due to the deletion of one side of the relationship. m2m_changed does not seem to fire in this case, nor do the regular post_save and post_delete signals seem to be applicable to the through model? My current solution is to listen to pre_delete on the models which compose either side of the relationship and then clear the relationship within that signal in order to trigger a m2m_changed. I'm surprised that I have to do this though, and feel I've got something wrong. What am I missing here? And if I am not missing anything why is this necessary (ie why is no such signal fired by default)? Code example: class ResearchField(models.Model): name = models.CharField(unique=True, max_length=200) class Researcher(models.Model): name = models.CharField(max_length=200) research_fields = models.ManyToManyField(ResearchField, blank=True) @receiver(m2m_changed, sender=Researcher.research_fields.through) def research_fields_changed(sender, instance, action, **kwargs): # need to do something important here print('m2m_changed', action) volcanology = ResearchField.objects.create(name='Volcanology') researcher = Researcher.objects.create(name='A. Volcanologist') researcher.research_fields.add(volcanology) >>> m2m_changed pre_add >>> m2m_changed post_add This m2m_changed signal fires as expected when the relationship is removed from either side: researcher.research_fields.remove(volcanology) # or equally … -
Django/Wagtail trying to create generic child classes
I'm working on a Django/Wagtail app and I'm trying to create generic, reusable components in my models. I'm trying to follow the way the built-in Image classes work since they can be attached to any other object type. However I keep getting an error: AttributeError: 'ReverseSingleRelatedObjectDescriptor' object has no attribute 'related' Here is my code for the models: class DownloadObject(models.Model): title = models.CharField(max_length=255) description = RichTextField(blank=True) download_link = models.URLField() cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) class Meta: abstract = True class Download(DownloadObject): admin_form_fields = ( 'cover_image', 'title', 'description', 'download_link', ) class Container(Page): body = RichTextField(blank=True) downloads = models.ForeignKey( 'Downloads', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('downloads', label="downloads"), ] -
How would my template look like given this Django model?
I am trying to make a simple dental chart interface but having troubles making the template. I guess my challenge started with how I designed my previous models. A dental chart is composed of 32 teeth, each tooth has its own attributes. Below is my model: class DentalChart(models.Model): patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE) date = models.DateField() dentist = models.CharField(max_length=100) PERIODONTAL_CHOICES = ( ('Gingivitis', 'Gingivitis'), ('Early Periodontitis', 'Early Periodontitis'), ('Moderate Periodontitis', 'Moderate Periodontitis'), ('Advanced Periodontitis', 'Advanced Periodontitis'), ('N/A', 'N/A') ) periodontal_screening = MultiSelectField(choices=PERIODONTAL_CHOICES, default='') OCCLUSION_CHOICES = ( ('Class(Molar)', 'Class(Molar)'), ('Overjet', 'Overjet'), ('Overbite', 'Overbite'), ('Midline Deviation', 'Midline Deviation'), ('Crossbite', 'Crossbite'), ('N/A', 'N/A') ) occlusion = MultiSelectField(choices=OCCLUSION_CHOICES, default='') APPLIANCES_CHOICES = ( ('Orthodontic', 'Orthodontic'), ('Stayplate', 'Stayplate'), ('Others', 'Others'), ('N/A', 'N/A') ) appliances = MultiSelectField(choices=APPLIANCES_CHOICES, default='') TMD_CHOICES = ( ('Clenching', 'Clenching'), ('Clicking', 'Clicking'), ('Trismus', 'Trismus'), ('Muscle Spasm', 'Muscle Spasm'), ('N/A', 'N/A') ) TMD = MultiSelectField(choices=TMD_CHOICES, default='') class Tooth(models.Model): chart = models.ForeignKey(DentalChart, on_delete=models.CASCADE) tooth_id = models.CharField(max_length=2) CONDITIONS_LIST = ( ('', ''), ('Present Teeth', 'P'), ('Decayed', 'D'), ('Missing due to Carries', 'M'), ('Missing (Other Causes)', 'Mo'), ('Impacted Tooth', 'Im'), ('Supernumerary Tooth', 'Sp'), ('Root Fragment', 'Rf'), ('Unerupted', 'Un') ) condition = models.CharField(max_length=30, choices=CONDITIONS_LIST, default='') RESTORATIONS_LIST = ( ('', ''), ('Amalgam Filling', 'A'), ('Composite Filling', 'Co'), ('Jacket Crown', 'Jc'), ('Abutment', … -
How to bring data from selected user to update it
I'm studying django and trying to make a simple CRUD, following the djangoGirls tutorial. But unfortunatelly they don't show how to UPDATE data. I'm already Inserting, Reading/listing how may I Delete and Update? I listed the users with an link to edit it: {% extends 'bloodDonation/master.html' %} {% block content %} <h1 class="center">LIST DONATORS<h1> <ul> {% for donator in donators %} <div class="row"> <div class="container"> <div class="col s12 blue-grey lighten-5 border_lighten"> <div class="col s12 m12 padding_normal"> {{ donator.name }} <div id="icon" class="right"> <a href="{% url 'edit_donator' %}" class="tooltipped" data-position="right" data-delay="50" data-tooltip="Editar Dados""> <i class="material-icons">edit</i></a> </div> </div> </div> </div> </div> {% endfor %} </ul> {% endblock %} As you can see, I have a a tag pointing to edit_donator url. How may I pass the ID/data of the selected/clicked user so I can pull his data and throw it inside the form? Form creation: class EditDonatorForm(forms.ModelForm): class Meta: model = Donator fields = [ 'name', 'age', 'email', 'phone', 'bloodType', 'observation' ] How may I get data from database and already place it inside form so I can perform an Update? -
Map over AForm to change form "name" settings
I am trying to implement something akin to Django's formsets, where you have multiple nested forms inside a single main form. type FormsetCount = Int mainForm :: AForm FormsetCount mainForm = areq intField "formset-count" (Just 0) subForm :: AForm Bool subForm = areq boolField "foo" Nothing -- later ... ((result, formW), _) <- lift $ runFormPost $ renderDivs $ mainForm Nothing formsetWidgets <- case result of FormSuccess count -> do for [1..count] $ \i -> lift $ runFormPost $ renderDivs $ subForm Nothing _ -> pure [] In this example, the generated ids for mainForm and subForm would obviously clash. Combining them first into a single form and therefore get fresh ids is not an option, because I want to be able to generate more formsets dynamically from javascript. My idea is to render each subForm independently of the mainForm, but as part of the same <form>. To do this, I would suffix (or prefix) all fields in the subForm with a running integer (up to "formset-count"). This would isolate each subform from the fields in it's parent and would allow me to dynamically (via JS) add more formset items. Now, the problem I am facing is that in order … -
Django new URL not working
So I'm trying to access a URL, http://localhost:8000/calc, but it gives me this error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='home'] ^calc/ The current path, calc, didn't match any of these. This is what I currently have for mysite URL and secondapp URL: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), url(r'^calc/',include('secondapp.urls')), ] from django.conf.urls import url from secondapp.views import CalcPage urlpatterns = [ url(r'calc/', CalcPage.as_view(), name='calc'), ] -
django global variable across web pages?
How to pass a variable between web pages/functions? For example, let's say when I visit webpage "test3.html", I'd like to get the sum of variables a_test1 and a_test2, which are "global" variables which increased as visiting test1.html and test2.html. test1.html, test2.html and test3.html could be visited multiple times and independently. The following code doesn't work as it is, but it would if I can somehow make a_test1 and a_test2 global variables? Can that be done? Another option maybe passing these variables by the "request" parameter? Can it be done that way? urlpatterns = [ url(r'^test1/$', views.test1), url(r'^test2/$', views.test2), url(r'^test3/$', views.test3), ] in views.py: def test1(request): a_test1=1+a_test1 return render(request,'test1.html',{'a_test1': a_test1}) #other stuffs def test2(request): a_test2=1+a_test2 return render(request,'test2.html',{'a_test2': a_test2}) #other stuffs def test3(request): a_test3=a_test1+a_test2 return render(request,'test3.html',{'a_test3': a_test3}) #other stuffs -
Django - show an image when a submit button is clicked
I would like to show an image when a user clicks a submit button. I want to just change the image, not render the whole page. What is the best way to do this? -
In django-taggit, is there a way to get all tags assoicated to a model?
I know how to get all tags, but let's say the tags are connected to lots of different models. Somehow I just want to extra the tags that is attached to a model not ALL tags. Is this possible? I know that I can do it in reverse, get the model then get all the tags, but I have LOTS rows in that model and if I try it this way, I have to get all rows then loop through all rows to get queryset of the tags But all I want is get all the tags attached to the model and count the tags. I do not require to know which row of the model is using this tag. Thanks in advance for any help. -
Digital Ocean: One Click Django Won't Route My Domain, Bad Gateway
The one click django with ubuntu 16, nginx, and gunicorn is not routing my domain name. When I type the IP address into the address bar it works but when when I use the domain I get 502 Bad Gateway nginx/1.10.3 (Ubuntu). Looking at the nginx error log I see: 2017/10/16 19:05:18 [error] 23017#23017: *80 upstream prematurely closed connection while reading response header from upstream, client: redacted server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/" I followed the steps here: https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars#registrar-godaddy and here: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-host-name-with-digitalocean But I must have done something wrong. Anyone have any ideas how to solve this. I am brand new to DO, Django, and really web dev. -
search autocomplete with django haystack
I use haystack like search engine in my django application. My search engine only with solid word. Example: I store pictures with different informations. In author_full_name field, I have 'serenmovan'. If I put 'serenmovan' in the search engine it works but I put 'ser' or 'mov' no results. Same thind for the other fields. here is my search_indexes.py : class PictureIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) author = indexes.CharField(model_attr='author', boost=1.5) author_full_name = indexes.CharField(boost=1.5) artist_location = indexes.CharField() uid = indexes.CharField(model_attr='uid') name = indexes.CharField(model_attr='name') slug = indexes.CharField(model_attr='slug') description = indexes.CharField(model_attr='description') orientation = indexes.CharField(model_attr='orientation') price_range = indexes.CharField(model_attr='price_range') thumbnail = indexes.CharField(model_attr='thumbnail') thumbnail_landscape = indexes.CharField(model_attr='thumbnail_landscape') thumbnail_portrait = indexes.CharField(model_attr='thumbnail_portrait') preview_large = indexes.CharField(model_attr='preview_large') created = indexes.DateTimeField(model_attr='created') tags = indexes.MultiValueField() admin_tags = indexes.MultiValueField(boost=2) google_tags = indexes.MultiValueField(boost=2) def get_model(self): return Picture def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().active_objects.filter(created__lte=datetime.datetime.now()).select_related() def prepare_tags(self, obj): return [tag.name for tag in obj.tags.all()] def prepare_admin_tags(self, obj): return [tag.name for tag in obj.admin_tags.all()] def prepare_google_tags(self, obj): return [tag.name for tag in obj.google_tags.all()] def prepare_author_full_name(self, obj): return obj.author_full_name def prepare_artist_location(self, obj): try: return obj.author.artistprofile.address.city except: pass` -
Setting Django model primary key field for translation with django-modeltranslation
I've searched in readthedocs.io but didn't find a solution. I'm using django-modeltranslation to translate my models in my Django project. Now, I'm trying to translate a model that has only one field, that is a primary key. models.py: class Gender(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name translation.py: class GenderTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Gender, GenderTranslationOptions) Running python manage.py makemigrations I'm having the following error: SystemCheckError: System check identified some issues: ERRORS: experiments.Gender.name_en: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. experiments.Gender.name_pt_br: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. It looks like it's trying to create name_en and name_pt_br fields as primary keys, what it's not the case because only name field is supposed to be primary key. What can we do in a case like this. The docs don't refer to creating that fields manually, nor a way of defining fields attributes in translation.py, at least until I know from them. -
Django and mod_wsgi installation suddenly stopped working
I have a script which I use to install my application on a virtual machine using django 1.9.6 and mod_wsgi. It use to work fine for at least a year and then after a few months I didn't use it - it's suddenly not working. I am always installing on a clean ubuntu trusty image and I didn't make any changes. So my guess is that apt-get is installing a different version of libapache2-mod-wsgi now. sudo apt-get update sudo apt-get install -y python-pip sudo pip install django=1.9.6 sudo apt-get -y install apache2 libapache2-mod-wsgi ... When I try to run the application the apache server gives the error: mod_wsgi (pid=8486): Target WSGI script '/root/geosearch_app/geosearch_project/geosearch_project/wsgi.py' cannot be loaded as Python module. I hope to solve this without actually changing anything except the installation script and that should work since it worked before. Any advice? -
How to send an email with excel file as attachment using django
I have an excel file in a specific folder and would like to send it via email. To do this, was trying to use openpyxl My code : fileToAttach = load_workbook(pathToFile) msg = EmailMultiAlternatives(subject, text_content, from_email, ['myMail@gmail.com']) msg.attach_alternative(html_content, "text/html") msg.attach("Report.xlsx", fileToAttach, "application/vnd.ms-excel") msg.send() But it returns an error: 'Worksheet -1 does not exist.' Could you tell me what I am doing wrong ? Thanks, -
Get data from two django models
My models look like this: class UserDevice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) activation_date = models.DateTimeField(default=timezone.now, null=False) friendly_name = models.CharField(max_length=20, null=True, blank=True) is_owner = models.BooleanField(null=False, default=False) is_admin = models.BooleanField(null=False, default=True) is_alerts_enabled = models.BooleanField(null=False, default=True) timeStamp = models.DateTimeField(auto_now = True, null=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) token = models.TextField(null=False, blank=True) first_name = models.TextField(null=True, blank=True) last_name = models.TextField(null=True, blank=True) timeStamp = models.DateTimeField(auto_now = True, null=False) I need to get device, user, is_alerts_enabled, is_admin, is_owner from UserDevice and first_name, last_name, token from userProfile. This is what I have so far and it gives me what I need from userdevice but I can't figure out how to add the userprofile stuff. nonOwners = UserDevice.objects.filter(device=device, is_owner=False) if nonOwners is None: return errormsg('non nonOwners found for this device') nonOwnersArray=[] for nonOwner in nonOwners: nonOwner_data = model_to_dict(nonOwner, fieldlist=( 'device.serial', 'user.email', 'is_alerts_enabled', 'is_admin', 'is_owner', ), rename={ 'device.serial': 'serial', 'user.email': 'email'}) nonOwnersArray.append(nonOwner_data) Any help would be greatly appreciated. Thanks! -
Django - usage of redirect_to_login
I want to use redirect_to_login in my view. For some reason, I get redirected to login twice (and therefore the URL is malformed). My TestView(View) looks like this (relevant part): def dispatch(self, request, *args, **kwargs): if not self.test_func(): if self.redirect_to_login: return redirect_to_login(self.request.get_full_path()) else: return HttpResponseForbidden() My urls.py (relevant part): url(r'^test/$', TestView.as_view()), When I type localhost:8000/test/ into my browser, I end up at http://localhost:8000/login/?next=/%3Fnext%3D/test/ instead of expected http://localhost:8000/login/?next=/test/ Any ideas what the problem might be? In case you need more files, just please ask.