Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Equality of Django's Q objects
I am trying to compare django's Q objects which are composed in the exact same way. But despite all children and relations between them being same, they aren't deemed equal. from django.db.models import Q $ q1 = Q(a=1) & Q(b=1) & Q(c=1) $ q2 = Q(a=1) & Q(b=1) & Q(c=1) $ q1 == q2 $ False This is posing problems in my unit tests where I build up filters for my querysets using Q objects. Why are the two Q objects not equal? I am using Django 1.11. -
Django Error: Reverse for 'query' with no arguments not found
What I'm trying to achieve is this: I have a list of branches and clicking on it would link me to a list of services of that specific branch. (url: http://127.0.0.1:8000/branches/[slug:branch_name]) 2.I have a search form with a button upon clicked will filter out the specific service that I want on the context of the branch I'm currently in. (url: http://127.0.0.1:8000/branches/[slug:branch_name]/search/[?q=specific_service]) It seems to me that the urls are configured properly and the problem is on the search-form.html action="{% url 'branches:search:query' %}". I've tried many things including trying to add kwargs in the url template tag slug=slug and customizing my views.py to add kwargs to reverse and replacing action = "{{ reverse_url }}" but nothing seems to work. I must be missing something. The only hack I've found to work is using action = {{request.path}}search/. I was wondering if there is a cleaner solution than this. Would appreciate any leads! Thanks! main/urls.py urlpatterns = [ url(r'^$',home_page, name='home'), url(r'^admin/', admin.site.urls), url(r'^branches/', include("branches.urls", namespace='branches')),] branches/urls.py urlpatterns = [ url(r'^$', BranchListView.as_view(), name='list'), url(r'^(?P<slug>[\w-]+)/$', BranchServiceListView.as_view(), name='services'), url(r'^(?P<slug>[\w-]+)/search/', include("search.urls", namespace='search')),] search/urls.py urlpatterns = [ url(r'^$', search_catalog, name='query'), ] search-form.html <form method="GET" action="{% url 'branches:search:query' %}" class="form-inline my-2 my-lg-0"> -
Changes to model with one to one relation not saving
I have two models that I'm relating using Django's OneToOneField, following this documentation: https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/ class Seats(models.Model): north = models.OneToOneField('User',on_delete=models.CASCADE,related_name='north', default=None, null=True) bridgetable = models.OneToOneField('BridgeTable',on_delete=models.CASCADE, default=None, null=True) class BridgeTableManager(models.Manager): def create_deal(self): deal = construct_deal() table = self.create(deal=deal) s = Seats(bridgetable=table) s.save() return table class BridgeTable(models.Model): deal = DealField(default=None,null=True) When I run this code I can successfully get the relationship working table = BridgeTable.objects.get(pk='1') user = User.objects.get(username=username) table.seats.north = user table.seats.north.save() print(table.seats.north) The print statement prints out the name of the player sitting north. But if I try to access the table again like this: table = BridgeTable.objects.get(pk='1') print(table.seats.north) I get "None" instead of the user's name. Is there something I'm missing, like a save that I missed or some concept I'm not understanding? Thanks. -
How to install a django package that does not have a pypi release? [duplicate]
This question already has an answer here: How to install Python package from GitHub? [duplicate] 2 answers I am trying to use ActivFlow on my project. Unfortunately there is no pypi package, so how should I go about installing and using the package on my project. Here it is on django-packages -
Django - Modelform not rendering
I created a form to update a User's profile, however when I run it, there are no errors, but when I try to open up the page, nothing shows up. Secondly, I was wondering how you would create a large textbox to store someone's biography. Models.py class UserProfile(models.Model): user = models.OneToOneField(User) biography = models.CharField(max_length = 255, default = '') city = models.CharField(max_length=100, default = '') website = models.URLField(default='') image = models.ImageField(upload_to='profile_image', blank=True) def setdefault(self, default_path='/profile_image/Default.jpg'): if self.image: return self.image return default_path def __str__(self): return self.user.username Forms.Py class UpdateBioForm(forms.ModelForm): class Meta: model = UserProfile fields = ( 'biography', 'city', 'website' ) def save(self, commit=True): savedBio = super(UpdateBioForm, self).save(commit=False) savedBio.biography = self.cleaned_data['biography'] savedBio.city = self.cleaned_data['city'] savedBio.website = self.cleaned_data['website'] if commit: savedBio.save() return savedBio Views.py def update_bio(request): if request.method == 'POST': form = UpdateBioForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/') else: form = UpdateBioForm(instance=request.user) args = {'form':form} return render(request, 'accounts/update_bio.html') update_bio.html {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Update Biography</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} -
how to write django web script for showing our run time input in web page url?
My questionn is how to show our input in web page when we are giving url with input in address bar. For example I am giving url in my web browser like localhost:8011/Sathish means It will show my input in web page. Like "Sathish". If I give localhost:8011/Kannan It will show like this. Like "Kannan" Can you please tell me how to write that code in django? -
Use response of a method to define a model field in Django
I need some dynamic choices fields in a django model and I want to validate if a table exists before get them. I already know how to check if the table exists with raw sql and also I know how to generate my dynamic tuple for choices, but I don't know how to use the response of my validation method. Any ideas? This is a snippet of my code: class SomeModel(models.Model): ... row = False def check_table(self): with connection.cursor() as cursor: cursor.execute( "SELECT EXISTS(" "SELECT *" " FROM pg_tables WHERE schemaname = \'schema_name\' AND " "tablename = \'table_name\')") row = cursor.fetchall() return row # Then, I need to put that reponse in a variable to do something like this. if table_exists: # do something ... Thanks -
Add two TaggableManager for a modal in django taggit
I have a model like class EmotionJournal(models.Model): situation = models.TextField() emotions_before = TaggableManager() emotions_after = TaggableManager() def __str__(self): return str(self.id) where I need to have two types of tag in a single model. I looked through various solutions like from this link But I was not satisfied with the solution. I wanted to know how can I do the same? -
Using python how to upload the image file into MSSQL Server via HTML
I wanted to upload a image file from HTML and that'll be redirected to server side script written in python. Since I wanted to upload the file name from this path: 'C:\Users\Desktop\Desktop\123456.jpg' After connection is established from the database and while inserting image into Database following things happens Raises an exception It takes only fileName not the absolute path of the file (i.e, 123456.jpg) index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } #dvPreview { filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image); min-height: 50px; min-width: 50px; display: none; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script language="javascript" type="text/javascript"> $(function () { $("#fileupload").change(function () { $("#dvPreview").html(""); var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/; if (regex.test($(this).val().toLowerCase())) { if ($.browser.msie && parseFloat(jQuery.browser.version) <= 9.0) { $("#dvPreview").show(); $("#dvPreview")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $(this).val(); } else { if (typeof (FileReader) != "undefined") { $("#dvPreview").show(); $("#dvPreview").append("<img />"); var reader = new FileReader(); reader.onload = function (e) { $("#dvPreview img").attr("src", e.target.result).width(150).height(200);; } reader.readAsDataURL($(this)[0].files[0]); } else { alert("This browser does not support FileReader."); } } } else { alert("Please upload a valid image file."); } }); }); </script> </head> <body> <form action = "http://localhost/img_upload.py" method = "post"> <label for="fileupload"> Select a file to upload </label> <br/><br/> <input type="file" name="fileupload" … -
Use different wagtail page as root without slug
I'm attempting to set a page as the root home page of my wagtail based site. I know you can set the homepage using the sites setting. But, my use case is different. I'm using a "redirect" page which redirects to an index page as the homepage. The index is restricted to only allow ertain page types (since it's an index....). But, this causes issues with other pages not being in the tree if it was set at the root. Hence, the redirect. But, upon redirecting the serve view of the redirect page to use this page it picks up the slug. I still want it to appear at the root url. Meaning, /. How can I achieve this? High level description: class IndexPage(Page): # children restricted to IndexSubpage class IndexSubpage(Page): # parent restricted to IndexPage class RedirectPage(Page): def serve(request): return redirect(self.link, permanent=True) # Link is a link to a page.... So, this will pick up the slug of IndexPage instead of being at / -
I am not able to connect mysql server with python engine getting following error
Following error I am getting ` Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03D26618> Traceback (most recent call last): Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ` I already install Django-Mssql -
Why I use vscode run django project and debug it, then I can not get post data
I can not get post data when I use vscode run django project, insteed of command, is my configuration wrong? addition: I can not get print content from debug console. -
How to display javascript from ajax response in HTML
I am designed one web application in which I want to show the plot which will be received by ajax response.This plot is written in javascript.I want to put this plot as the HTML div. Below is my HTML code, {%load static %} {% load staticfiles %} <head> <script src=" {% static 'jquery-1.12.4.js' %}"></script> </head> <button type="button" id="myBtn" onclick="myFunction()">Try it</button> </html> <div id="plot"></div> <script> function myFunction() { $.ajax({ url: '/visualization/', type: 'POST', contentType: 'application/json; charset=utf-8', //data: JSON.stringify(finalJson), //dataType: 'text', success: function(response){ console.log("!!!Reponse!!!") console.log(reponse) document.getElementById("plot").innerHTML = response } }); } </script> Below is javascript received for plot: <style> </style> <div id="fig_el150211404154248054569977043312"></div> <script> function mpld3_load_lib(url, callback){ var s = document.createElement('script'); s.src = url; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){ // already loaded: just create the figure !function(mpld3){ mpld3.draw_figure("fig_el150211404154248054569977043312", {"axes": [{"xlim": [-1.1078409018075122, 1.1078409018075119], "yscale": "linear", "axesbg": "#FFFFFF", "texts": [{"v_baseline": "auto", "h_anchor": "start", "color": "#000000", "text": "RP1", "coordinates": "data", "zorder": 3, "alpha": 1, "fontsize": 8.0, "position": [-1.0, 1.7], "rotation": -0.0, "id": "el15021140415296730768"}, {"v_baseline": "auto", "h_anchor": "start", "color": "#000000", "text": "RP2", "coordinates": "data", "zorder": 3, "alpha": 1, "fontsize": 8.0, "position": [0.0, 1.7], "rotation": -0.0, "id": "el15021140415296731792"}, {"v_baseline": … -
Missing manage.py while trying to install Graphite (with Django)
I am trying to install Graphite on Ubuntu following the instructions given here: https://gist.github.com/albertohm/5697429 When I install the components, especially Django, I do not get any errors. However when I run these two commands I get an error saying that "manage.py could not be found": cd /opt/graphite/webapp/graphite sudo python manage.py syncdb I've tried many different ways of setting up Graphite but none worked :-( Can someone please help me as to why manage.py does not exist in the graphite web folder? -
What is the difference b/w authenticate() and login() in Django?
I want to understand the difference b/w both user = authenticate( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password1') ) login(request, user) -
Celery crontab scheduler not working
I added a task to Celery's beat schedule configuration to run at a specific time under a specific timezone, America/Chicago, the timezone where I live. I can see that the Celery app's timezone is in fact America/Chicago after changing it, but when the time comes the task doesn't run. The task will run at intervals of time, but will not work with crontab. Celery.py import datetime from celery import Celery from celery.schedules import crontab BROKER_URL = "amqp://" CELERY_RESULT_BACKEND = "redis://localhost" app = Celery('tasks', broker=CELERY_RESULT_BACKEND) from time import time new_time = datetime.datetime.now() app.conf.timezone = 'America/Chicago' @app.task def campaign_heartbeat(): return app.conf.timezone app.conf.beat_schedule = { 'campaign-heartbeat': { 'task': 'tasks.campaign_heartbeat', 'schedule': crontab(hour=23, minute=26) } } -
Check Form Before Submit Use Ajax Django
I use Ajax to send data from form to server. But I want to check data in form before Submit by Ajax: <form id='#id_form' onsubmit='return checkInputSubmit();' > ... </form> In Ajax: $('#id_form').submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: url, dataType: 'json', data: $('#id_form').serialize(), // serializes the form's elements. success: function(data) { if(data.result == true) { //My code } else { //My code } } }); }); But checkInputSubmit() can't prevent submit from Ajax. You can explain for me and give me solution to check data in form before Submit by Ajax. Thanks. -
What is a clean way of mocking multiple methods on a class in python?
When writing tests I am often faced with the needed to mock several class methods. Currently I am doing this by nesting with statements contain the mock references e.g. from ... import A def test_sample(self) instance = A() with mock(A, 'function_1', return_value=1): with mock(A, 'function_2', return_value=2): with mock(A, 'function_3', return_value=3): assert A.function_4, 10 Is there a neater / recommended way of doing this? It would be nice to be able to remove several nested calls! -
update objects before access using DetailView (Django)
I am using DetailView in Django. I have a model including certain time field(taxi_time), and I would like compare the time and now. If taxi_time < datetime.now(), I want to change a field(taxi_is_closed) in the model from False to True. So before users access the post, I need to (automatically) check the time and modify taxi_is_closed. How can I do it? My View.py : @method_decorator(login_required(login_url='/login/'), name='dispatch') class RecruitView(PermissionRequiredMixin, generic.DetailView): model = Recruit template_name = 'taxi/recruit.html' def has_permission(self): return self.request.user.profile.email_confirmed def handle_no_permission(self): error_message = '아직 인증이 완료되지 않았습니다. 이메일 인증을 완료해주세요! :)' if self.raise_exception: raise PermissionDenied(self.get_permission_denied_message()) return render(self.request, 'taxi/info.html', {'error_message': error_message}) def get_context_data(self, **kwargs): context = super(RecruitView, self).get_context_data(**kwargs) #pdb.set_trace() img_var = self.get_object().taxi_popnow*10 + self.get_object().taxi_poptot img_name = str(img_var) context['img_name'] = img_name context['ApplyForm'] = ApplyForm() return context MY model.py : class Recruit(models.Model): taxi_time = models.TimeField('출발 시각') taxi_is_closed = models.BooleanField('마감', default=False) def chk_closed(self): now = datetime.datetime.now() taxi_datetime = datetime.datetime.combine(self.taxi_date, self.taxi_time) is_full = self.taxi_poptot <= self.taxi_popnow is_past = taxi_datetime <= now if (is_full or is_past): self.taxi_is_closed = True else: self.taxi_is_closed = False self.save() I picked only related code. -
Django Use ManyToManyField Data in View
models.py class Profile(models.Model): profile_name = models.CharField(max_length = 255, blank = False) extra_profile_text = models.CharField(max_length = 50, blank = False) class Category(models.Model): category_name = models.CharField(max_length = 50, blank = False) extra_category_text = models.CharField(max_length = 50, blank = False) class ProfileCategory(models.Model): profile = models.ManyToManyField(Profile) category = models.ManyToManyField(Category) forms.py class ProfileCategoryForm(forms.ModelForm): class Meta: model = ProfileCategory fields = ('profile', 'category',) views.py def task(request): if request.method == "POST": form = ProfileCategoryForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user #use [profile_name, extra_category_text data] that user selected post.save() form.save_m2m() return redirect('somewhere') else: form = ProfileCategoryForm() context = {'form': form } return render(request, 'some_app/somewhere.html', context) I want to bring 'profile_name', 'extra_category_text' datas in view when user select from ProfileCategoryForm. process will be Front: user select one of Profile, one of Category > Save Back: get user selected Profile, Category datas(ex: profile_name, extra_profile_text) > do some task > Save to ProfileCategory model. it seems that I need to use queryset but no clue at all :( -
Django - Default Profile Picture not showing
I have a question about images and imagefields. However, the default picture I chose does not show up, only a blank circle. This was my default picture Models.py class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=255, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') def __str__(self): return self.user.username class ProfilePicture(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to='profile_image', default='profile_image/Default.jpg') Forms.py class UploadPictureForm(forms.Form): image = forms.ImageField() profile.html <div class="container"> <div id="left"> <div id="profilecard"> {% if user.userprofile.image %} <img class="circular--square" src="{{ }}" width="200" height="200"> {% endif %} <div id="info"> <br> <h3>{{ user.first_name }} {{ user.last_name }}</h3> <p>@{{ user }}</p> <p>{{ user.userprofile.city }}</p> <p>{{ user.userprofile.website }}</p> <p><i>{{ user.userprofile.description }}</i></p> </div> </div> -
Django testing user model fails but it works in the browser
I am new to testing and am trying to run the following tests but I get a 404 assertion error because the method that tries to reverse the url cannot find the category that had been created in the setUp method. I can create categories in the browser using the superuser with no problem and the url responds with 200 status. Could you help me understand what I am doing wrong? Test: from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.auth.models import User from cataloger.models import Category class CatalogerCategoriesTests(TestCase): def setUp(self): tom = User.objects.create_user(username="tom", password="1234567") Category.objects.create(name="cell phone", description="current cell phone types in the market.", created_by=tom) def test_category_page_success_status_code(self): url = reverse('category_items', kwargs={'pk': 1}) response = self.client.get(url) self.assertEquals(response.status_code, 200) Fail: Traceback (most recent call last): File "/home/ubuntu/workspace/cataloger/tests_categories.py", line 48, in test_category_page_success_status_code self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 Models: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name="categories") Views: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from cataloger.models import Category def category_items(request, pk): category = get_object_or_404(Category, pk=pk) return render(request, … -
AssertionError: 200 != 404
====================================================================== FAIL: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 77, in test_dont_remember_cc self.assertEqual(200, rs.status_code) AssertionError: 200 != 404 ---------------------------------------------------------------------- Ran 1 test in 1.200s View class OnlinePaymentView(CustomerViewMixin, TemplateView, CreateView): template_name = 'zoneclient/payment.html' form_class = OnlinePaymentForm object = None def get_success_url(self): return reverse('zoneclient-dashboard', kwargs={'clientcode': self.get_customer().code}) def get(self, request, clientcode=None): self.object = self.get_customer() return self.render_to_response({ 'customer': self.get_customer(), 'is_quickform': False, 'form': self.form_class(user=self.get_customer()), }) def post(self, request, clientcode=None): if self.request.POST.get('quickform'): self.object = self.get_customer() try: amount = '%0.2f' % float(self.request.POST.get('amount')) except ValueError: amount = '' # Paypal invoice = { 'business': settings.PAYPAL_BUSINESS, 'amount': '%0.2f' % float(request.POST.get('amount')), 'item_name': _('Online payment'), 'invoice': generate_invoice_id(self.get_customer().pk), 'notify_url': get_full_url(self.request, 'paypal-ipn'), 'return_url': '{}'.format( get_full_url(self.request, 'paypal-payment-done')), 'cancel_return': '{}'.format( get_full_url(self.request, 'paypal-payment-cancel')), 'currency_code': 'CAD', } return self.render_to_response({ 'customer': self.get_customer(), 'is_quickform': False, 'paypal_invoice': invoice, 'paypal_form': PayPalPaymentsForm(initial=invoice), 'form': self.form_class( user=self.get_customer(), initial={'amount': amount}), }) else: log.info('{} submitted a payment via website'.format(usr(request))) return super(OnlinePaymentView, self).post(request) def get_form(self, form_class): kwargs = self.get_form_kwargs() kwargs['user'] = self.get_customer() return form_class(**kwargs) def form_valid(self, form): amount = '%0.2f' % float(form.cleaned_data.get('amount')) payment = StripePayment(self.get_customer()) # Newly entered card if form.cleaned_data['cc_hash'] == 'new': pargs = { 'exp_month': form.cleaned_data['expdate'].month, 'exp_year': form.cleaned_data['expdate'].year, 'name': form.cleaned_data['name'], 'number': form.cleaned_data['acct'], 'cvc': form.cleaned_data['cvv2'], 'card': 'new', 'ip': get_client_ip(self.request), 'remember_cc': form.cleaned_data.get('remember_cc')} # Using stored card else: pargs = { 'card': form.cleaned_data['cc_hash'], 'remember_cc': … -
Django Pagination and Ajax Refresh
I got this simple Django model, class Person(models.Model): name = models.CharField(max_length=100) that I want to display using paginator showing only 1 item (name) per page. A left and right arrow when pressed will show the previous and next item in the paginator queryset using Ajax refreshing only the name. I'm using jQuery for Ajax. Question is when refreshing by Ajax how do you know the current page number and in this case the current page number corresponded to the currently shown name and so to display the next or previous item in the list using page_next and page_previous? -
ImportError: cannot import name. Cannot import class from the model.py
I got a full code from github and everything was OK, server worked without any problems. But then I tried to do some changes, like adding a new class in the model.py and trying to import it to the admin.py I got such an error: ImportError: cannot import name TechnicalExamination. Of course, I did migrations before this, using python manage.py makemigrations and python manage.py migrate. Here is my class in model.py: class TechnicalExamination(models.Model): class Meta: verbose_name_plural = 'Technical Examinations' technician = models.CharField(max_length=70) person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() def get_fields(self): pairs = [] for field in self._meta.fields: name = field.name try: pairs.append((name, getattr(self, "get_%s_display" % name)())) except AttributeError: pairs.append((name, getattr(self, name))) return pairs def __str__(self): return str(self.technical) Here is my admin.py: from __future__ import unicode_literals from django.contrib import admin from .models import Person, Car, InsuranceCompany, Policy, HealthExamination, TechnicalExamination admin.site.register(Person) admin.site.register(Car) admin.site.register(InsuranceCompany) admin.site.register(Policy) admin.site.register(HealthExamination) admin.site.register(TechnicalExamination) And here is my root: enter image description here