Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to submit a mock url? (Django)
I have a problem, I can't test my forms by using requests. add_playlist = self.client.post(reverse('new-playlist'), data={'url': 'https://dailyiptvlist.com/dl/it-m3uplaylist-2018-03-11-1.m3u'}) I need to create a mock response for 'https://dailyiptvlist.com/dl/fr-m3uplaylist-2018-03-06.m3u' so it will be acceptable to test adding a channel while the url isn't maintained. So, I need to create a mock response for this url. I can't imagine how to do this. Please help me. -
response.get('X-Frame-Options') on stripe failed payment
I am trying to customize stripe payment gateway using elements, I followed the documentation provided on stripe website and on this tutorial http://zabana.me/notes/how-to-integrate-stripe-with-your-django-app.html. I managed to get my payment charged and I am now testing for defect card such as Charge is declined with an expired_card code that stripe provide but I am getting an error that I do not even understand so hard for me to debugg what is going on ... error : if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' my code: payment-views.py: from Authentication_project import settings from django.views.generic import TemplateView from django.shortcuts import redirect import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class payment_form(TemplateView): template_name = "transaction.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_PUBLIC_KEY return context def checkout(request): if request.method == "POST": token = request.POST.get("stripeToken") print(token) print(request.user.email) try: charge = stripe.Charge.create( amount=2000, currency="usd", source=token, description="SoftScores Team Assessment", receipt_email=request.user.email, ) except stripe.error.CardError as ce: return False, ce else: return redirect('index') Any idea how to solve it ? -
Trouble attaching postgres database to Heroku application
I have a Django application with PostgresQL database. I have successfully deployed the application on heroku (myapp), but getting trouble attaching the local database to it. To attach the local database to my Heroku application (myapp), I followed these steps 1.Created database (db-name) dump file sudo pg_dump -U postgres db-name > db-name.dump 2.Uploaded dump file online where its accessible through link https:url/db-name.dump on following the above link db-name.dump file gets downloaded 3.Used pg:backups:restore command to restore the backup on my heroku application heroku pg:backups:restore 'https:url/db-name.dump' DATABASE_URL --confirm myapp On issuing the above pg:backups:restore command, I am getting an error Restoring... ! ▸ An error occurred and the backup did not finish. ▸ ▸ waiting for restore to complete ▸ pg_restore: [archiver] did not find magic string in file header ▸ pg_restore finished with errors ▸ waiting for download to complete ▸ download finished successfully ▸ ▸ Run heroku pg:backups:info r004 for more details. Any guessed whats going on here.. -
Django: Multiple values in Radio Select Form
I've got a radio select form that displays addresses that the user has saved. Currently, when the user visits the "select address" template, they are only shown the 'street' field for each address that they've saved. This is controlled by the "return self.address" line below as I've established through testing. I'd like user to see the street, city, and state of each of the addresses that he/she has saved. From the list, they'll select the radio button next to the address that they'd like to ship to. models.py class Order(models.Model): user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE) billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True, on_delete=models.CASCADE) order_id = models.CharField(max_length=20, null=True, blank=True) class UserAddress(models.Model): street = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120) state = models.CharField(max_length=120, choices=STATE_CHOICES, null=True, blank=True) def __str__(self): return self.address I'm using a class based view. Here are some functions within that view that I belive are controlling the output within the template: def get_addresses(self, *args, **kwargs): user_check_id = self.request.session.get("user_checkout_id") user_checkout = UserCheckout.objects.get(id=user_check_id) b_address = UserAddress.objects.filter(user=user_checkout) return b_address def get_form(self, *args, **kwargs): form = super(AddressSelectFormView, self).get_form(*args, **kwargs) b_address = self.get_addresses() form.fields["billing_address"].queryset = b_address return form Within the template, I've got the following: {% csrf_token %} {{ form }} <input type='submit' value='Select' /> </form> I … -
Serializing nested object in Django Rest Framework
I'm trying to serialize a json that must have a token string and a nested user object (which has its own serializer). I'd like to have something like: class LoginResponseSerializer(serializers.Serializer): token = serializers.CharField(read_only=True) user = UserSerializer(read_only=True) But this is not working, I don't know how should I create this serializer and how to pass the data. Thank you very much -
django: Create custom user with email as login and other fields
I am using Django 2.0.3. I want email as the username and also First Name and Last Name as required fields. Apart from this,later the user can update the gavtar (models.ImageField) and aboutme (models.CharField(max_length=140)), dateofbirth, country, city. So what is the best way to do this in Django. -
Use raw URL or static URL for images?
Is there any difference when using: <img src="{% static 'images/someimage.png' %}" and <img src="https://s3.us-east-2.amazonaws.com/my-bucket/static/images/someimage.png" -
How does django differentiate between 2 management forms on same page?
I have 2 formsets based on 2 different models. While debugging a validation problem where my formsets were failing is_valid validation (see errors below): (Pdb) FormsetItem.errors [{'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That … -
how to get item from select option html Django?
I tried to implement 2nd dropdown based on the 1st dropdown and get the item from two dropdowns. <select class="js-example-basic-single" name="select1" id="select1"> <option value="1">Disease</option> <option value="2">Drug</option> <option value="3">Problem</option> <option value="4">Test</option> <option value="5">Treatment</option> </select> <select class="js-example-basic-single" name="select2" id="select2"> {% for item in content1 %} <option value="1" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content2 %} <option value="2" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content3 %} <option value="3" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content4 %} <option value="4" itemY="{{item}}">{{item}}</option> {% endfor %} {% for item in content5 %} <option value="5" itemY="{{item}}">{{item}}</option> {% endfor %} </select> and in JS: <script type="text/javascript"> $("#select1").change(function() { if ($(this).data('options') === undefined) { /*Taking an array of all options-2 and kind of embedding it on the select1*/ $(this).data('options', $('#select2 option').clone()); } var id = $(this).val(); var options = $(this).data('options').filter('[value=' + id + ']'); $('#select2').html(options); $("#select2 option:selected").text(); var conceptName = $('#select2').find(":selected").text(); }); </script> In views.py f2 = request.POST.get('select1',False) f3 = request.POST.get('select2',False) it return the value not item............ I want the item. Based ont he -
Getting error of to many arguments were given - django project
I have a django project with a django app called users. in the projects url settings I have it connected to the users app url python file. I want to connect them and have the urls base off of the url patterns in the users urls file.. WHile doing so, I am getting an error that there were to many arguments that were being passed and I have no idea what it means or any reference as to how I can fix this error. This is the main error that I am getting I am getting the error when i run the following command python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108629378> Traceback (most recent call last): File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = … -
What is happening when I run `python manage.py test` and on which port the django test server is listening?
I wrote a test for for a signup feature. When I do manually, the signup process sends email to the user, but when I do it with test script the email is not sent. So I was wondering what is happening inside? And what is the port for the test server? Is there any relation for the test server to send mail with it? Can I specify the test server port? -
How do you call a user defined function in views.py DJANGO
The requirement is to display the logged in username and his role in the organization in all the pages at the top right corner. The role can be identified by the permissions he is given. My approach: I thought of creating a user-defined function in views.py and call it in each and every other function. The function that I create should check the current user's permissions and based on them his role should be decided. All these details must be sent to base.html so that it will render and display the username and his role every time the page is loaded. Any suggestions on other approaches are welcomed and if my approach is entirely wrong please let me know. -
Django Session Data lost after clearing browser Data
Im using django 1.11.7 and the session objects to store data from users that are login works fine but when I clear the browser data the session object is lost, as far as I know if you use this 'django.contrib.sessions', you're setup to save the session object in the DB and im able to see Data in the Db each time someone logs in but the problem is that for some reason I cant use this data when i fetch it maybe is the way I fetch the data because the data is being saved in the DB here is how I fetch the data in the views: this is the normal way that works until I clear the browser data in_test = request.session['in_test'] then in some reading they suggest that even if the data is being saved in the db some cookies are created to match that data and they use this to some how also get the data from the session obj but same result: in_test = request.session.get('in_test') but at least there is a hint that the browser cookie is obviously missing since I cleared but the question is how to pair or directly fetch the session object … -
how to instantiate recursive foreign key in django?
class Notebook(models.Model): title=models.CharField(max_length=10) father = models.ForeignKey('self', on_delete=models.CASCADE) How to use it? n1=Notebook(title='a', father='???') n2=Notebook(title='b', father=n1) how to set the value for father attribute of n1? -
How to override Django admin `change_list.html` to provide formatting on the go
In Django admin, if I want to display a list of Iron and their respective formatted weights, I would have to do this. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight_formatted',) def weight_formatted(self, object): return '{0:.2f} Kg'.format(object.weight) weight_formatted.short_description = 'Weight' I.e: 500.00 Kg The problem with this however is that I would have to write a method for every field that I want to format, making it redundant when I have 10 or more objects to format. Is there a method that I could override to "catch" these values and specify formatting before they get rendered onto the html? I.e. instead of having to write a method for each Admin class, I could just write the following and have it be formatted. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight__kg',) def overriden_method(field): if field.name.contains('__kg'): field.value = '{0:.2f} Kg'.format(field.value) I.e: 500.00 Kg -
python two dictionary dynamically in for loop if condition based upon store
db fetched data key based upon generated for loop def data(request): from_date=2009-01-01 todate=2009-01-31 with connection.cursor() as cursor: cursor.execute("select id,name,no_of_apsent,no_of_lop,amount from pay where from_date='%s' and todate='%s'"%from_date,todate) fetched_data=cursor.fectall() a={} b={} for c,d,e,f,g in fetched_data: if f<=e: h=g*10/100 a[c]=h else: i=g/31 b[c]=i print(a,b) return render(request,hai.html,{'a'a,'b',b}) db fetched data key based upon generated for loop if condition true and key value based upon store for example {0:1,1:0,2:9} like this if the key value 1 is false the key value store 0 true means store required value. This is the trouble -
configure the django with Oracle 11g data base issue
Oracle database configurations with Django and while migrating the application facing the error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the dja ngo_migrations table (ORA-02000: missing ALWAYS keyword) application environment 1.windows10 2.Python 3.6.x 3.Django 2.0.2 4.oracle 11g XE in settins.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'abc', 'PASSWORD':'xxxx', 'HOST':'localhost', 'PORT':"1521", } -
django ugettext msguniq: too many errors, aborting
I was working with ugettext for translation and it was ok , but i dont know what has happened that when i write django-admin makemessages on command, it shows this lots of errors: CommandError: errors happened while running msguniq C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite \locale\d jango.pot:25:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:25: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:42: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:55: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:60: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65:3: syntax error C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65: keyword "models" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:65: keyword "py" unknown C:\Users\pouyasystem\Desktop\Project\BallBearingProject\BallbearingSite\locale\d jango.pot:70:3: syntax error msguniq: too many errors, aborting I also have imported from django.utils.translation import ugettext as _ at the top of my codes -
HttpResponse. How to use it properly?
all. I am newest in Django and I have a question. I want learn what I need return to ajax get/post request. I have example, but I know it is not good. Can u please explain me about responses? When, what and why? I did not find any information about it. When I click on button, object will delete from data base. This is my ajax request: function removeProduct(){ $('.btn-remove').click(function(e){ e.preventDefault(); var data = {}; data["csrfmiddlewaretoken"] = $('#quantity_goods [name="csrfmiddlewaretoken"]').val(); var product = $(this); data.product_id = product.data("product_id"); var url = product.attr("action"); $.ajax({ url: url, type: 'POST', data: data, cache: true, success: location.reload(), }); }); } This is my view: def remove_product(request): """Remove product from basket.""" data = request.POST product_id = data.get('product_id') product = ProductInOrder.objects.filter(id=product_id) product.delete() return HttpResponse() -
working with django forms and templates
I am working with django frame work as fresher and my senior gave me the template and told me to create a Form which contains 4 fields(name,email address,phone number,message), the main task is the above field details when filled and clicked on send button the data should be received on his email address. Please help with this. {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <style> body{ background: url('{% static "img/new4.jpg" %}') no-repeat center fixed; - webkit- background: cover; - moz - background: cover; - o - background: cover; background-size: cover; } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Personality Leading.com</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom' %}"> --> <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom.css' %}"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <div class="mynav"> <div class="p-3 mb-2 bg-info text-white"><strong> PERSONALITY LEADING </strong></div> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand" href="index.html"></a> <button … -
how should I access a view function with a Custom name from urls?
I have a API view class with some custom named functions, like this: class UserList (APIView): def listusers (self , request): users = User.objects.all() jason = UserSerializer (users , many=True) return Response (jason.data) how could i tell the url patterns when you got an special url do what in this function? -
Django admin, changelist_view, ModelAdmin seems to act like a singleton
I noticed a strange behaviour while extending ModelAdmin. I have this code: class MakeModelAdmin(admin.ModelAdmin): ... def changelist_view(self, request, extra_context=None): if request.user.is_superuser: self.list_display = ['company', 'name'] # else: # self.list_display = ['name'] return super().changelist_view(request, extra_context=extra_context,) The goal is to change list_display dynamically based on user (supervisor or not). I log in with two different users, in two different browsers, one of them results to be a superuser, the other isn't. self.list_display is set by one of users but debugging the request with the other user I can see the variable still set, so it changes the next behavior of the other user's view. Uncommenting the lines it works but I don't like it at all. It seems to me it's acting like a singleton. I also tried to change to: super(MakeModelAdmin, self).changelist_view(request, extra_context=extra_context,) But it has the same effect. Is there any solution for that? Maybe this is not the right way to achieve my goal? -
(CSRF token missing or incorrect.) using AJAX in Django
So I am trying to create some basic search functionality to my Django project using Ajax. However, I keep getting an error about the CSRF token. Here is the javascript in my template: <script type='text/javascript'> var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $('#search').keyup(function () { var search_text = $(this).val(); console.log(search_text); $.ajax({ type: "POST", url: "/search/", data: { 'search_text': search_text, }, success: function (data) { console.log('it worked'); }, }); }); </script> Any ideas why this isn't working? -
How to display uploaded file to user
I have a django view function that allows the user to upload a file. After the upload completes, the user just needs to be shown a file on a page. If I save the file, I can find it the media cdn I've set up and can view it using the link generated in the table in django admin, but what I'm trying to do is return the image that the user uploaded as a response back to them to view it. Here is the code I have for the view: def home(request): title = "Upload your photo" form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): instance = form.save(commit=False) instance.save() name = "" for filename, file in request.FILES.iteritems(): name = request.FILES[filename] imageFileName = name imageUrl = imageFileName if form != None: return HttpResponseRedirect(imageUrl) context = { "title" : title, "form" : form } return render(request, "home.html",context) Right now, when the image is uploaded, the user is just redirected to a url with the filename concatenated to the original url but the image isn't displaying. How can I redirect the user to a page with the image they just uploaded? -
Failing to connect to mysocket.sock, connection refused (gunicorn, nginx)
Full error: 2018/03/12 04:59:08 [error] 1562#1562: *1787 connect() to unix:/home/mik e/movingcollage/movingcollage.sock failed (111: Connection refused) whil e connecting to upstream, client: 107.205.110.154, server: movingcollage .com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/mike/movin gcollage/movingcollage.sock:/", host: "movingcollage.com" My config is ok, this used to work; I pulled some new application code and am now getting a 502 bad gateway error (before I pulled the application code the site worked fine). I already did service gunicorn restart and systemctl restart gunicorn and am still getting the 502 bad gateway error. Can anyone help? This is a django project, for what it's worth.