Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ensure Saving of multiple Objects in Django service
So, if the code has some indent problems, it's due to how I pasted it into Stack overflow, but basically I have this service listed below that is ran when a Django webservice is hit. 95% of the time everything works perfectly, but if you look at the amount of .save() is being called, that sometimes the payment object is never saved even though the account.save() is ran. I'm not familiar with calling django commit, but I know due to past projects that it's best practice not to list too many .save()'s in one webservice. Anyone know what I can do to ensure that all the objects are saved or none at all? It makes a huge problem if the credit card payment goes through, the Account object is updated and then the Payment Object never gets created even though the cards get charged and account shows a new payment. import gateway import datetime import smtplib merchant = {'merchantKey': '', 'processorId': '', } data = dict(merchant) cardNumber = request.GET.get("cardNumber", "") cardExpYear = request.GET.get("cardExpYear", "") cardExpMonth = request.GET.get("cardExpMonth", "") fullName = request.GET.get("fullName", "") accountIDOriginal = request.GET.get("accountID", "") accountID = accountIDOriginal.split('-')[0] if Payments.objects.filter(accountID=accountID,paymentDate=str(datetime.date.today())).count() > 0: return HttpResponse('You Have already ran a payment … -
How to use paho mqtt client in django?
I am writing a django application which should act as MQTT publisher and as a subscriber. Where should I start the paho client and run loop_forever() function. Should it be in wsgi.py ? -
setting up django and jquery selectbox
I have a problem with the django app I'm developing. Let's start at the beginning. I have a modelform . In the modelform I have a field: users = forms.ModelMultipleChoiceField(queryset=User.objects.all(),label='Users',required=False) In my template I have the selectbox "id_users" and also I have created a seond one called "id_users_to" .I am doing it this way to help the user when he selects elements.So the second selectbox is mainly just for show. Django "reads" and stores the options selected in the id_users field. Or this is what I have get so far. So.. 1.If I select one option,hit move_right button,select another hit move right again..and so on, it stores only the last one I have selected. 2.If I press CTRL and select as many as I want and click the button to "move" them to the "id_users_to", all of the items are being selected after I save the form. I can see that in the base and at an info template I have. 3.If I select items by dragging the mouse, the same, all of the items are being selected. I need the 1st option to work as well!!!! here's my jquery code! function moveElements( selector, $source, $destination ){ const $elems = … -
Django inline, conditional readonly
I want to have the inlines that have some tag (a hidden field) as readonly, but the user will be able to add another and change the lines that dont have that tag. I've been searching for a while, but I only found how to make a field readonly, when I need to have the whole line, but not all lines. The first line I need to be readonly [ checked ] The second line I need that the user can change [ ] The third line is the input line, need to be editable [ ] -
django.db.utils.IntegrityError 1215 - Custom UserModel
I am following this blog a tutorial how to Extend Django User Model. In my code i had this authentication.models.py from django.conf import settings from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): store_name = models.CharField(max_length=40, unique=True) class AccountUser(models.Model): account = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='account_users', on_delete=models.CASCADE) And in my store.settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'rest_framework', 'compressor', 'authentication' ] AUTH_USER_MODEL = 'authentication.Account' How after setting up the app models, the project settings and running the python manage.py migrate as the beginning of table creations. The command gave me this error which is i suspected in AccountUser field account: django.db.utils.IntegrityError: (1215, u'Cannot add foreign key constraint') UPDATE Found this question but it has a different solution and implementation. -
How to upload Image Files on Shared Host/ Shared Folder using Django, Python?
I have two application server 10.1.xx.xx and 10.1.xx.yy and middle of both I have load balancer 10.5.aa.bb and I have deployed my Django application in both the servers successfully and able to access the application too. There is a shared folder in between both the servers where I have to upload the images so that both servers have access of all the images, but I don't have any idea, how should I do it? up-till now I just upload the images in project folder. I googled a lot I just got this blog, http://www.bogotobogo.com/python/Django/Python_Django_Image_Files_Uploading_On_Shared_Host_Example.php but It is also not working. -
Select a valid choice is not one of the available choices
I'm new to Django. What i'm trying to do is to show some JSON response value which i converted into tuples to show in the choicefield of my Django form. This is how i'm creating the tuples usernamelist = [] useremaillist = [] for userobject in userobjects: username = userobject['somevalue'] email = userobject['somevalue'] useremaillist.append(email) usernamelist.append(username) user_tuple = zip(usernamelist,useremaillist) This is my form class UserSelectForm(forms.Form): users = forms.ChoiceField(label="Select user") Then in my views i'm trying to put all these names into drop down list selectform = UserSelectForm() selectform.fields['users'].choices = user_tuple its successfully showing but when i try to submit my form i'm getting Select a valid choice is not one of the available choices error. This is where i'm trying to get the drop down selected value from submitted form if request.method == 'POST' and 'preview' in request.POST: selectform = UserSelectForm(request.POST) if selectform.is_valid(): user_email = selectform.cleaned_data['users'] print user_email return HttpResponseRedirect('/') -
django receives 2 requests for the same url
I'm writing a simple django web application, and today I have a very strange issue. For my index template which is for url 'index', whenever I enter the url for the browsers (Firefox,Chrome), django server always receives the same GET requests two times. I found this question which has the same problem with me, but I couldn't figure out how to fix it. Could you please suggest me a solution? Many thanks. -
django-parler get the field type
I need to get from MyModel(*, TranslatableModel) the fields using the Django get_field class MyModel(TimeStampedModel, TranslatableModel): # The translated fields translations = TranslatedFields( description=models.TextField(_('description'), blank=True, help_text=abstract_help_text), title=models.TextField(_('title'), blank=True, help_text=title_help_text), ** But (of course) the usual way MyModel._meta.get_field('description') doens't work because MyModel.description is a TranslatedFieldDescriptor: <TranslatedFieldDescriptor for MyModel.description> How can I implement get_internal_type() and get_default() on TranslatableModel? Thanks -
Django locale datetime questions
I have TIME_ZONE = 'UTC', USE_I18N = True USE_TZ = True I actually have 3 questions: What is the difference between USE_I18N and USE_TZ? If I set TIME_ZONE='Europe/Athens', then in admin django outputs You are 2 hours ahead of server time. How does he know it? Compares server time with my system time? What if site is not on localhost, but on remote server? Some use of javascript? In templates dates are beautifully formatted according to locale date format. But in admin I use datetime as string representation of an object and it looks ugly. How do I fix 2016-12-07 07:00:56.934712+00:00? -
How to get a set of values through a foreign key and many to many relationship?
I have the following models. class Pizza(models.Model): toppings = models.ManyToManyField( Topping, blank=True, through='PizzaTopping' ) locations = models.ManyToManyField( Location, blank=True, through='PizzaLocations' ) class PizzaTopping(models.Model): pizza = models.ForeignKey( Pizza, on_delete=models.CASCADE ) topping = models.ForeignKey( Topping, on_delete=models.CASCADE ) class PizzaLocations(models.Model): pizza = models.ForeignKey( Pizza, on_delete=models.CASCADE ) location = models.ForeignKey( Location, on_delete=models.CASCADE ) class Topping(models.Model): topping = models.CharField( max_length=255, null=True, blank=True, db_index=True) class Location(models.Model): location = models.CharField( max_length=255, null=True, blank=True, db_index=True) I would like to do this query: Get the most popular toppings where location = some location I understand I need to do something like: Filter the pizzas by location Get the toppings used in all those pizzas Order by most frequent toppings But I'm getting totally confused. Could you please help explain how to construct such a complex query? Thank you. -
Show Images Upload in Admin using FileField in Django
I need to show multiple images uploaded in the Admin page (using FileField) in my html. I'm currently using: Python 3.6.0b4 Django 1.10.3 I can currently show if the model only has one image but when I try to put multiple images, I have no idea how to show it. Here is my code: models.py class Product(models.Model): name = models.CharField(max_length=140) created_by = models.ForeignKey(User,null=True) def __str__(self): return self.name class ProductImage(models.Model): name= models.ForeignKey(Product) image = models.FileField(upload_to='media/',null=True,blank=True) admin.py class ProductImageInline(admin.TabularInline): model = ProductImage class ProductModelAdmin(admin.ModelAdmin): exclude = ('created_by',) inlines = [ProductImageInline] def save_model(self, request, obj, form, change): if not change: obj.created_by = request.user obj.save() admin.site.register(Product,ProductModelAdmin) If I add image = models.FileField(upload_to='media/',null=True,blank=True) in my model.py, I can show it in the html like this: <img width=200 src="{{product.image.url}}" /></a> How can I show the Multiple Images in the html? I'm fairly new to Django but have experience on web development. Thanks in advance. -
Handling inputs from multiple elements on the page
I need to find a way to effectively handle button clicks on my Django webpage. Currently I have each button assigned a unique id, and I call JS function to handle the clicks: < button id="id1_element1" onclick="bhandler(this.id)" /> Then in jQuery I analyze which button fired off the bhandler and take appropriate action on server side with ajax call. The problem with this approach is that I have a lot of elements, and each event has a lot of ids. It would be cumbersome to name each button manually and then handle that input in JS. Is there an effective way to tackle this problem without writing a lot of manual code? Is jquery/ajax even the right tool? There seems to be so many JS frameworks these days, that I feel like there should be a one line solver for this. -
Use InlineForm for ForeignKey
With a ForeignKey relationship, is it possible display the form of the object being pointed to inline? The documentation shows how to do the reverse, with inline formsets; but I was unable to find how to replace the default selection box with an inline form. For example, consider the case: class Address(models.Model): line_1 = models.CharField(max_length=100) line_2 = models.CharField(max_length=100) town = models.CharField(max_length=50) state = models.CharField(max_length=5) post_code = models.CharField(max_length=4) class Person(models.Model): # ... residential_address = models.ForeignKey(Address, unique=True) postal_address = models.ForeignKey(Address, unique=True) By default, the form for Person will display two drop-down selections: one for the residential address and one for the postal address. Could I display the form instead? Perhaps through a widget and/or custom field? -
django passing parameters value to formset
I'm trying to do a very simple formset like in django documentation. I have in models.py: class PersonAdd(models.Model): person = models.ForeignKey(Person) key = models.CharField(max_length=100) value = models.CharField(max_length=100) in views: class PersonAddForm(UpdateView): model = PersonAdd fields = ['key', 'value'] template_name_sufix = '_form.html' def formset_personadd(request): PersonAddFormSet = formset_factory(PersonAddForm, extra=3) if request.method == 'POST': formset = PersonAddFormSet(request.POST) for form in formset: form.save() else: formset = PersonAddFormSet() return render(request, 'formset_personadd.html', {'formset': formset}) in forms.py (not sure if necessary) class PersonAddData(forms.Form): model=PersonAddForm key = forms.CharField(max_length=100) value= forms.CharField(max_length=100) in urls.py: (...) url(r'^(?P<pk>[0-9]+)/addsth/$', formset_personadd, name='formset-personadd'), and in link to this formset href="{% url 'formset-personadd' person.id %}" My problem is, that I cannot get data from database on my formset' site based on that person.id. Say, person.id is "1" I get page url address ".../1/addsth/ " like I should from urls.py, but when I try to get this "{{person.id}}/{{object.id}}" on that page it doesn't show. And I don't know how to pass any value. (Formset doesn't work, and doesn't show fields to fill, but I didn't even work on it, because of above problem) -
relation "auth_group" does not exist
after python manage.py runserver Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 92, in inner_run self.validate(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 280, in validate num_errors = get_validation_errors(s, app) File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 35, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 166, in get_app_errors ... packages/django/db/models/sql/compiler.py", line 775, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 58, in execute six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2]) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 54, in execute return self.cursor.execute(query, args) django.db.utils.DatabaseError: relation "auth_group" does not exist LINE 1: ...ELECT "auth_group"."id", "auth_group"."name" FROM "auth_grou... same after python manage.py syncdb or migrate -
Django Heroku Application error 'ImportError: No module named 'first_django_app'
2016-12-07T08:08:28.734943+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-12-07T08:08:28.734944+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app 2016-12-07T08:08:28.734944+00:00 app[web.1]: __import__(module) 2016-12-07T08:08:28.734945+00:00 app[web.1]: ImportError: No module named 'first_django_app' 2016-12-07T08:08:28.735075+00:00 app[web.1]: [2016-12-07 08:08:28 +0000] [9] [INFO] Worker exiting (pid: 9) 2016-12-07T08:08:28.867009+00:00 app[web.1]: [2016-12-07 08:08:28 +0000] [4] [INFO] Shutting down: Master 2016-12-07T08:08:28.867190+00:00 app[web.1]: [2016-12-07 08:08:28 +0000] [4] [INFO] Reason: Worker failed to boot. 2016-12-07T08:08:28.972207+00:00 heroku[web.1]: Process exited with status 3 2016-12-07T08:08:28.981573+00:00 heroku[web.1]: State changed from starting to crashed 2016-12-07T08:14:54.504670+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fierce-savannah-32564.herokuapp.com request_id=f177fa29-6141-49f6-b911-0a141a2d7699 fwd="106.51.39.154" dyno= connect= service= status=503 bytes= 2016-12-07T08:14:55.470283+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fierce-savannah-32564.herokuapp.com request_id=ce2f7d67-2380-4efa-8e8c-b24704ba16d2 fwd="106.51.39.154" dyno= connect= service= status=503 bytes= When am visiting the app url its show 'Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.' the log shows the message above i have no idea what that means please help -
Django raising a parse error for single quote escaping in JQuery
I am appending a html code which contains double quotes and single quotes in image tags for Django processing, which raises a parse error. I reckon escaping a single quote would work but not. text = '<img src= "{% static ' + '\'app/img/' + myField[i] + '.png\'' + ' %}">'; The error is Django GET TemplateSyntaxError :: Could not parse the remainder: '\'app/img/'' from '' + '\'app/img/' Obviously, it couldn't parse the escaping. How can I resolve this? -
can someone give me a hand and example this script? django
I found a script online which helps me changing login to use both username and email instead of just username, but there are quite a lot of parts which I don't really understand. Like, I understand pretty much what each line means but I don't get why by doing that would make my login work with email. class EmailBackend(object): def authenticate(self, username=None, password=None): user_cls = get_user_model() try: user = user_cls.objects.get(email=username) if user.check_password(password): return user except user_cls.DoesNotExist: return None except: return None def get_user(self, user_id): user_cls = get_user_model() try: return user_cls.objects.get(pk=user_id) except user_cls.DoesNotExist: return None Thanks in advance. -
ValueError while sharing page of Django on facebook
I have a Django site in pythonanywhere. When I copy and paste the url in facebook to share it, I get this error: If you click the link, it works well. I dont know how to access the description of the ValueError. I have tried this code in the template in order to select the image of thumbnail: <meta name="og:image" content="{{ object.image.url }}" /> <link rel="image_src" href="{{ object.image.url }}"/> But it doesnt work. Whats happening? -
I want to know whether there is a default functionality for updating a django template from the server side based on an event
I am a beginner django developer. I am supposed to make an auction website. I have to update the template which shows the listing of the items and bids and I will have to update the template with latest bids each time a bidder makes one without having to refresh the page for each new update. I have thought of querying the table each second and make ajax calls at the same intervals but I want to have real time updates without the extra overhead of polling and ajax calls each second, thus this question. I am not looking for a specific piece of code to accomplish this, I just wanted to know whether there is any relevant package available to aid me in this, if not I'd request you to suggest me with a generic direction to accomplish this. -
TypeError: __init__() takes 1 positional argument but 2 were given
I am develop a simple rest api using Django 1.10 When I run my server and call app url I get an error: TypeError: __init__() takes 1 positional argument but 2 were given GET /demo/ HTTP/1.1" 500 64736 models.py from django.db import models class ProfileModel(models.Model): name = models.CharField(max_length=30, blank=False, default='Your Name') address = models.CharField(max_length=100, blank=True) contact = models.IntegerField() def __str__(self): return '%s %s' % (self.name, self.address) views.py from django.shortcuts import render from rest_framework import viewsets from mydemoapp.models import ProfileModel from .serializers import ProfileSerializer class ProfileView(viewsets.ModelViewSet): profile = ProfileModel.objects.all() serializer_class = ProfileSerializer serializers.py from .models import ProfileModel from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): class Meta: model = ProfileModel fields = ('name', 'address', 'contact') urls.py (Application Url) from django.conf.urls import url from mydemoapp import views urlpatterns = [ url(r'^$', views.ProfileView), ] urls.py (project url) from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^demo/', include('mydemoapp.urls')), ] -
Bootstrap signup modal for django allauth
I want to create a bootstrap modal with login and signup functionality in django and i have used django allauth. I am fairly new to django and don't know how to proceed. I have got the login page at http://127.0.0.1:8000/accounts/login/ and signup page at http://127.0.0.1:8000/accounts/signup/ but what i want is a button like signin and when i press that i want a modal to popup which i can do and in the modal i want both the login and signup form and do login and signup from there. -
Retrieve property of an object through multiple foreignkeys
I'm learning Django and I have chained different classes Archipel -> Island -> Community in order to localize items to be published in a website (Communities belong to only one Island which belongs ton only one Archpelago). Maybe I did wrong but here is how I coded : #models.py class Archipel(models.Model): """docstring for Archipel.""" archipel_name = models.CharField(max_length=200) def __str__(self): return self.archipel_name class Island(models.Model): """docstring for Archipel.""" archipel = models.ForeignKey(Archipel, on_delete=models.CASCADE) island_name = models.CharField(max_length=200) def __str__(self): return self.island_name class Community(models.Model): """docstring for Archipel.""" island = models.ForeignKey(Island, on_delete=models.CASCADE) community_name = models.CharField(max_length=200) community_zipcode = models.IntegerField(default=98700) def __str__(self): return self.community_name In the following class, I can easily get the community name of the product thanks to the ForeignKey : class Product(models.Model): community = models.ForeignKey(Community, on_delete=models.CASCADE) island = # community->island archipelago = # community->island->archipelago Product_title = models.CharField(max_length=200) Product_text = models.TextField() Product_price = models.IntegerField(default=0) Product_visible = models.BooleanField(default=False) pub_date = models.DateTimeField('date published') How can I retreive the island_name and archipelago property of my product ? I tried island = Community.select_related('island').get() but it returns me a QuerySet of all islands. So I tried "community" but Django answers that ForeignKey object don't have a slelect_related object. -
Tracking (View or downloads) a link (file hosted on S3) sent via Email
Hello geek need suggestion,I have an file hosted on S3 bucket. I am sending an welcome email to all my subscribers with an link to see my profile(File hosted on S3). I want to know how many users has clicked on link(View my profile) sent via email and how many of them has download my profile(My S3 file).I want do this using Django app.