Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to daemonize celery in Centos 7?
I have a working system where email is sent using Redis + Celery. When I transferred the code to my Centos 7 server I installed Redis in the system and redis-cli ping returns PONG. I installed Celery in my virtualenv with pip and it works too because when I run venv/bin/celery multi start -A erp -l info I can send the emails from server. However, I cannot seem to daemonize celery. I have copied the contents of celeryd file from celery github and pasted it in /etc/init.d/celeryd file. I have also used the following configuration in /etc/default/celeryd/: CELERYD_NODES="worker1" CELERY_BIN="/home/michel/erp/venv/bin/celery" CELERY_APP="erp" CELERYD_OPTS="-A erp -l info" CELERYD_LOG_FILE="/home/michel/erp/var/log/celery/%n%I.log" CELERYD_PID_FILE="/home/michel/erp/var/run/celery/%n.pid" CELERYD_USER="michel" CELERYD_GROUP="michel" CELERY_CREATE_DIRS=1 The emails are not sent with this setup. Where can I start to look in order to find the problem? -
How to i open a link in the same page
Once i click on the link it opens in different page, I want to open it in the same html page. Following is the code: view.py def index(request): all_client = Clients.objects.all() return render(request,'update/index.html',{'all_client' : all_client}) def detail(request,album_id): client = get_object_or_404(Clients,pk=album_id) return render(request,'update/detail.html',{'client' : client}) index.html <body> <main> <nav id="nav"> <div class="innertube"> {% if all_client%} <h3> All the clients</h3> <ul> {% for client in all_client %} <li><a href="{% url 'update:detail' client.id %}" target="MainWindow">{{client.client_name}}</a></li> {% endfor %} </ul> {% else %} <h3> There is no such client</h3> </div> </nav> </main> <div class = "middle"> </div> </body> update/urls.py urlpatterns = [ # /music/ url(r'^$',views.index, name='index'), # /music/71/ url(r'^(?P<client_id>[0-9]+)/$',views.detail, name='detail'), ] The page is detail.html which i want to load in index.html -
Version controll for Django db.sqlite3 and .mo files
Should the following Django files be committed to GitHub (a Git server) in general? db.sqlite3 .mo files If the files are committed, I think setup can become easy. -
Picture not showing up on django
Hey i am trying to make clone of www.producthunt.com and while i was working on it i made model by which people can upload the picture of the product and title, body, etc.. While i made the models.py, views.py, and the detail.html[Page where the user gets redirected to his own post after posting] I found that the picture wasn't able to showup it had a image symbol and thats it! So, my views.py looks like: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): products = Product.objects return render(request, 'products/home.html',{'products':products}) @login_required(login_url="/accounts/signup") def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url = request.POST['url'] else: product.url = 'http://' + request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) else: return render(request, 'products/create.html',{'error':'All fields are required.'}) else: return render(request, 'products/create.html') def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'products/detail.html',{'product':product}) And the detail.html looks like: {% extends 'base.html' %} {% block content %} <div class="row"> <div class="col-2"> <img src="{{ product.icon.url }}" class="img-fluid" … -
Update multiple fields of member of an instance simultaneously
Suppose I have a User model and this model class modelEmployer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) employer_image = models.ImageField(upload_to='images/', default='') Now suppose i have an instance of modelEmployer and I would like to update the content of the user object in it. I know I can do this instance.user.email = new value instance.first_name = new value instance.save() I read we can run an update on a queryset (even if it returns one object). Now suppose I have a dictionary like this dict = {"first_name : "John","last_name" : "deer",....} How can i do something like this modelEmployer.object.filter(instance.user.email=dict["email"]).update(only update the user objects as I would like to update the user object of this field using directly the dictionary. Any suggestions ? -
"Could not find a version that satisfies the requirement" error for Django2 app installation
I'm newbie Python/Django programmer. I created an application based on Django 2.0 and packaged it according to the official document. Then I run the command: $ pip install --user django-easybuggy-0.1.tar.gz However, I get the error and cannot install. Processing ./django-easybuggy-0.1.tar.gz Collecting certifi==2018.1.18 (from django-easybuggy==0.1) Could not find a version that satisfies the requirement certifi==2018.1.18 (from django-easybuggy==0.1) (from versions: ) No matching distribution found for certifi==2018.1.18 (from django-easybuggy==0.1) Does anyone know the reason why the error occurs and how to fix it? In addition, I created requirements.txt by the command: $ pip freeze > requirements.txt Steps to reproduce: Download my application archive: $ wget https://github.com/k-tamura/easybuggy4django/releases/download/0.0.1/django-easybuggy-0.1.tar.gz Run the command: $ pip install --user django-easybuggy-0.1.tar.gz Best regards, -
bootstrap tabs change colour django when db changes with form submission/success
I am relatively new to django. Currently I have few bootstrap tabs and there is separate functionality in each tab. I have to change the colour of 1 tab with respect to changes done in any other tabs(like any db change) adding rows,fields with forms submission/success. Then i need to go to this tab which has changed its colour and upon some successful query, the colour becomes normal/previous. Do i need to use query here or some other way. Please help or guide me here. Thanks in advance -
How can we fetch data from other sites and compare the data with python?
I am looking to design a site which can compare some data which is fetched from different sites..And what are the required technologies which can help me in a better way. -
ManyToMany Field like tags in Django
I have a form that has many to many field. It displays like a dropdown with select, but what I want is, I want Many To many field to be displayed as that of stack overflow tags. How can I do so? I want to display those users like that in stack overflow tags. -
How to preserve the existing query string when submitting a form in Django?
I'm working on a ListView which contains both a filter form and search form as described in In a Django template, how to specify a dictionary key which is itself an attribute?. When I submit a search query, I would like it to retain the existing filter query. Previously, I implemented this by adding hidden <input> elements of which the value was obtained from request.GET using a custom filter, get, which calls the QueryDict's get method. I found that the problem with this is that for MultipleChoiceFields, for example, if multiple choices are selected, only one is retained, since the get method only returns the last value as described in https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict.get. I'm now trying a different approach. Using the custom filter relative_url, from django import template from django.utils.http import urlencode from django.http import QueryDict register = template.Library() @register.simple_tag def relative_url(field_name, value, query_string=None): """ Replace the key 'field_name' in the query_string with the given value. For example, relative_url('guide', 1, 'q=Christine') == '?q=Christine&guide=1' (After https://simpleisbetterthancomplex.com/snippet/2016/08/22/dealing-with-querystring-parameters.html) """ url = urlencode({field_name: value}) if query_string: query_dict = QueryDict(query_string, mutable=True) query_dict[field_name] = value url = query_dict.urlencode() return '?' + url and the custom filter referer_query, from urllib.parse import urlparse from django import template register = template.Library() … -
Django changing modelchoice's queryset
Model: class Event(models.Model): organizer = models.ForeignKey( Person ) event_date = models.DateField() I want to create a form for event_id = 1: form_class = modelform_factory( Event, exclude = () ) instance = Event.objects.get( id = 1 ) event_form = form_class( instance = instance ) Now, I want to alter the organizer select field so that it only shows the existing person as the only option. So: event_form.fields[ 'organizer' ].queryset = Person.objects.filter( id = instance.organizer_id ) My question is this: in the process of assigning a new queryset, I need to do a new query to the database. I feel that this is unnecessary as I already have the specific organizer that I want to assign to (instance.organizer). Is there a way to convert this organizer instance into a queryset thereby avoiding the need to do a new query? It's not a big deal for one form, but I do want to make a formset out of the modelform which would mean n queries for n forms. Thanks. -
on conflict do update
I would like to know if there's a workaround for this. I need to insert Student Balance data into a table. The source data have duplicate values for student_id, school_id and campus_name. My StudentBalance model in Django have Class Meta of: class Meta: unique_together = ( "school", "student_id", "campus_name" ) Searched online and found this magical tool called ON CONFLICT DO UPDATE. I played around with it, made it work but there's a problem. The balance data is not being updated which is because it's not in class Meta with unique_together. I would like to know if there's a way to update the data in Student Balance column without adding it to the class Meta? Thanks, J -
How to add Banned Users to table,and send details from table to user email when banned in Django Admin
I have a simple banning function that sets user active to false and a basic emailing function to send emails. The tables I am working with are User,Profile,Report & Banned_User Table. I am looking to: add the user Profile,Reason_reported from Report table and datetime that they were banned into the Banned_User table once banned. send these details to the users email Currently I am recieving a 'Attribute Error at /admin/api/profile/: WSGIRequest' object has no attribute 'report'' and not sure how to go about doing these 2 things. def banning_users(self, request, queryset): for obj in queryset: if hasattr(obj, 'user'): # This object is a Profile, so lookup the user obj = obj.user obj.is_active = False #email function banned_user = Banned_User.objects.create(profile=request.user.profile, report_reasons=request.report.report_reason) banned_user.save() #Sends ban email to user,does not send through the variables yet subject = 'Ban' message = 'You have been banned' email_from = settings.EMAIL_HOST_USER recipient_list = [obj.email] send_mail( subject, message,email_from, recipient_list ) obj.save() self.message_user(request, "User is banned and Email has been sent") Tables are below: Report Table class Report(models.Model): def __str__(self): return str.join(str(self.user_reported), str(self.datetime_sent)) TOXICITY = 'Toxicity' SPORTSMANSHIP = 'Poor sportsmanship' REPORT_REASON_CHOICES = ( (TOXICITY, 'Toxicity'), (SPORTSMANSHIP, 'Unsportsmanlike Behaviour'), ) session = models.ForeignKey( 'Session', on_delete=models.PROTECT, blank=False, null=False, ) user_reported = … -
Python Django- Not Returning a Valid Result
I am generating all possible combinations for the given scrambled letters and storing it in a list. Then, I'm checking if words from that list are in my database. Although, the word is in the database, it is not returning so. example for result list: result = ['aargh', 'raagh', 'hraag'] Although there is a word called aargh in my database, its not returning it. for r in result: # print(r) try: actual = Dictionary.objects.get(word=r) print(actual.word) except: actual = 'Not found' print("Actual Word " + str(actual)) I have words stored in 'Dictionary' Table. What is wrong here? -
change display order(number) in django admin easier?
Currently, I add display_order to my models, and my model objects will be display in main.html order_by this number. i.e. I when I have 5 objects, I can give numbers to them 1 to 5, and it's displayed in main page from 1 to 5. like this Unfortunately, it's little bit hard to change numbers one by one every time change this order. So I want to change this method for admin people. Is there more convenient way to change those order at one, more easily? Any suggestions and ideas are fine. Thanks in advance! -
Datepicker in Django 2
I am trying to put that little calendar on my field of date, in my form, for user can chose the date without have to typing, but strangely, I don't found how to do that. -
Django adding global variable
My problem, i want using query and adding variable to global and use this variable to anywhere django template same request. Any suggestions or advice on how to resolve the issue would be greatly appreciated!! Thank you in advance! -
Updating a Django list view with ajax
I'm having trouble linking this together. I'm trying to build a small leaderboard app. basically users just vote things up or down. I've got everything working except I want the leaderboard itself to update in real time or close to it without having to refresh the page. I know I need a way to basically get an updated list based on the votes and sort them by highest votes. So I used Django rest to build an API endpoint that produces a list of dictionaries in the order that I want. The next step would be to use AJAX to get that list. I just can't figure out how to get my new list in place of the old list. I started to write my ajax request and found that I was rewriting my whole HTML template, that can't be right. Could someone provide me some direction? I might just be overthinking this. Maybe I just need an ajax request that refreshes the whole page. I think I might be having trouble grasping "updating" the HTML classes. I don't need to append or prepend just reorder the given elements. Or I'm totally overthinking this whole thing so another perspective may … -
How to inject a variable into a Django template's context, similar to the 'as' argument of the built-in 'url' tag?
According to https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#url, it is possible to define a URL to be retrieved later like so: {% url 'some-url-name' arg arg2 as the_url %} <a href="{{ the_url }}">I'm linking to {{ the_url }}</a> Following https://simpleisbetterthancomplex.com/snippet/2016/08/22/dealing-with-querystring-parameters.html, I've defined a tag relative_url as follows: from django import template from django.utils.http import urlencode from django.http import QueryDict register = template.Library() @register.simple_tag def relative_url(field_name, value, query_string=None): url = urlencode({field_name: value}) if query_string: query_dict = QueryDict(query_string, mutable=True) query_dict[field_name] = value url = query_dict.urlencode() return '?' + url I would like to make this tag work with as similar to the built-in url tag, so that I can do {% with params=request.GET.urlencode %} {% relative_url field value params as action_url %} {% endwith %} and thereafter refer to it like <form action="{{ action_url }}"> ... </form> I'm looking at the Django source code for the url tag at https://github.com/django/django/blob/master/django/template/defaulttags.py, but I'm finding it not so easy to comprehend. What I suspect I need to do is instead of return the string, return a URLNode, like return URLNode(viewname, args, kwargs, asvar) where asvar is the variable being injected into the context, but I'm unsure what to fill in for each constructor argument. Is there a simple way … -
Django: How to increment URL?
How to increment the URL? I have a poll app, a user can vote in a question with "yes" and "no" each time. I would like to know how to redirect the user to the next question after the user vote for the actual question. Let's say in total I have 10 questions saved in the database. I don't want to show all 10 questions in the same page. I've read about making it with ajax and also I did read about passing question id in the url. If anyone can clarify it for me. Thanks!! -
Django in Queryset.create() method, what is 'self._for_write' for?
In this code below, what does the code self._for_write mean? def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj -
Update data using RetrieveUpdateAPIView - Getting validated data from a serializer
I would like to update certain properties of a user (say first_name and last_name) my json object through a PUT request would look like this { "user" : { "first_name": "Jack", "last_name": "shnider", "password":"admin123" "email" : "foo@google.com" }, "employee_zip" : 12345 } This is what my view looks like class UpdateProfile_RetrieveUpdateAPIView(RetrieveUpdateAPIView): queryset = modelEmployer.objects.all() serializer_class = Serializer_UpdateEmployer lookup_field = 'user__email' permission_classes = [permissions.AllowAny] def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() #------>I have the object that I would like to update serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) #--->Success Now I would like to get a validated fields (The json only contains the fields that have been updated). I know if I do something like this serializer.save I would get back a modelEmployer but instead I get back this error AssertionError at /api/employer/update_profile/employerA@gmail.com/ The `.update()` method does not support writable nested fields by default. Write an explicit `.update()` method for serializer `Employer.api.serializers.Serializer_ListEmployer`, or set `read_only=True` on nested serializer fields. Request Method: I have two questions 1-Why is save failing ? 2-How can I get the validated data from the above serializer ? -
Django/Flask Upload and Processi multi-part files
I have a python flask rest endpoint that will accept a multi-part file upload and then passes it over to a downstream service via a POST for validations. The downstream service uses Django Rest Framework. response = requests.request( request.method, request.path, files=request.files, **kwargs, ) The problem is that while the flask service gets the file as expected but in the downstream service I get the image as a byte string in the request.body and both request.FILES and request.data are empty. Following relevant headers are set: Content-Type: multipart/form-data Content-Length: ### I looked up all relevant discussions on SO but just could not get the file to move into request.FILES or request.data instead of a byte string in request.body. Any suggestions? -
python upload images in django app using pyqt4
I have create I desktop simple pyqt4 project where the user can select some image using addfile function and preview in Gui using web view (preview). my project update my PostgreSQL database with that images paths . add image : def addfile function(): dialog = QFileDialog() filename=QFileDialog.getOpenFileName() file_Field.setText(filename_1) preview : img = open(file_Field.text(), 'rb').read() webview_image_1.setContent(img, 'image/png') webview_image_1.show() my database image field keep complete paths like this C:/users/images/my_image.png for example Now I want to connect my pyqt4 project and my PostgreSQL database with django web app to see that and new images in the some web page. but the problem is the static path , I take error in images because is outside from media root path that error is correct I know why. my question is how to upload that images in django web app with some automatic way from my pqt4 Gui to django app ? -
Batch requests Gmail API
So I have a function that is telling me from/to whom are you recieving/sendig emails the most. It takes an aray of id's, loads messages on the page, then loads metadata, gets an address and adds it to a dictionary where it will be later sorted and printed. I have 10 000+ messages in INBOX. This take too long to get all these user addresses from metadata of EVERY email. How can I make it faster? I read about batch requests but I don't know how to apply them in my case. Please, help. Sorry for a little bit unreadable code but I guess main attention should near lines where I call 'service': import operator from googleapiclient import errors from quickstart import service def getTop(n): try: label = '' if n == 1: label_ids = "INBOX" label = "From" else: label_ids = "SENT" label = "To" user_id = "me" topers = service.users().labels().get(userId=user_id, id=label_ids).execute() count = topers['messagesTotal'] topers = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() tmp = [] st = [] if 'messages' in topers: tmp.extend(topers['messages']) l = len(tmp) for i in range(0, l): idshka = tmp[i]['id'] mdata = service.users().messages().get(id=idshka, userId=user_id, format='metadata', metadataHeaders=[label]).execute() head = mdata['payload']['headers'] obval = head[0]['value'] # algo/////////////////////// t = str(obval) t …