Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom command to upload photo to Photologue from within Django shell?
I have successfully employed Photologue to present galleries of regularly-created data plot images. Of course, now that the capability has been established, an obscene number of data plots are being created and they need to be shared! Scripting the process of uploading images and adding them to galleries using manage.py from the Django shell is the next step; however, as an amateur with Django, I am having some difficulties. Here is the custom command addphoto.py that I have currently developed: from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from photologue.models import Photo, Gallery import os from datetime import datetime import pytz class Command(BaseCommand): help = 'Adds a photo to Photologue.' def add_arguments(self, parser): parser.add_argument('imagefile', type=str) parser.add_argument('--title', type=str) parser.add_argument('--date_added', type=str, help="datetime string in 'YYYY-mm-dd HH:MM:SS' format [UTC]") parser.add_argument('--gallery', type=str) def handle(self, *args, **options): imagefile = options['imagefile'] if options['title']: title = options['title'] else: base = os.path.basename(imagefile) title = os.path.splitext(base)[0] if options['date_added']: date_added = datetime.strptime(options['date_added'],'%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.UTC) else: date_added = timezone.now() p = Photo(image=imagefile, title=title, date_added=date_added) p.save() Unfortunately, when executed, it results in an exception: django.core.exceptions.SuspiciousFileOperation: The joined path (/home/user/cache/image.png) is located outside of the base path component (/home/website/mywebsite/media) Obviously, a copy of the image file was not put in the the media/ … -
type object 'SubscriptionList' has no attribute '_meta'
Good afternoon. While trying to create an object of SubscriptionList model. I've got this error. I did a research on this topic but haven't found a relative answer. Traceback: File "D:\PyDocs\taskagain\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "D:\PyDocs\taskagain\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\PyDocs\taskagain\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\edit.py" in get 213. return super(BaseCreateView, self).get(request, *args, **kwargs) File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\edit.py" in get 174. return self.render_to_response(self.get_context_data()) File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\edit.py" in get_context_data 93. kwargs['form'] = self.get_form() File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\edit.py" in get_form 44. form_class = self.get_form_class() File "D:\PyDocs\taskagain\lib\site-packages\django\views\generic\edit.py" in get_form_class 132. return model_forms.modelform_factory(model, fields=self.fields) File "D:\PyDocs\taskagain\lib\site-packages\django\forms\models.py" in modelform_factory 558. return type(form)(class_name, (form,), form_class_attrs) File "D:\PyDocs\taskagain\lib\site-packages\django\forms\models.py" in __new__ 261. apply_limit_choices_to=False, File "D:\PyDocs\taskagain\lib\site-packages\django\forms\models.py" in fields_for_model 144. opts = model._meta Exception Type: AttributeError at /blogs/1/add_to_subscription/ Exception Value: type object 'SubscriptionList' has no attribute '_meta' Models class SubscriptionList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='subscription_list') blogs_in_subscription = models.ManyToManyField(Blog, related_name='in_subscription_lists', blank=True) def __str__(self): return "%s subscription list" % self.user.username Views class AddBlogToSubList(CreateView): model = SubscriptionList fields = ['user', 'blogs_in_subscription'] template_name = 'blog/add_blog_to_sub_list.html' success_url = reverse_lazy('blog:blog-list') def form_valid(self, form): form.instance.blogs_in_subscription = Blog.objects.get(pk=self.kwargs['blog_pk']) form.instance.user = self.request.user return super(AddBlogToSubList, … -
Why isn't my regex_validator working in formset without overriding clean method?
My goal The following code is supposed to display a formset containing a certain number of TravellerForm then validate them and save the CompleteSubscription and his Traveller associated. Only the main contact - first form - is supposed to have a mendatory phone number at the E.164 format validated by a regex. Results of the following code It correctly suppress the phone number field for other forms than the first and properly displays the fields I need. Then, when I submit my form , the travellers are saved in my database, including the first although I put an invalid phone number in it. The subscription is correctly saved. For fix this issue, I've overrided the clean_phone_number method, it seems working but it's giving me two errors and not only one as expected. Phone number must be in E.164 format. Ex: +33123456789 Make sure that this value has a maximum of 16 characters (currently 143). My problematic Why does I need to override the clean_phone_number method to display the errors, aren't formsets supposed to call the clean method of theirs forms before saving ? If it so, why is my clean_phone_number method called when I override it ? I'm by the … -
I wanna connect Swift&Django in sending files
I wanna connect Swift & Django in sending files. I wanna send images from Swift to Django server. Now, my swift code is func myImageUploadRequest(){ let myUrl = NSURL(string:"http://localhost:8000/accounts/upload_save/"); let request = NSMutableURLRequest(url:myUrl! as URL) request.httpMethod = "POST" let boundary = generateBoundaryString() request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let imageData = UIImageJPEGRepresentation(self.myImageView.image!, 1) if(imageData==nil) { return; } var name = "" if let text = textField.text { name = text } let postString = "name=\(name)" request.httpBody = postString.data(using: .utf8) //myActivityIndicator.startAnimating(); let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if error != nil { print("error=\(error)") return } print("******* response = \(response)") let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print("****** response data = \(responseString!)") DispatchQueue.main.async(execute: { }); } task.resume() } on the other hand,my Django code is def upload_save(request): photo_id = request.POST.get("p_id", "") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") photo_obj.image = files[0] # photo_obj.image2 = files[1] # photo_obj.image3 = files[2] photo_obj.save() # return render(request, "registration/accounts/photo.html") photos = Post.objects.all() context = { 'photos': photos, } return render(request, 'registration/accounts/photo.html', context) Now,Django has an error, IndexError at /accounts/upload_save/ list index out of range . Traceback says photo_obj.image = files[0] ... ▼ Local vars Variable Value files [] … -
Django reverse error [duplicate]
This question already has an answer here: What is a NoReverseMatch error, and how do I fix it? 1 answer Iam working on this project for listing patient details and updating them getting error Reverse for 'update_patient' not found. 'update_patient' is not a valid view function or pattern name. help to fix the error patient.html {% extends 'patient/base.html' %} {% block content %} <p>Patient: {{ patient }}</p> <p>Entries: </p> <p>Update Patient:</p> <p> <a href="{% url 'patient:new_entry' patient.id %}">add new entry</a> </p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> <p> <a href="{% url 'patient:edit_entry' entry.id %}">edit entry</a> </p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> <a href="{% url 'patient:update_patient' patient.id %}">update</a> <a href="{% url 'patient:new_patient' %}">Add a new patient:</a> {% endblock content %} views.py def update_patient(request, patient_id): patient = Patient.object.get(id=patient_id) if request.method != 'POST': # Initial request; pre-fill form with the current entry. form = PatientForm(instance=patient) else: # POST data submitted; process data. form = PatientForm(instance=patient, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('patient:patients', args=[patient.id])) context = {'patient': patient, 'form': form} return render(request, 'patient/update_patient.html', context) urls.py url(r'^update_patient/(?P<patient_id>\d+)/$', views.update_patient, name='update'), update_patient.html {% extends … -
What framework/packages/modules should I use for this project?
I'm a very amateur high-school programmer so please excuse my ignorance! I have to create a school project for computer science. It's basically a voting platform for different questions raised by students, so the following must be enabled: - A login/logout function - An admin function that can delete/approve questions - For each question the following must be included: - a description - the email of the user that asked the question My understanding of python through the internet is really confusing me. This needs to be a GUI-based application for which people can also vote for or against these questions to assess their importance. My question is, should I be using something like Django or flux to enable this app online? Or should I just be using some sort of database like MySQL? It would really help me out if someone could quickly guide me in the right direction - Thanks! (Something that would allow this program to be made quickly would be ideal!) -
How do I manage stateful data for database objects in Django/Python?
In a project I have to process a lot of order (as in purchase) data. Together with the order data, I have to generate state information that somehow has to be cached. I'm unsure about good ways of managing such data. Models class Order: buyer_name = TextField() class OrderItem: order = ForeignKey(Order) quantity = IntegerField() name = TextField() Requirements The buyer name is being checked for validity by looking at the characters and querying an external API. It's also checked if there are multiple orders from the same buyer (→ duplicates). The user must be able to filter orders according to their check results. Last, but not least, every order has a condition that's directly dependent on check results: Buyer name is valid, no duplicate order: Order condition is OK. Buyer name is valid, duplicate order: Order condition is Warning. Buyer name is invalid: Order condition is Error. Issue My question: What's a good way of storing information such as conditions or check results? I might also have to query for the total quantity count per order without joining and aggregating the item quantities all the time (performance). -
Django Channels - connected isn't executed
Hi i am copying parts of the github project multichat from the creator of django channels. I am making slight changes to the code like not using jquery, renaming of some consumers and such. I have literally no errors when running the code however when i join the page and the JS creates a websocket it says simply [2017/08/03 13:13:48] WebSocket HANDSHAKING /chat/stream [127.0.0.1:37070] [2017/08/03 13:13:48] WebSocket CONNECT /chat/stream [127.0.0.1:37070] Which one would think is fine ofcourse... However i'n my connect function i have a print("********CONNECTED**********"), wich is nowhere to be seen in the console. It simply doesn't run the function i have told it to when someone connects but it still says the person connected and it throws no errors. This is the main routing: channel_routing = [ include("crypto_chat.routing.websocket_routing", path=r"^/chat-stream/$"), include("crypto_chat.routing.chat_routing"), ] Routing from app: websocket_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] chat_routing = [ route("chat.receive", chat_send, command="^send$"), route("chat.receive", user_online, command="^online$"), Connect Consumer: @channel_session_user_from_http def ws_connect(message): # only accept connection if you have any rooms to join print("******************CONNECT*************************''") message.reply_channel.send({"accept": True}) # init rooms - add user to the groups and pk num to the session message.channel_session['rooms'] = [] for room in Room.objects.get(users=message.user): room.websocket_group.add(message.reply_channel) message.channel_session['rooms'].append(room.pk) print(message.channel_session['rooms']) Heres … -
Django model nested serializer
I have the model structure like below class BaseProduct: id = models.CharField(max_length=15) name = models.CharField(max_length=20) class Product base_product = ForeigKey(BaseProduct) name = models.CharField(max_length=20) class Condition: category = models.ForeignKey(Product, related_name='allowed_product') check = models.IntegerField(default=0) allow = models.PositiveSmallIntegerField(default=1) The query: Product.objects.filter(condition__allow=1, condition__check=1) I want format something like below Base Product and inside that list of products based on allow and check filter [ { "name": "BaseProduct 1", "products": [ { "name": "TV", }, {}, .... ] }, ........ ] -
My development server of DJango doesn't work
I'm following the first tutorial of Django docs to run my development server, but in the moment to try to access to the server in http://127.0.0.1:8000 it fails to connect. The browser simply says that it couldn't connect to the server. This is what outputs the console when I put the command: System check identified no issues (0 silenced). August 03, 2017 - 14:31:04 Django version 1.11.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003E14730> Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\comma nds\runserver.py", line 149, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Program Files\Python36\lib\site-packages\django\core\servers\basehttp .py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Program Files\Python36\lib\site-packages\django\core\servers\basehttp .py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "C:\Program Files\Python36\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Program Files\Python36\lib\wsgiref\simple_server.py", line 50, in ser ver_bind HTTPServer.server_bind(self) File "C:\Program Files\Python36\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Program Files\Python36\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 3: invalid continuation byte I'm using python 3.6.1 and django 1.11.4, on Windows … -
Django - Make private page by user
I'm currently developping a micro_blog to learn Django, and i didn't find the way to make a page only visible by one User. ex: i want that each user got a private page on /profile/username/private . How sould i do to make that only the user "username" got access to it? For the moment, every-user can access to this page by typing the url. I already put the " @login_required " on head of my func, but logged user can still access to the page. Hope that you'll understand my issue, Kind Regards, -
Django ModelForm ManyToManyField initial value
I'm using Django 1.11.2 to build ab website. I use ModelForms to edit my model instances on my website. Every field of the form gets the fitting value of the instance I want to edit via 'initial' in my view. It works fine for all fields except ManyToManyFields. The relevant code looks like this: models.py: class model1(models.Model): name = models.CharField(max_length=45, blank=False, null=False) class model2(models.Model): name = models.CharField(max_length=45, blank=False, null=False) relation = models.ManyToManyField(model1) the ModelForm in forms.py: class model2_form(forms.ModelForm): class Meta: model = model2 fields = '__all__' and the view I use to edit model2 intances: def model2_edit(request, objectid): link = 'Model2' model2_inst = model2.objects.get(id=objectid) form = model2_form(initial={'name': model2_inst.name, 'relation': ???}) if request.method == 'POST': f = model2_form(request.POST, instance=model2_inst) if f.is_valid(): f.save() return HttpResponseRedirect('/model2') return render(request, "edit_db.html", {"form": form, "link":link}) Everytime I edit an instance of model2 via the ModelForm, the 'relations' of the instance that already exist aren't preselected ('initial' isn't working). If I save the form like this without selecting the relations again, they get deleted and that instance of model2 has no relations anymore. At the place of the '???' in my code I tried many ways to get those relations already selected in the form, but I … -
Add Orderable Model to custom settings in Wagtail CMS
I'd like to organize common site elements in an appropriate place. For example, site footer elements. As far as I know Site settings is a good approach. Everything was going OK until I decided to add Orderable model there to be able to build kind of iterable list with some items contain attributes "text", "URL link". I encountered a trouble, usual way I used to apply in page models didn't help me. Here is the code: @register_setting class SiteFooterSettings(BaseSetting): class Meta: verbose_name = _('Footer Settings') blog_title = models.CharField(_('Title'), max_length=50, null=True, blank=True) blog_article_button_text = models.CharField(_('Article Button Text'), max_length=50, null=True, blank=True) panels = [ MultiFieldPanel( heading=_('Our Blog'), children=[ FieldPanel('blog_title'), FieldPanel('blog_article_button_text'), ], classname='collapsible' ), MultiFieldPanel( heading=_('Blog Menu Items'), children=[ InlinePanel('blog_menu_items', label=_('Blog Menu Item')), ], classname='collapsible' ), ] class SettingsBlogMenu(Orderable): page = ForeignKey('ds.SiteFooterSettings', related_name='blog_menu_items') blog_menu_item = models.CharField(_('Item'), max_length=70, null=True, blank=True) blog_menu_item_url = models.CharField(_('URL'), max_length=70, null=True, blank=True) panels = [ FieldPanel('blog_menu_item'), FieldPanel('blog_menu_item_url') ] Usually I use ParentalKey to bind such kind of list to a page. Though during migration Django throw an error and advises to change it to Foreign key. Finally I get "KeyError at /admin/settings/ds/sitefootersettings/2/ 'blog_menu_items' What's wrong here? Thanks. -
Django import export: Django ignore ForeignKeyWidget in admin panel import
Does someone has example with using ForeignKeyWidget. I need to pass value from FK table and this library need to find ID by that value and write it into database. Is it possible to do? Thanks! -
How to send a request for token from graphql to python api?
I need to send an Authorization request from graphql to a python API so that I can communicate with the Python API. In this request, I need to send the user's username and password with Authorization header and receive token that will be used in further communication. I dont know how to send this request. I have created the schema to communicate otherwise but can't figure out how to add this part. Here is the rest of my code : Schema.js import { GraphQLSchema, GraphQLObjectType, GraphQLString, } from 'graphql'; import fetch from 'node-fetch'; const BASE_URL = 'http://localhost:9000/api'; function getUserByURL(relativeURL) { return fetch(`${BASE_URL}${relativeURL}`) .then(res => res.json()) .then(json => json.user) } const UserType = new GraphQLObjectType({ name: 'User', description: '...', fields: () => ({ firstName: { type: GraphQLString, resolve: (user) => user.first_name }, lastName: { type: GraphQLString, resolve: (user) => user.last_name }, email: {type: GraphQLString}, username: {type: GraphQLString}, blockchain_address: {type: GraphQLString}, }), }); const QueryType = new GraphQLObjectType({ name: 'Query', description: '...', fields: () => ({ user: { type: UserType, args: { id: {type: GraphQLString,} }, resolve: (root, args) => getUserByURL(`/users/${args.id}/`), } }) }); export default new GraphQLSchema({ query: QueryType, }); index.js import express from 'express'; import graphQLHTTP from 'express-graphql'; import schema … -
What is doing __str__ function in Django?
I'm reading and trying to understand django documentation so i have a logical question. There is my models.py file from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=255) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return self.name class Post(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline What is doing here each str function in each class ? What is the reason i need those functions in it ? -
Pre-selecting all the checkboxes when using django.forms.ModelMultipleChoiceField
I want to show pre-selected options to the user (since they are more likely to remove a few items rather than add all the items, which is a hassle). Is it possible to pre-select all the checkboxes rendered by a ModelMultipleChoiceField? Would this be done in the model, or the form? I'd prefer not to use javascript to do it. I can't find any documentation about pre-selecting for ModelMultipleChoiceField and official documentation is scant: https://docs.djangoproject.com/en/1.11/ref/forms/fields/#modelmultiplechoicefield def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['my_items'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=models.MyItem.objects.all(), initial=self.instance.MyItem.all()) -
AttributeError: Can't get attribute on <module '__main__' from 'manage.py'>
def getNer(text): with open('chunker.pkl', 'rb') as pickle_file: chunker = pickle.load(pickle_file) return chunker.parse(pos_tag(word_tokenize(text))) Running this function works fine But when I include this function in my Django Project I get the following error chunker = pickle.load(pickle_file) AttributeError: Can't get attribute 'NamedEntityChunker' on <module '__main__' from 'manage.py'> The object being pickled is class NamedEntityChunker(ChunkParserI): def __init__(self, train_sents, **kwargs): assert isinstance(train_sents, Iterable) self.feature_detector = features self.tagger = ClassifierBasedTagger( train=train_sents, feature_detector=features, **kwargs) def parse(self, tagged_sent): chunks = self.tagger.tag(tagged_sent) iob_triplets = [(w, t, c) for ((w, t), c) in chunks] return conlltags2tree(iob_triplets) Im using the latest version of Django and Python3 -
foreign key and primary key relation in models in django
# these models are in two different applicaltion in django, I had created # the primary key and foreign key relation between the two tables but still # the output is not desired output... class User(models.Model): user_name = models.CharField( max_length=255, default=None) email = models.CharField( max_length=255, default=None) mobile_number = models.IntegerField( default=0) created_on = models.DateTimeField( auto_now=True) class Todo(models.Model): title = models.CharField( max_length=255, default=None) description = models.CharField( max_length=255, default=None) created_on = models.DateTimeField(auto_now=True) user = models.ForeignKey('Account.User',on_delete=models.CASCADE) suppose i created a entry in the User table and its id assigned is 1 but i can also create a entry in the Todo table with a user_id = 2 (which is not a valid value according to the rule ) and the entry is created. Can any one suggest why?? -
How to download csv file and return to the page using Python and Django
I need some help. I am generating the csv file and downloading it but after download it need to return to the other page using Python but its not happening like this. I am explaining my code below. if request.method == 'POST': param = request.POST.get('param') report = Reactor.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=status.csv' writer = csv.writer(response) writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' writer.writerow([rec.rname, status, rec.date]) return response u = urllib.URLopener() f = u.open(param) open("down.txt","w").write(f.read()) pers = User.objects.get(pk=request.session['id']) root = [] user_name = pers.uname count = 1 root.append( {'username': user_name, 'count': count }) return render(request, 'plant/home.html', {'user': root, 'count': 1}) Here actually user input is one URL e.g https://pypi.python.org/pypi/autopep8 like this . Here my requirement is first all required data will fetch from database and write inside one csv file and download it. secondly the user provided URL content will be written on a text file and download it finally the required page will be redirected. In my case after downloading the csv file only the page is remaining same means not redirecting. Please help me. -
how to skip empty get parameter in django
I have URL like www.example.com/search?param1=abc&param2=xyz&param3=, currently what I'm doing in views is something like this. if ((request.GET.get('param1')) or (request.GET.get('param2')) or (request.GET.get('param3'))): if request.GET.get('param1'): value1 = request.GET.get('param1') if request.GET.get('title'): value2 = request.GET.get('param2') if request.GET.get('location'): value3 = request.GET.get('param3') api_url = `www.api-end-point.com?p1=value1&p2=value2&p3=value3&format=json` But you guys can see param3 is empty ,and to hit api i need to skip empty parameters. So My question is how can i get all the set parameter from url in GET request in django. -
Django won't start after downloading anaconda with Python3
So I downloaded Anaconda to get started with Jupyter from here. I downloaded the 3.5 but I use 2.7 for all my other Python projects. The Problem is that there seems to be a conflict now. When I want to run Django I get an error that its not installed like: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I found this SO Question but I really don't feel like reinstalling everything, I would rather delete the Python3 Folder/Anaconda. Is there an easy way to get around this? I would like to test python 3.5 but if I have to rewrite/install everything in Django the tradeoff is not given. -
In Django using ORM., how to do multiple self join on different values
Could any one help me to how to write multiple self join on different values in Django using ORM ? For example., We have two tables. (1) projects (2) project_tab_status tables as picture I have wrote the query as below and not able to access the second join fields: Project.objects.filter(projecttabstatus__tab_status_type='processor1').annotate(tab_status_type_bv=Concat('projecttabstatus__tab_status_type', Value(''), Value('')),tab_status_bv=Concat('projecttabstatus__tab_status', Value(''), Value(''))).filter(projecttabstatus__tab_status_type='processor2').values('name', 'tab_status_type_bv', 'projecttabstatus__tab_status_type', 'projecttabstatus__tab_status', 'tab_status_bv', 'projecttabstatus__id').filter(id=698) but the second processor's values are not coming properly. Please help!! Thank you, Srinivas -
Design a system to send email at various times periodically?
I am working on a feature that will allow the user to configure an email to be sent a time he chooses. Once he has saved this configuration, email will be delivered at his chosen time (or around that time) daily until he/she deactivates that configuration or deletes that. There can be many such configurations having different times. So far I was doing something like this : Run a cron job every 10 minutes. Look for email configurations that are to be executed in (now - 10 minutes). Send those emails and update status logs. This used to work fine but has few pitfalls. Emails configured at intersection times like 02:00 were not sent sometimes. Due to a deployment or high CPU usage corn didn't run at all. In both the above scenarios, email that are missed won't be picked again in next 24 hours. How should I go forward to design a robust system that guarantees that all emails are sent. If it matters I am using Django and a linux machine. -
How to show mistakes with Django Serializer Validation?
I'm using Django with Django-Rest-Framework. If i run the serializer.is_valid() function I get False als result. Well, but how can i show the reason of False?