Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why consecutive calls to update with empty dict in RequestContext.__init__?
The following is the implementation of the __init__ method in RequestContext def __init__(self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True): super(RequestContext, self).__init__( dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = request self._processors = () if processors is None else tuple(processors) self._processors_index = len(self.dicts) # placeholder for context processors output self.update({}) # empty dict for any new modifications # (so that context processors don't overwrite them) self.update({}) As you can see, it calls self.update({}) consecutively without any operation in between. While the comment preceding each call mentioned what it's doing, I still failed to see the difference because without the comment, it looks like this: def __init__(self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True): super(RequestContext, self).__init__( dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = request self._processors = () if processors is None else tuple(processors) self._processors_index = len(self.dicts) self.update({}) self.update({}) Is the second call not redundant? -
Python Django framework: deciding a model field's default value by primary key
In Django, is there a way to decide what kind of value I want to use for my model's field's default value, relatively to this model instance's primary key? ex: if I have a Question object that has a field question_title what I'm trying to do is to set up this field as: question_title = models.CharField(max_length=100, default="title") but instead of just say default="title", I would like to say: default="title"+self.pk The problem is, (at least I think what the problem is) that when the class member been defined at runtime, there is no instantiation, so from Python interpretor level, there is no way to know what value of self.pk has. if yes, I tried to implement the init() function, but still get a type error: class Question(models.Model): question_title = models.CharField(max_length=100, default="untitled") question_text = models.CharField(max_length=200, default ="content") def __init__(self): self.question_title = models.CharField(max_length=100, default="title"+str(self.pk)) self.question_text = models.CharField(max_length=200, default ="content") def __str__(self): return self.question_title the error msg is: __init__() takes exactly 1 argument (4 given) -
Cannot get to Django root url (r'^$') after deploying to Elastic Beanstalk, all other routes work
When deploying a django project to AWS Elastic Beanstalk, I am able to get to all of my urlpatterns except the root pattern (i.e. what should map to sitename-staging.us-east-1.elasticbeanstalk.com). The page never loads anything and eventually chrome shows ERR_CONNECTION_TIMED_OUT. Note that I am able to get to all my other routes (i.e. sitename-staging.us-east-1.elasticbeanstalk.com/members, /admin, etc) and all the static files are on S3 and seem to be working. urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^users/', include('sitename.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), url(r'^members/', include('sitename.members.urls', namespace='members')), url(r'^contact/', include('sitename.contact.urls', namespace='contact')), url(r'^settings/', include('sitename.sitesettings.urls', namespace='settings')), url(r'^history/$', views.flatpage, {'url': '/history/'}, name='history'), url(settings.ADMIN_URL, include(admin.site.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) There are no errors during deployment and the health shows ok on the dashboard. I am able to get to my root route as expected when running locally or with docker. This isn't an issue with the template I am trying to route to as I can change the route and it will load correctly at the new route: ex: url(r'^test$', TemplateView.as_view(template_name='pages/home.html'), name='home'), I have tried moving the ^$ route up and down above the other named routes but that doesn't seem to work Nothing is sticking out in the logs, but it seems as if the request never even gets … -
Python program works in shell but in console
I'm writing a program that enables my Django application to consume a REST API. My problem is that Django rejects the program if I run it as a .py file, but accepts it via shell. The program is divided into two files: one that interacts with the API, and another that interacts with Django. The main folder structure is as follows: /root folder [rest of Django project] -__init__.py -test.py -mid_side.py -teamup_api/ -__init__.py -teamup.py where test.py is the file that starts the program, mid_side.py is the Django-side part, and teamup.py is the API-side part. Below is the specific code I'm having trouble with. test.py import django from mid_side import dates from datetime import datetime start = datetime(2017,7,28) end = datetime(2017,8,19) test = dates(start,end) print(test) Where dates is a method from mid_side that accepts two datetime objects as parameters. According to Django, the problem emerges in mid_side.py, as it imports models from an app in the main Django project. The specific line Django has issues with is from events.models import Service, where events is an app Django uses and Services is a model. The traceback is Traceback (most recent call last): File "test.py", line 2, in <module> from mid_side import dates File … -
seperate out lengthy logic from class based view django
I'm still new to Django and I'm trying to do a word unscrambler site/app in Django. I've already written the code in python and it's about 30 lines or so. I was wondering if there is way to separate out this logic from my views.py. I've tried searching for it but not having any luck. Surely there is as I can only imagine with a real/larger Django project the views.py file would get really big without it. Any ideas or references you all know of? Thanks in advance! -
How to capture form values and send them via email as ajax request ? Rails
I'm trying to setup a simple form where the user types in his email address to subscribe for a newsletter. I then receive an email with the user's email address. This is what I tried so far: The form: <%= form_with(model: @subscribe, id: 'sub_form') do |f| %> <input type="email" name="email" placeholder="Your email address" id="sub_email"> <button class="btn btn-success" type="submit" id="sub_btn">Subscribe</button><br> <p id="sub_output" class="lead" style="color: white;"></p> <% end %> The route get 'subscribe/', :to => 'welcome3#subscribe', as: "email_subscribtion" The controller: class Welcome3Controller < ApplicationController def subscribe EmailMeMailer.confirmation().deliver end end The mailer: class EmailMeMailer < ApplicationMailer default from: "info@example.com" def confirmation @greeting = "Hi" mail to: "my_email_address@gmail.com", subject: "subscribtion confirmation" end end JQuery Ajax method: $('#sub_form').submit(function(e) { e.preventDefault(); }).validate({ rules: { email: { required: true, email: true }, }, submitHandler: function (form) { var btn = $('#sub_btn'); btn.button('loading'); setTimeout(function() { btn.button('reset'); }, 3000); $.ajax({ type: 'POST', url: '/subscribe', // data: form.serialize(), dataType: 'json', async: true, data: { csrfmiddlewaretoken: '{{csrf_token}}', sub_email: $('#sub_email').val(), }, success: function (json) { $('#sub_output').html(json.message); $("#sub_email").prop('disabled', true); } }); return false; // for demo } }); I'm stuck at: how do I capture the submitted email address and send it to myself ? I'm not using any models to save data. … -
Convert list of list of dictionaries to multiple lists for use with Plotly
I have a large list of lists that I've generated based on pulling data from some Django models. I'm trying to combine that data into lists for use with a stacked Plotly bar chart. Below is a subset example of the data I'm getting: data_list = [ [{'assignee': 'Person 1', 'assignment_group': 'Group A', 'assignee__count': 7}], [{'assignee': 'Person 2', 'assignment_group': 'Group B', 'assignee__count': 25}], [{'assignee': 'Person 3', 'assignment_group': 'Group C', 'assignee__count': 33}], [{'assignee': 'Person 4', 'assignment_group': 'Group B', 'assignee__count': 3}], [{'assignee': 'Person 5', 'assignment_group': 'Group D', 'assignee__count': 12}, {'assignee': 'Person 5', 'assignment_group': 'Group C', 'assignee__count': 10}], [{'assignee': 'Person 6', 'assignment_group': 'Group E', 'assignee__count': 1}, {'assignee': 'Person 6', 'assignment_group': 'Group B', 'assignee__count': 3}, {'assignee': 'Person 6', 'assignment_group': 'Group F', 'assignee__count': 2}], [{'assignee': 'Person 7', 'assignment_group': 'Backups', 'assignee__count': 4}, {'assignee': 'Person 7', 'assignment_group': 'Group B', 'assignee__count': 2}], [{'assignee': 'Person 7', 'assignment_group': 'Group B', 'assignee__count': 6}]] What I'm ending up needing is three lists (assignee, assignment_group, and count). The latter two, assignment_group and count will probably be a list of lists as I need each list to be the same length. assignment_group would contain six items (one for each group), then for each assignment_group, there would be a list in a list for assignee … -
Django - How to update views based on dropdown selection from frontend?
I'm stuck with a problem for last few days. I want on frontend when a user selects an item from drop down list, a kind of signal is sent to Django backend with the primary-key of the item selected. Models.py: class Company(models.Model): name = models.CharField(max_length=10, blank=True, null=True) code = models.CharField(max_length=2, blank=True, null=True) I send this model to HTML and unpack it: {% load staticfiles %} {% load i18n %} <!DOCTYPE html> <html> <head> </head> <body> <form action="" method="GET" id="selection-form"> {% csrf_token %} <select> {% for company in company_list %} <option> {{ company.name }} </option> {% endfor %} </select> <input type="button" value="Update" id="selection-button"> </form> </body> </html> Now the user get the option to select e.g. Company A, Company B and Company C. If the user selects say Company A and click the 'Update' button, it sends the primary-key to views.py Views.py: def company_selected(request): if request.method === 'GET': selection = request.GET.get() // Not sure what to have within .get() selected_company = Company.objects.filter(pk=selection) return selected_company I'm actually not sure if I'm doing it correctly in views.py or not. What kind of signal is sent from front-end that can help to identify the primary-key of the option selected? -
How to clone querysets and give each an unique identifier?
An odd way to use Django but I get through my view 5 different objects and I'd like to clone those 3 queries * 3 and alter each of them slightly to show it on my template (which makes 9 different results shown to the user). each shape has their own unique identifier and contains specific json that'll also be overrided by new values. shapes = Shape.objects.all() #let's say this shows 3 objects #from : shapes = <QuerySet [<Shape: triangle>, <Shape: round>, <Shape: cynlinder>> #to : shapes = <QuerySet [<Shape: triangle>, <Shape: round>, <Shape: cynlinder>, <Shape: triangle>, <Shape: round>, <Shape: cynlinder>, <Shape: triangle>, <Shape: round>, <Shape: cynlinder>> tmp_shapes = [] for shape in shapes: shape.identifier = str(uuid.uuid4()) tmp_shapes.append(shape) return render(request, 'creation_results.html', { 'shapes': tmp_shapes, }) I wasn't sure how I could achieve this since shapes will be shown on a form as radio and I have to get back the selected shape again in order send it to server on form submit, is this possible ? -
Volume share from container to host docker-compose
I'm trying to share data between container and host. So I just want to do this to store container files. The data must be shared from a container to host. My docker-compose.yml version: "3.3" services: django: image: python:slim volumes: - type: volume source: ./env target: /usr/local/lib/python3.6/site-packages volume: nocopy: true - ./src:/usr/src/app ports: - '80:80' working_dir: /usr/src/app command: bash -c "pip install -r requirements.txt && python manage.py runserver" When I run docker throws this: ERROR: for django Cannot create container for service django: invalid bind mount spec "/Users/gustavoopb/git/adv/env:/usr/local/lib/python3.6/site-packages:nocopy": invalid volume specification: '/Users/gustavoopb/git/adv/env:/usr/local/lib/python3.6/site-packages:nocopy': invalid mount config for type "bind": field VolumeOptions must not be specified ERROR: Encountered errors while bringing up the project. https://docs.docker.com/compose/compose-file/#long-syntax-3 -
Keep data of fields after submit a form with an error on django
After I submit a form with an error with django, all fields of the form are cleaned. I want to keep the information on the fields, because it will help the users when they are submiting data. This is my views.py of the aplication: def new(request): context = {} if request.method == 'POST': form = NewSubject(request.POST) if form.is_valid(): context['is_valid'] = True form.save() form = NewSubject() else: context['is_valid'] = False else: form = NewSubject() context['form'] = form return render(request, 'subjects/new.html', context) -
Form Confirmation
I'm trying to pass data from a successful form submission to a thank you page that could then display this data. I am trying to do a reverse HttpResponseRedirect but i keep getting this error: NoReverseMatch at /contactform/process Reverse for 'thankyou' with arguments '(24,)' not found. 1 pattern(s) tried: [u'contactform/thankyou/$'] Here is the code i have so far: views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Contact_Object def index(request): template_name = 'contactform/index.html' return render(request, 'contactform/index.html') def thankyou(request, entered_id): contact_info = get_object_or_404(Contact_Object, pk=contact_object_id) template_name = 'contactform/thankyou.html' return render(request, 'contactform/thankyou.html', {name: contact_info.name}) def process(request): entered_name = request.POST['fullname'] entered_email = request.POST['email'] entered_message = request.POST['message'] entered = Contact_Object(name=entered_name, email=entered_email, message=entered_message) entered.save() entered_id = entered.id return HttpResponseRedirect(reverse('contactform:thankyou', args=(entered.id,))) urls.py from django.conf.urls import url from . import views app_name = 'contactform' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^thankyou/$', views.thankyou, name='thankyou'), url(r'^process$', views.process, name='process'), ] Template for Form <H1>Contact Form</H1> <FORM action="{% url 'contactform:process' %}" method="post"> {% csrf_token %} Full Name:<br> <input type="text" name="fullname"><br> Email:<br> <input type="text" name="email" ><br> Message:<br> <textarea name="message" cols="40" rows="5"></textarea> <input type="submit" value="Enter"> </FORM> Template for Thank you page <h1>Thank You</h1> <p>Thank you, {% contact_info.name %}</p> I'm new to working … -
Django redirect inside a function
I am trying to build forum. When processing urls there is a board id and a board name. The board name exists just for user readability meaning if someone enters the id correctly but the board name is wrong or has changed it will redirect them to the correct url. I created a function to manage this because there are multiple times I need to check if the board is right, not just this one url. # urls.py ... url(r'^boards/(?P<board_id>\d+)/(?P<board_name>[^/]+)/$', views.board, name='board'), ... # views.py def board(request, board_id, board_name): RedirectIfWrong(request, board_id, board_name) ... return render(request, 'forums/board.html', {'board': board}) def RedirectIfWrong(request, pk, name): board = Board.objects.all().get(pk=pk) if (board.name != name): return redirect(request.get_full_path().replace(name, board.name, 1)) However when I call redirect inside a function it does not work. I have also heard of using middleware to do this. How does that work and how do I make it only apply to urls involving a board? -
Better Approach to design a DB for User and Products Schema using Django
So i am attempting to design a database where users can sell their products. Basically a user can sell many products and a product can be sold by many users. Now i'm attempting to do this in django. I have 2 solutions and will like to get feed back on which will be appropriate. 1st Approach: Have a class called Product that has the following attributes and just do a many to many mapping on the Product class: class Product(models.Model): name = models.CharField('product_name',max_length=100) description = models.CharField('description', max_length=255) quantity = models.IntegerField() price = models.DecimalField('price', max_digits=6, decimal_place=2) userId = models.ManyToManyField(User) class ProductImages(models.Model): productId = models.OneToManyField(Product, on_delete=models.Cascade) 2nd Approach: I decided to have the Product class just have a name and make the name field unique. The reason behind this if another used decided to add a product of the same name, and if it already exists just get the id of the name and add it to another class or table called User_Product. The class User_Product will be composed of description, quantity, price, userId, and productId. The class will be defined as follows: class Product(models.Model): name = models.CharField('product_name',max_length=100, unique=True) class User_Products(models.Model): description = models.CharField('description', max_length=255) quantity = models.IntegerField() price = models.DecimalField('price', max_digits=6, … -
Django order by issue
I don't know how to do to order by in this situation. May be someone knows. I have 2 models : Comments : class Comments(models.Model): text = models.CharField(max_length=300, null=False) image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True) articles = models.ForeignKey(Articles, verbose_name="Article", null=False) author = models.ForeignKey(User, verbose_name="Auteur") in_answer_to = models.ForeignKey('self', verbose_name="En réponse au commentaire", blank=True, null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") And a Up model : class Up(models.Model): comments = models.ForeignKey(Comments, verbose_name="Commentaire", null=True, blank=True) user = models.ForeignKey(User, verbose_name="Auteur", null=False) Users can add comments and they can "Up" some usefull comments. So, by default I want to order comments by date. However I want to priorize the order by number of Up. To give you an idea how comments and Up are register, this is a screenshot of my database : Comments : Up : For example, the comment where id is 50 has 2 Up from two differents users. So it should be at top of the list compared to the comment 49 which only have 1 Up. For now, I just use the order by date and I need the order by Up : comments = Comments.objects.all().exclude(in_answer_to__isnull=False).order_by('-date') I need something like : comments = … -
django queryset filter foreignkey
I'm having problems trying to use the queryset filter with my models. It is a control for posts in groups. This is my code: class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() class Group(models.Model): title = models.CharField(max_length=200) url = models.URLField(unique=True) class Control(models.Model): published = models.DateField(auto_now=False, auto_now_add=False) group = models.ForeignKey(Group, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) I'm trying to get all posts from a group with the title "title": queryset_list = Control.objects.filter(group__control="title") My models might nit be right, I'm new to this. Any help? -
JSON parse error on POST request
I used django-cors-headers, and config it. Backend: Django 1.11 + django-rest-framework 3.6.3 settings.py ALLOWED_HOSTS = ['*'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True python manage.py runserver 192.168.1.111:8000 Frontend: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $.ajax({url: "http://192.168.1.111:8000/api/user/forgot_password/", type: "post", data: {"email": "nikhil.29bagul@gmail.com"}, headers:{"Content-Type":"application/json"}, success: function(result){ $("#div1").html(result); }}); }); }); </script> </head> <body> <div id="div1"></div> <button>Forget Password</button> </body> </html> Getting 400 response for POST request and response content {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} But when I am calling this API from postman its work properly. How can i resolved this issue? -
Cannot see new SQL tables in Django online interface on PythonAnywhere
As part of hosting my website I have an SQL server on pythonanywhere.com with some data collected from my website. I need to aggregate some of the information into a new table stored in the same database. If I use the code below I can create a new table as observed by the SHOW TABLES query. However, I cannot see that table in the Django online interface provided alongside the SQL server. Why is that the case? How can I make the new visible on the Django interface so I can browse the content and modify it? from __future__ import print_function from mysql.connector import connect as sql_connect import sshtunnel from sshtunnel import SSHTunnelForwarder from copy import deepcopy sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 def try_query(query): try: cursor.execute(query) connection.commit() except Exception: connection.rollback() raise if __name__ == '__main__': remote_bind_address = ('{}.mysql.pythonanywhere-services.com'.format(SSH_USERNAME), 3306) tunnel = SSHTunnelForwarder(('ssh.pythonanywhere.com'), ssh_username=SSH_USERNAME, ssh_password=SSH_PASSWORD, remote_bind_address=remote_bind_address) tunnel.start() connection = sql_connect(user=SSH_USERNAME, password=DATABASE_PASSWORD, host='127.0.0.1', port=tunnel.local_bind_port, database=DATABASE_NAME) print("Connection successful!") cursor = connection.cursor() # get the cursor cursor.execute("USE {}".format(DATABASE_NAME)) # select the database cursor.execute("SHOW TABLES") prev_tables = deepcopy(cursor.fetchall()) try_query("CREATE TABLE IF NOT EXISTS TestTable(TestName VARCHAR(255) PRIMARY KEY, SupplInfo VARCHAR(255))") print("Created table.") cursor.execute("SHOW TABLES") new_tables = deepcopy(cursor.fetchall()) -
Angular 2/4 authentication to Django rest_framework_jwt using custom model
How are you eveyone. I am developing Angular 4 website using Django Backend server. To use JWT for authentication, I am using rest_framework_jwt module of Django. Also I am using custom model for authentication(there are some reason for that) I tried authentication using default authentication model and It works well. But I am not sure how to use custom model for authentication with rest_framework_jwt in Django. Example code or link will be big help! :) Thanks for your consideration. -
Django __init__() takes 1 positional argument but 2 were given
i'm have problem with django, i'm tried created second page in django but get typeerror, i'm need help, where i'm did can make mistake, i'm first time created in django site, and i did tried read documentation but it's hard to me now. **__init__.py** default_app_config = 'page.apps.PageConfig' **urls.py** from django.conf.urls import url from . import views urlpatterns = [ # url(r'^$', views.IndexView.as_view(), name='index' ), url(r'^$', views.IndexView, name='index'), ] **view.py** from django.views.generic import TemplateView from libs.views import CachedViewMixin from .models import Page class IndexView(CachedViewMixin, TemplateView): template_name = 'main/index.html' config = None **model.py** from django.db import models from django.utils.translation import ugettext_lazy as _, ugettext from solo.models import SingletonModel class Page(SingletonModel): updated = models.DateTimeField(_('change date'), auto_now=True) class Meta: default_permissions = ('change',) verbose_name = _('settings') def __str__(self): return ugettext('Home page') **apps.py** from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class PageConfig(AppConfig): name = 'page' verbose_name = _('Another page') -
Converting if else flow from Django to Ruby on Rails
I need to convert this Django If Else flow to Ruby on Rails: This is the Django code: <select name="level" id="level"> {% if level == 'gold' %} <option value="gold" selected>Gold</option> {% else %} <option value="gold" >Gold</option> {% endif %} {% if level == 'silver'%} <option value="silver" selected="">Silver</option> {% else %} <option value="silver" >Silver</option> {% endif %} % if level == 'bronze' %} <option value="bronze" selected="">Bronze</option> {% else %} <option value="bronze" >Bronze</option> {% endif %} </select> This is the RoR version I did: <select name="level" id="level"> <% if @package_signup.level == 'gold' %> <option value="gold" selected>Gold</option> <% else %> <option value="gold" >Gold</option> <% end %> <% if @package_signup.level == 'silver' %> <option value="silver" selected="">Silver</option> <% else %> <option value="silver" >Silver</option> <% end %> <% if @package_signup.level == 'bronze' %> <option value="bronze" selected="">Bronze</option> <% else %> <option value="bronze" >Bronze</option> <% end %> </select> This is the controller (I'm trying to access the level variable): class Welcome2Controller < ApplicationController def pricing @package_signup = params[:level] end end This is the error I receive: undefined method `level' for "bronze":String -
Why does Jinja not transfer tags in blocks into html file which is extended?
guys! I'm very new at Django, and there is a problem appearred: There are two files (landing.html and test_jinja.html) and I'm trying to extend first file with Jinja's code, but the tags inside the block can't reach landing.html: This is the jinja_test.html code: {% extends 'landing/landing.html' %} {% block content %} <h1>Hello!</h1> {% endblock %} ======================================================================== This is the part of html code, where block is situated: <div class="col-sm-10"> <div class='container-fluid'> <br><br> {% block content %} {% endblock %} </div> </div> P.S.: All links to static files (img,css etc) in landing.html are working. Python 3.6; PyCharm 2017.1. -
Getting error when importing from sibling package
I am learning django, following on Tango with Django. My project structure is as follows: /django_demo |-- __init__.py |-- manage.py |-- populate.py |-- settings.py |.....<other modules> | |--/django_demo | |-- __init__.py | |-- populate_rango.py | |...<other modules> | |--/rango | |-- __init__.py | |-- models.py | |-- apps.py | |....<other modules> I am not able to resolve two queries: Query 1 - populate_rango.py contains the following code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_demo.settings') import django django.setup() from django_demo.rango import models the models import is giving unresolved import error, even though I am using the correct absolute imports notation, acc. to the documentation. i saw the following questions Sibling package imports - 1 and sibling package imports - 2 but got no answer for the above behavior. Query 2 - the populate.py under the root /django-demo package contains the following code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_demo.settings') import django django.setup() from rango import models questions like subfolder import - 1 and subfolder import - 2 specify that it is mandatory to either use the absolute import or the dotted notation to import from sub-folder. the above piece of code uses neither. I am not able to understand how does the from rango import models doesn't … -
jquery parse data array unexpected token
I have a problem parsing data array with jquery parseJSON, returns SyntaxError:Unexpected token , in JSON at position 1 var selected = $( 'input[type=radio][name=packs]:checked' ); gf_allowed= $.parseJSON(selected.data('gf_allowed')); This is the data tag <input type="radio" name="packs" value="361" data-price="22,00" data-desc=" 2 GGFF + BUGGIE(22.00EUR pax)" data-gf_exact="True" data-gf_allowed="[&quot;2&quot;, &quot;4&quot;]"> What I´m doing wrong? -
How to get scrambled image file name from models to views django
I'm trying to get scrambled name of image that will be uploaded and send it to views. In views I know how to get real name of image but how do I get scrambled name from models? models.py from django.db import models import uuid def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) def filename(instance, filename): return filename # Create your models here. class UploadImage(models.Model): # print (scramble_uploaded_filename) image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename) img_type = models.IntegerField("Image type") created = models.DateTimeField(auto_now_add=True) user = models.CharField(default='1',max_length= 100,editable=False) views.py import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from rest_framework import viewsets from api.models import UploadImage from api.serializers import UploadedImageSerializer from rest_framework import authentication, permissions from rest_framework.parsers import MultiPartParser,FormParser import MySQLdb class FileUploadViewSet(viewsets.ModelViewSet): #create queryset view permission_classes = (permissions.IsAuthenticated,) queryset = UploadImage.objects.filter(id=1,user='auth.User') serializer_class = UploadedImageSerializer parser_classes = (MultiPartParser, FormParser,) #after post action get this def perform_create(self, serializer): #grab request image_name = self.request.data['image'] username = self.request.user #grab scrambled filename