Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loop Through Variables for Endpoint in Python
We are using Django to GET data from a number of shops via the below endpoint. Each shop has an API key and password stored via settings.{shop}_API_KEY and settings.{shop}_PASSWORD. How do we loop through each shop in Python or (JS using fetch and parse)? orders_endpoint = 'https://{api_key}:{password}@{shop}.site.com/admin/orders/count.json' orders_url = orders_endpoint.format(api_key=settings.{shop}_API_KEY, password=settings.{shop}_PASSWORD) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json)) -
Restore tensorflow saved model from Django webapp
I have a tensorflow saved model. I can restore and run the model on test dataset as follows df = pd.read_csv('data/testdata.csv', sep='\t') Y_test = df['label'] X_test = df.drop('label', 1) class_names = np.unique(df['label']) classifier = SupervisedDBNClassification.load('data/model.pkl') Y_pred = classifier.predict(X_test) Whenever I run this code from terminal this works just fine. But run the same code inside a Django webapp and it gives following error File "/media/bcc/Others/CNV TH/mysite/dbn_new/tf_models.py", line 205, in from_dict sess.run(tf.variables_initializer([getattr(instance, name) for name in cls._get_weight_variables_names()])) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 789, in run run_metadata_ptr) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 927, in _run raise RuntimeError('The Session graph is empty. Add operations to the ' RuntimeError: The Session graph is empty. Add operations to the graph before calling run(). [19/Feb/2018 17:35:16] "POST /home HTTP/1.1" 500 132429 I don't understand what am I missing here. Do I have to run the code some other way to restore tensorflow model from Django webapp? -
Not able to query UserProfile model in django interactive console
I am creating an UserProfile models by extending User model as below, from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): # Below line links UserProfile to an User model instance user = models.OneToOneField(User) # Now add however additional attribues you want to add website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images',blank=True) def __str__(self): return self.user.username after this I am going into django interactive shell and querying the above model as below, UserProfile.objects.all() I am expecting that by running this I will get an empty set as I have not added anything. But I am getting the below error, UserProfile not defined How do I fix this? -
Partial html replacement in when form is submitted
I have a Django application which requires a user to fill in a number of forms directly after one another. I have been previously doing this purely in the view but now I am trying to move away from this towards a more JavaScript oriented way. What I am trying to do is introduce intercooler into the application, and so I am trying to build a small poc to test it. I have seen lots of people say how well Django and intercooler work together but I am struggling to get this set up. Say I have two simple forms: from django.forms import ModelForm from . import models class EventStep1Form(ModelForm): class Meta: model = models.EventStep1 fields = ['name', 'description',] class EventStep2Form(ModelForm): class Meta: model = models.EventStep2 fields = ['url', 'schema', 'username', 'password',] All the fields are CharFields and the simplest view possible (it essentially just contains the form_class). I have my template set up like this: {% extends 'base.html' %} {% block content %} <div id="event-forms"> <form method="post" ic-post-to="{% url 'step2' %}"> {% csrf_token %} {{ form }} <button class="btn btn-primary">Next</button> </form> </div> {% endblock content %} but this isn't working. I have taken a look at this short tutorial … -
Django: Using backwards relationships in views.py
So I'm trying to pass an object to my HTML template consisting of the parent object and all child objects that relate to it. For instance: Model Chamber: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Has ChamberProperty: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100) user_defined = models.BooleanField(default=True) They are two separate models because the customer can add as many properties as they want to their chamber. In my views.py class ChambersView(generic.DetailView): template_name = 'pages/chambers.html' def get(self, request): user = User.objects.get(username=request.user) customer = Customer.objects.get(user=user) chambers_list = list(Chamber.objects.filter(customer=customer)) try: chamber_properties = list(ChamberProperty.objects.filter(chamber__in=chambers_list).order_by('id')) except: car_properties = "No properties" form = ChambersFilterForm(request=request) return render(request, self.template_name, {'filter_form':form, 'chambers_list': chambers_list, 'chamber_properties': chamber_properties}) Now, that does get me a list of all cars, and a list of all car properties. Except they're not linked to each other. I'm not sure how to build a list of related objects. I read about backwards relationships just now, but I don't seem to grasp how to use them. I tried the following: chambers_and_props = Chamber.chamberproperty_set.all() And I get the following error: AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all' So I'm not quite sure how to use it. The threads I saw mentioned that … -
Make Django REST API accept a list
I'm working on a functionality where I need to be able to post a list consisting of properties to the API. A property has a name, value and unit. Now I have two questions: How exactly should my list look for the API to accept it as a correct list from the get go? Should I parse the list as Objects? Or is a plain list fine? I am using the Django REST framework and I have made the API using this tutorial (works perfectly). But how do I make Django accept multiple objects/a list? I have read that it is as simple as adding many = True to where you instantiate the serializer, which I do here: class PropertyViewSet(viewsets.ModelViewSet): queryset = Property.objects.all() serializer_class = PropertySerializer So I tried doing serializer = PropertySerializer(queryset, many=True), which broke the API view. So I think I have to create a new serializer and view just for this (am I right)? But how do I make sure that my API knows which one to use at the right time? If anyone could clarify this that would be great, thanks. -
Django with pandas or odo: unable to update postgresql database
I'm working on a website where users can upload csv files to update the database. It was working using python's csv module and Django's ORM (model_instance.save()) but obviously it was painfully slow, so I turned to pandas' to_sql and to odo, via blaze. In both of these cases I'm unable to update the database; no error messages are displayed but you can see logs here and here. I can't update all the fields of a Value instance from the data, I'm guessing that might be the problem. The code is executed from inside a channels 2.x consumer, if that makes any difference. The csv files look like this: Timestamp Address (64bit) Zone Sensor Type Data type Value 12/23/16 00:05:09 0x13a2004149c71f 5 0 0 255 12/23/16 00:05:09 0x13a2004149c71f 5 0 1 514 12/23/16 00:05:09 0x13a2004149c71f 5 0 3 2331 models.py class CsvBuffer(models.Model): # file_name = models.CharField(max_length=255, default=None, null=True, blank=True) timestamp = models.DateTimeField(default=timezone.now) address = models.CharField(max_length=16) data_type = models.IntegerField(default=None, null=True, blank=True) value = models.IntegerField(default=None, null=True, blank=True) # ... class Device(models.Model): address = models.CharField(max_length=16, unique=True) serial = models.CharField(max_length=14, unique=True) complexe = models.ForeignKey(Complexe, on_delete=models.DO_NOTHING) building = models.ForeignKey(Building, on_delete=models.DO_NOTHING) unit = models.ForeignKey(Unit, on_delete=models.DO_NOTHING) devicetype = models.ForeignKey(DeviceType, on_delete=models.DO_NOTHING) room = models.ForeignKey(Room, on_delete=models.DO_NOTHING) def __str__(self): return self.address … -
How to provide a path to django project in one directory from a python project in another directory
I am having a django project in Projects folder with path '/home/pyral17/Projects/project1' and im having a python project on desktop with path '/home/pyral17/Desktop/pyproject'. Now i need to set path in django project from my python directory. where should i modify that path? Is it possible to append path or set up dynamic path instead of static path? Thankyou -
python error with devstack
can someone help me with this error: No handlers could be found for logger "openstack_dashboard.settings" Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/compilemessages.py", line 67, in handle basedirs.extend(upath(path) for path in settings.LOCALE_PATHS) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. +lib/horizon:configure_horizon:1 exit_trap +./stack.sh:exit_trap:510 local r=1 ++./stack.sh:exit_trap:511 jobs -p +./stack.sh:exit_trap:511 jobs= +./stack.sh:exit_trap:514 [[ -n '' ]] +./stack.sh:exit_trap:520 '[' -f /tmp/tmp.rvJ6EFfCY3 ']' +./stack.sh:exit_trap:521 rm /tmp/tmp.rvJ6EFfCY3 +./stack.sh:exit_trap:525 kill_spinner +./stack.sh:kill_spinner:424 '[' '!' -z '' ']' +./stack.sh:exit_trap:527 [[ 1 -ne 0 ]] +./stack.sh:exit_trap:528 echo 'Error on exit' Error on exit +./stack.sh:exit_trap:530 type -p generate-subunit +./stack.sh:exit_trap:531 generate-subunit 1519055792 418 fail +./stack.sh:exit_trap:533 [[ -z /opt/stack/logs ]] +./stack.sh:exit_trap:536 /opt/stack/devstack/tools/worlddump.py -d /opt/stack/logs World dumping... see /opt/stack/logs/worlddump-2018-02-19-160331.txt for details +./stack.sh:exit_trap:545 exit 1 i'm runnig devstack (a minimal version of openstack) and when i run the ./stack.sh i get error with python2.7 (django) … -
Error return truncatechars & safe by using Built-in template tags and filters
I try to Truncates the string and remove the html tags, First, when I write it this way. {{ post.context|safe }} or {{ post.context |truncatechars:100 }} The left navigation bar shows normal. But when I write this, this part of the HTML is gone. {{ post.context |truncatechars:100|safe }} But I can still find this Html in the source code. So what can I do to get the correct results?thank you -
How do we pass a variable to an endpoint in Python?
We are using Django and making a GET request to a remote server. The server returns an object for the given shop. How we pass the 'shop' variable through to the 'settings.{shop}_api_key' and 'settings.{shop}_password' so that it returns an object for each 'shop' in our database? shop = models.CharField(max_length=140, blank=True, null=True, default='EXAMPLE') orders_endpoint = 'https://{api_key}:{password}@{shop}.myshopify.com/admin/orders/count.json?status=any' orders_url = orders_endpoint.format(api_key=settings.EXAMPLE_API_KEY, password=settings.EXAMPLE_PASSWORD) -
Django + Postgres: Trying dump and restore database, but are seeing ERROR: relation "*_id_seq" does not exist for all sequence tables
I am trying to move a database from a virtual machine (docker-machine) over to a database server on azure. I am first using the following command to dump the database to a local file: pg_dump -h <virtual-machine-ip> -U <username> postgres > dump.sql Then I try to restore it on the new server: psql -h <database-server-ip> -U <username> -d <new_database_name> -f dump.sql Which produces a lot of errors (example below): psql:dump.sql:608: ERROR: relation "suppliers_supplierbundle_id_seq" does not exist psql:dump.sql:614: ERROR: relation "suppliers_supplierbundle_id_seq" does not exist CREATE TABLE ALTER TABLE psql:dump.sql:647: ERROR: syntax error at or near "AS" LINE 2: AS integer ^ psql:dump.sql:650: ERROR: relation "transactions_transaction_id_seq" does not exist psql:dump.sql:656: ERROR: relation "transactions_transaction_id_seq" does not exist CREATE TABLE ALTER TABLE psql:dump.sql:685: ERROR: syntax error at or near "AS" LINE 2: AS integer I have tried reading the docs on pg_dump, but whatever I do, I get the same result... Any idea of what is happening here? Have I missed some options that should have been included in the dump command? Thank you very much! -
How to filter "and not in" in Django query with Q?
I am working on Django project and basically it is kinda custom article system. So we have articles that are divided in Circle and Region. So for example I have Region1, Region2 and Region3 regions. Similarly I have Circle1, Circle2 and Circle3 circles. I have user that belong to one region and one circle. So lets say my user, User1 belongs to Region1 and Circle2. I have Article1 that was posted for Region1 and Circle1, Article2 that was posted for Region1 and Circle2, Article3 was posted for Region2 and Circle2. I need to filter article for this user in following way. Get me article(s) that belongs to my circle and not to my region, get me article(s) that belongs my circle and region both. What I have done so far is, Article.object.filter(is_archived=False).filter( Q(belongs_to_circle=self.cid) & Q(belongs_to_region=self.rid) | Q(belongs_to_circle=self.cid) & ~Q(belongs_to_region=self.rid) ) If I use to query to get articles that belongs to circle and region both, it works fine but I am trying to get articles that belongs to my circle but not in my region. So if Article was posted for Region1 and Circle2 I should get it. If Article was posted for Region2 and Circle2 I should get it, … -
How to create a custom signal in django?
I have been searching for a guide to write my own custom signals in django. Django documentation does a good job of giving details of individual topic, but does not give a working example of the same, and I can't seem to understand how to write my own custom signals. I searched online on various sites but it still does not ring any bells :P. Can anyone give a complete working example of the same? Thanks in advance. Regards. -
Django+Django-REST+AngularJS or maybe just AngularJS?
I pretty much a beginner and I am tasked to translate an Excel tool to a web based program. So pretty soon I favored Python since I think it's easy to use and is used extensively for calculations of all sorts. So I looked into the Django. Now I also needed to show graphs. "Coding for entrepreneurs" advised to use the Django-REST framework for this, so I looked into that also. Now I made a very limited functionality REST API. I.e. still very possible to trash this and go into a different direction... My thinking here is to detach the backbone (REST API) which solely deals with the bare bone information. And next I would like to connect this to a nice user interface. So I am now starting to look into AngularJS. Now AngularJS seems to be much more than a shiney front, and again has quitte the learning curve to master it. So it has been quitte a journey, I feel like I pull a string and just get more string. I am now wondering if it's just possible to write the whole applications using just AngularJS? Or am I on a viable and doable path devising a … -
Use Pillow resize with an ImageField
I am new to python and trying to use ImageField in my model. I have some images in files separate from my Django Project that I want to upload. So I have a Django model class Product(models.Model): img_thumbnail = models.ImageField(upload_to='products_images', blank=True, null=True) In my conversion code which uploads images, I want to generate thumbnails at a specific height so I can not use: img = Image.open(file_path) img.thumbnail() Instead, I calculate the necessary width and resize it using Pillow. img = Image.open(file_path) h_percent = (75/ float(img.size[1])) if h_percent < 1: width = int((float(img.size[0]) * float(h_percent))) img = img.resize((width, base_height), Image.ANTIALIAS) filename = os.path.basename(file_path) That works fine but when I tried to save that to an ImageField, I get an error: AttributeError: 'JpegImageFile' object has no attribute 'content' product.img_thumbnail.save(filename, img, True) Searching the web, I found reference to SimpleUploadedFile. So write the resized image with a suffix. I received another error; : 'charmap' codec can't decode byte 0x81 in position 251: character maps to file_root, file_ext = os.path.splitext(file_path) new_file_name = file_root + '_thumbnail' + file_ext img.save(new_file_name) filename = os.path.basename(file_path) with open(new_file_name) as infile: _file = SimpleUploadedFile(filename, infile.read()) So what should I do here? I am using Python 3.6 with Django 2.0 Thanks … -
How to serialize in Django Rest Framework with custom fields?
Let's say my model is: class Contact(models.Model): email = models.CharField(max_length=50) I want to have a serializer that receives multiple fields and then combine them to create an email. For example: class ContactSerializer(serializers.Serializer): first = serializers.CharField() second = serializers.CharField() third = serializers.CharField() It would convert {"first": "user", "second": "example", "third": "org"} to a new Contact object with the email 'user@example.org'. What should I do? -
Django: Rendering a table with 2 objects of variable size in HTML template
I've a bit of a dilemma here, and I'm not sure how best to approach it. I need to create a table of all objects in model "Chamber" and all objects in (ForeignKey related) model "ChamberProperties", except that the items in model "ChamberProperties" are user defined and not limited. Say model "Chamber" has 2 objects in it: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) With: Object 1: chamber_name: Lab Object 2: chamber_name: Production And the properties of the chambers are set up by the managers on site, so we don't know what they'll end up putting there. And the model "ChamberProperties" can have many related objects in it: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100) And for ChamberProperties: For example Chamber "Lab" may have: **ChamberProperties**: 1. Charge: 100v 2. Last test: yesterday 3. Scientist: Tom But Chamber "Production" may have many more: **ChamberProperties**: 1. Charge: 100000v 2. Error: 2018-02-19 11:55 3. Site: XK-1 4. Production: Foo 5. Risk: High My problem is in creating a table that shows all properties for all chamber in a HTML table. Both in constructing the HTML table itself and with filtering in the view. The table layout I was given is … -
Django celery beat with Django as backend
I'm trying to set up Django-celery-beat in order to create periodic tasks. My configuration is as follows: from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') celery = Celery(broker="django-db") celery.autodiscover_tasks() CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' I'm trying to use Django as database and run both the beat service and the workers. When I launch the workers like this: celery -A monitoring worker --loglevel=DEBUG --app=config.settings.local ... I get: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@django-db:5672//: [Errno 8] nodename nor servname provided, or not known. And when I try it when beat: celery -A monitoring beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler --app=config.settings.local I get this error: ERROR/MainProcess] beat: Connection error: [Errno 8] nodename nor servname provided, or not known. Trying again in 4.0 seconds... I'd like to be able to create periodic tasks through the Django admin but I'm stuck at this point so any help is welcome. -
Type Error with Django POST-Method
I'm pretty new to Django. I know that we had this topic before, but I couldn't find a solution in my research. I just want to POST a simple todo with a form but for some reason I get this Type Error: "TypeError at /todo/add/ expected string or bytes-like object" Hope you guys can spot my mistake. The Model: from django.db import models from datetime import* import time from django.utils.timesince import timesince from django.urls import* class Task(models.Model): task_title = models.CharField(max_length=50) complete = models.BooleanField(default=False) def get_absolute_url(self): return reverse('todo:detail', kwargs={'pk':self.pk}) def __str__(self): return self.task_title The Form: from django import forms class TodoForm(forms.Form): task_title = forms.CharField(max_length=50, widget=forms.TextInput(attrs{'class':'formcontrol','placeholder': 'Enter todo e.g. Delete junk files', 'aria-label' : 'Todo', 'aria-describedby' : 'add-btn'})) The View: @require_POST def addTodo(request): form = TodoForm(request.POST) print(form.errors) print(request.POST['task_title']) if request.method == 'POST': if form.is_valid(): new_todo = Task(task_title=request.POST['task_title']) new_todo.save() print('DONE') return redirect('index') The urls: from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # match list, url(r'^$', views.index, name='index'), url(r'^add/$', views.addTodo, name='add'), # match id goes to detail view url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] The template: <div class="sidebar"> <form action="{% url 'add' %}" method="POST" role="form"> {% csrf_token %} <div class="form-group"> <div class="input-group"> {{ form.errors }} {{ form.task_title }} … -
Django 2 url path matching negative value
In Django <2 the normal way of doing this is to use regex expression. But it is now recommended in Django => 2 to use path() instead of url() path('account/<int:code>/', views.account_code, name='account-code') This looks okay and works well matching url pattern /account/23/ /account/3000/ However, this issue is that I also want this to match negative integer like /account/-23/ Please how do I do this using path()? -
Rendering in Django 2.0.2
Could anybody help me, please? Django documantation says that 'render_to_response' is not used starting from the 2nd version. I can't display list on my template. For the model: class Partners(models.Model): title = models.CharField(max_length=256) description = models.TextField(blank=True) image = models.ImageField(upload_to="pictures", blank=True) link = models.URLField(max_length=128, blank=True) def __str__(self): return self.title i tried both of 2 methods: def partners(request): partners_list = Partners.objects.all() return render(request, 'partners.html', {'partners_list': partners_list}) and def partners(request): partners_list = Partners.objects.all() return TemplateResponse(request, 'partners.html', {'partners_list': partners_list}) Template is: {% for partners in partners_list %} <div class="col-sm-2" id="partners"> <div class="card"> <img class="card-img-top" src="{{partners.image.url}}" alt="Card image cap"> <div class="card-block"> <h4 class="card-title">{{partners.title}}</h4> <p class="card-text">{{partners.description}}</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Cras justo odio</li> </ul> <div class="card-block"> <a href="{{partners.link}}" class="card-link">Card link</a> </div> </div> </div>{% endfor %} Urls are: urlpatterns = [ path('admin/', admin.site.urls), path(r'', headpage, name='headpage'), path(r'about/', about, name='about'), path(r'partners/$', partners, name='partners'), ] What i do wrong? List of partners isn't displayed..Thank's a lot for your help! -
Ensure that a path to a dir is a Django project
For the last two days I am struggling with the following question: Given an absolute path (string) to a directory (inside my file system or the server, it doesn't matter), determine if this dir contains a valid Django project. First, I thought of looking for the manage.py underneath, but what if some user omit or rename this file? Secondly, I thought of locating the settings module but I want the project root, what if the settings is 2 or more levels deep? Third, I thought of locating the (standard) BASE_DIR name inside settings, but what if the user has not defined it or renamed it? Is there a way to properly identify a directory as a valid Django project? Am I missing something? -
Django admin: TypeError on any post request
I created a new Django (v. 1.11) project and using python manage.py createsuperuser I created a user. I can log in to the admin section on localhost:8888/admin with this user account. However, I cannot do anything else: whenever I trigger a POST request other than the login page, I get the following error: TypeError at /admin/... slice indices must be integers or None or have an __index__ method ("..." can be replaced for example by auth/group/add/), but this behavior is general, not specific to this request The following traceback suggests problem with parsing the CSRF token from the page, but I didn't have such issues on other pages within my application apart from admin. Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 178. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/middleware/csrf.py" in process_view 298. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py" in _get_post 126. self._load_post_and_files() File "/usr/local/lib/python2.7/site-packages/django/http/request.py" in _load_post_and_files 299. self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/local/lib/python2.7/site-packages/django/http/request.py" in parse_file_upload 258. return parser.parse() File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in parse 198. data = field_stream.read(size=read_size) File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in read 369. out = b''.join(parts()) File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in parts 364. emitting = chunk[:remaining] Exception Type: TypeError at /admin/auth/group/add/ Exception Value: slice indices must … -
I am trying to transfer data from one table to another in django. How can I do that?
class Project(models.Model): extra_1_label = models.TextField(blank=True, null=True) extra_2_label = models.TextField(blank=True, null=True) extra_3_label = models.TextField(blank=True, null=True) extra_1 = models.TextField(blank=True, null=True) extra_2 = models.TextField(blank=True, null=True) extra_3 = models.TextField(blank=True, null=True) class project2(models.Model): name = models.TextField(blank=True, null=True) value = models.TextField(blank=True, null=True) trying to move data from table project to project2, label should be in name column and extra_1,2,3 should in value column.