Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
want to upload several pictures for a user, only allowing me to upload more than one.
I want users to be able to upload several pictures, but I can only get it to do one. here is my code: urls.py from . import views from django.urls import path app_name = 'accounts' urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('profile/<int:user_id>', views.profile, name='profile'), path('profile/<int:user_id>/upload/', views.upload_pics, name='upload_pics'), ] here is my view: def upload_pics(request, user_id): user_profile = get_object_or_404(User, pk=user_id) if request.method == "POST": pic = File() pic.user = user_profile file_list = request.FILES.getlist('files') for afile in file_list: pic.image = afile pic.save() return redirect("groups:index") else: render(request, 'accounts/pic_upload.html') return render(request, 'accounts/pic_upload.html') finally, here is the form(pic_upload.html): <form action="{% url 'accounts:upload_pics' user.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <tr> <td>Select Pictures: </td><td><input name="files" type="file" size="50" accept="image/*" multiple> </td> <td><button type="submit"> Upload </button> </td> </tr> </table> </form> and here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class File(models.Model): image = models.FileField(upload_to='images/') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='files') i've been trying to get this done for several days, but no luck. I've looked into formsets but simpler methods for accomplishing multiple file uploads seem to exist. any guidance as to why only 1 picture is being saved would really be appreciated. thanks ya'll -
Define time period in database for analyses
I want to store timeseries in a database. The values of these timeseries are usually defined for a certain period, for example: country population in 2014, 2015, 2016, etc. number of houses in country in 2014, 2015, 2016 I want to combine the data of these varabiales to be able to do some statstics, so housing vs population. This is only possible if I make sure the time periods are exactly the same. The periods are usually on a per year/quarter/month basis. How to best store these values such that I can later compare them? I currently use start_date (datetime) and end_date (datetime), which obviously works but needs a good GUI to prevent that one person enters for example: start = 1-1-2016 & end = 31-12=2016 while another would enter: start = 1-1-2016 & end = 1-1=2017 I think it would be a good idea to keep the freedom of defining the period with the user but help them in defining the right thing. How would you suggest to do this? BTW: I work with Django so my current model has the following two fields: period_start = models.DateField(null=False) period_end = models.DateField(null=False) -
Deleted tasks still showing in celery
I've completely removeed all records of of celery tasks in settings.py, celery.py and tasks.py except for one which is called test_post. However an error relating to an old task is still showing in my celery.log file: [2018-05-08 07:23:05,115: ERROR/MainProcess] Received unregistered task of type 'post_jobs'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"chord": null, "chain": null, "errbacks": null, "callbacks": null}]' (77b) Traceback (most recent call last): File "/home/james/postr/env/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 561, in on_task_received strategy = strategies[type_] KeyError: 'post_jobs' Why is this happening and how can I fix it? I've already tried celery -A myapp purge and it didn't do anything. -
Maintain the order of Jason data when serializing
I have a data set like this. { 'album_name': 'Dear John', 'artist': 'Loney Dear', 'tracks': [ 'Airport Surroundings', 'Everything Turns to You', 'I Was Only Going Out', ] } when I serialize it, my Jason file does not look like the same every time. Because order of 'tracks' change every time. I was looking at 'to_representation' but since this data doesn't have a Key i failed to implement it as i expected. Can any one give a hint, to make sure that 'tracks' always in same order. -
Django implement the chain method and list
I'm trying to do a join between two models (tabels Reports and Sources) such as explained in the following code. In statistics.html I don't see data as I would I'm newbie in DJANGO I don't know how modify the code View.py from itertools import chain class Statistics(ListView): model = Reports template_name = 'statistics.html' context_object_name = 'Statistics' def get_context_data(self, **kwargs): context = super(Statistics, self).get_context_data(**kwargs) context['statisticsTest'] = list(chain(Reports.objects.values('id','idsite','idcity','idsys', ).filter(idsite = self.kwargs['idsite'], idcity = self.kwargs['idcity'], idsys = self.kwargs['idsys'], ), Sources.objects.values('idsite','idcity','idsys','name_site','name_sys').filter(idsys =self.kwargs['idsys']))) return context statistics.html counter:{{statisticsTest|length}} {% for item in statisticsTest %} <p>{{ item.idsite }}</p> <p>{{ item.idsys }}</p> {% endfor %} {% for item in statisticsTest %} {{ item.idsite }} {{ item.idcity }} {{ item.idsys }} {{ item.name_site }} {{ item.name_sys }} {% endfor %} -
what are the most frequently used 3rd party django database backends for MS SQL server?
Currently I'm using django-pyodbc-azure with django 1.11. But it seems slower than other. Is there any other library that performs faster than this? Can anyone suggests me some other libraries to check the query performances? -
How to return multiple values using API in django
I am brand new to django. This is the api json value I called from internet: {'message': '', 'result': [{'name': 'ABC', <------ 'Type': 'True', <----- 'Fee': 0.0005}, {'name': 'DEF', <------- 'Type': 'False', <------ 'Fee': 0.004}, } I want to put name and type to the webpage using HTML. ABC True DEF False Do I need to modify models.py? Please give me an example. thank you The only think I know is to use for loop in HTML, but I do not know does it work? -
Django migrating from Mysql to Oracle causes ORA-00932:inconsistent datatypes: expected Number got Boolean
We have a Django1.3 project that works with a legacy MySQL db and trying to migrate this project to Oracle 12C. After migration the current Application environment: CentOS 6.6 Python 2.6.6 Django 1.3 cx_Oracle 5.2.1 Oracle 12.2.0.1 Understood that BooleanField in Django can be mapped to Oracle column type Number(1) in OracleDB. But while saving Django User model(from django.contrib.auth.models) which has 2 to 3 boolean fields facing ORA-00932:inconsistent datatypes: expected Number got Boolean. How to resolve this issue, any quick help will be appreciated. And do we have any proper steps to migrate Django project from Mysql to Oracle?. -
python / django : nested for loop is really slow for query set traversal
I have two models named machine and performance, class machine(models.Model): machine_type = models.CharField(null=True, max_length=10) machine_no = models.IntegerField(null=True) machine_name = models.CharField(null=True,max_length=255) machine_sis = models.CharField(null=True, max_length=255) store_code = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) class Performance(models.Model): machine_no = models.IntegerField(null=True) power = models.IntegerField(null=True) store_code = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) For each Machine, there are multiple fields of in Performance Model and i have to find the count of Performance Model's rows in the db which have power = some_integer. Here is what my view looks like: machines = machine.objects.filter(machine_type="G",machine_sis="919") #let's say machine.count() sometimes is 100 #for each of this machine i need to calculate the number of machines which have power = 100 in performance model. # so what i did first was but was really slow for obj in machines: print performance.objects.filter(machine_no=obj.machine_no,power=100).count() # my second approach was faster than first approach for obj in machines: data = performance.objects.filter(machine_no=obj.machine_no,power=100) counter = 0 for p in data: # ***** lets say this loop is called star-loop if p.power == 100: counter +=1 My problem: The speed is really slow when i have to check 100 machines in Performance model whose power = something . Additional info: I am not using foreign key in Performance Model because … -
Django rest IntegrityError: 1048, "Column cannot be null" on foreign key serializer
I have my models defined as following: class Responsibility(models.Model): name = models.CharField(max_length=50, blank=True, null=True, ) class Collaborator(models.Model): name = models.CharField(max_length=50, blank=True, null=True, ) class Card(models.Model): thing = models.CharField(max_length=50, blank=True, null = True, ) responsibilities = models.ForeignKey(Responsibility, related_name='res_cards', blank=True, on_delete=models.CASCADE) collaborators = models.ForeignKey(Collaborator, related_name='col_cards', blank=True, on_delete=models.CASCADE) And serializer: class CollaboratorSerializer(serializers.ModelSerializer): class Meta: model = Collaborator fields = '__all__' class ResponsibilitySerializer(serializers.ModelSerializer): class Meta: model = Responsibility fields = '__all__' class CardSerializer(serializers.ModelSerializer): responsibilities = ResponsibilitySerializer(many=True,) collaborators = CollaboratorSerializer(many=True,) class Meta: model = Card fields = '__all__' def create(self, validated_data): responsibilities_data = validated_data.pop('responsibilities') collaborators_data = validated_data.pop('collaborators') card = Card.objects.create(**validated_data) for responsibility_data in responsibilities_data: Responsibility.objects.create(card=card, **track_data) for collaborator_data in collaborators_data: Collaborator.objects.create(card=card, **track_data) return card My POST request looks like following: {u'thing': u'Book', u'responsibilities': [{u'name': u'Name'}, {u'name': u'ISBN'}], u'collaborators': [{u'name': u''}]} But the application throws above error. What am I missing? Responsibilities and Collaborators do not preexist, they will be created along with Card and should also be updated along with Card and not independently. -
django test client.put doesn't have data
I am trying to test django view with REST framework. It starts like this. class MoveViewSet(viewsets.ModelViewSet): serializer_class = FamilySerializer queryset = Family.objects.all() http_method_names = ['put'] def update(self, request, pk=None): user = request.mobile_user ... family_id = request.POST.get('family_id', None) ... in test.py I make a request like this. data = dict( join_type='join', family_id=target_family.id, ) # also tried data = { ... } header = { 'Authorization': user.api_key, ... } client = Client() response = client.put(url, data=data, content_type='x-www-form-urlencoded', **header) ### What I've tried ### # response = client.put(url, data=data, **header) # response = self.client.put(url, data=data, **header) # response = client.put(url, data=data, content_type='application/json', **header) but in view, request.POST.get('paramname', 'default') makes error. request.POST has empty parameter set and of course, request.PUT is None. I checked middleware but neither could I find params there. Also I've tried this in middleware's process_request. def process_request(self, request): if request.method == "PUT" and request.content_type != "application/json": if hasattr(request, '_post'): del request._post del request._files try: request.method = "POST" request._load_post_and_files() request.method = "PUT" except AttributeError as e: request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT' request.PUT = request.POST It gives me this error. AttributeError: 'WSGIRequest' object has no attribute 'content_type' If I send client.post() with data, request.POST has data, but put doesn't. How … -
How to get postgresql database out of deadlock after django manage.py migrate script failed
I recently tried to run a django manage.py migrate command on a remote database. I believe that the connection to the database may have been interrupted during the command. I got back this error when the command finished: DETAIL: Process 11463 waits for AccessExclusiveLock on relation 96771 of database 16389; blocked by process 11681. Process 11681 waits for AccessShareLock on relation 25332 of database 16389; blocked by process 11463. I get the same error if I try to run the migrate command again. What should I do to get out of this state? Should I find and kill these two blocking processes? Remove the locks? I'm not sure what to do here and don't want to try random things that may make the situation worse. I have daily backups of this database, but would rather not lose data. Django version 1.8.xx, PostgreSQL 9.4.15 -
Object of type 'Product' is not JSON serializable
I'm trying to pull the from my app via Django. The issue is when I call Order Detail via my serializers, I get this error: TypeError at /api/customer/order/latest/ Object of type 'Product' is not JSON serializable Request Method: GET Request URL: http://localhost:8000/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX Django Version: 1.10 Exception Type: TypeError Exception Value: Object of type 'Product' is not JSON serializable I'm pulling the data from this Model: class OrderDetail(models.Model): order = models.ForeignKey(Order, related_name='order_details') product_size = models.ForeignKey(ProductSize) quantity = models.IntegerField() sub_total = models.FloatField() def __str__(self): return str(self.id) # references Prodcut and allows old code to work. @property def product(self): return self.product_size.product This is what is being pulled: 'order_details': [OrderedDict([('id', 68), ('product_size', 44), ('quantity', 1), ('sub_total', 20.0), ('product', <Product: Bacon Burger - withDrink>)])], 'status': 'Your Order Is Being Picked Right Off The Plant!', 'total': 20.0} request <WSGIRequest: GET '/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX'> Serializers: class OrderDetailSerializer(serializers.ModelSerializer): class Meta: model = OrderDetail fields = ("id", "product_size", "quantity", "sub_total", "product") class OrderSerializer(serializers.ModelSerializer): customer = OrderCustomerSerializer() driver = OrderDriverSerializer() restaurant = OrderRestaurantSerializer() order_details = OrderDetailSerializer(many = True) status = serializers.ReadOnlyField(source= "get_status_display") class Meta: model = Order fields = ("id", "customer", "restaurant", "driver", "order_details", "total", "status", "address") I'm not sure what needs to be done. Thank you advance for the help -
How to jump to the middle of the flow in ViewFlow?
I'm using ViewFlow/Django and I've defined Flow which includes 10 steps. Suppose I have all the relevant data for the first 5 steps. How can I programatically start my flow, save the data for these steps and jump directly to step 6? -
unable to login with superuser django administration
i am unable to login to my djnago admin account with superuser credentials. When i supply correct credentials and press login button it will remain on the very same page. Here is the screenshot of the server when i try to login admin I have tried the same with new superuser. The new superuser was created successfully but it got stuck again on login page.For convenience i am attaching screenshot of the page i am stuck on Here is my settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bw@cz+hu#m$af4=!ky_3=34kd&9$4hhwupskst8kn)dxvzl3h8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'djoser', 'advertisements', 'wallet', 'User', 'custom_user', 'corsheaders', 'deployedcontracts', 'paymenthistory', 'saved', 'file_app', 'mail' ] REST_FRAMEWORK = { … -
Make fields of parent class appear last
I have several models which in turn use some similar fields. So instead of copying and pasting each repeatable field I instead inherited it from another class CommonFields. When running ./manage.py migrate this leads to having the parent class's fields first in the db which is understable. But is there a way for them to be last? from django.db import models class CommonFields(models.Model): deleted_at = models.DateTimeField(null=True, blank=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Foo(CommonFields): firstname = models.CharField(max_length=191) lastname = models.CharField(max_length=191) Which leads to a table with the parent fields first. +------------+------------+------------+-----------+----------+ | deleted_at | updated_at | created_at | firstname | lastname | +------------+------------+------------+-----------+----------+ Can it be +-----------+----------+------------+------------+------------+ | firstname | lastname | deleted_at | updated_at | created_at | +-----------+----------+------------+------------+------------+ -
Not able to generate graph from NVD3 in Django
I am trying to generate a graph from Sqlite DB using NVD3. However on the webpage i am not getting the graph, instead i am getting a dictionary. Below is my code for views.py # views.py from django.db import connections from django.db.models import Count from django.http import JsonResponse from django.shortcuts import render from personal.models import * def graph(request): return render(request, 'personal/graph.html') def play_count_by_month(request): data = NetworkRelatedInformation.objects.all().values('month').annotate(count_items=Count('id')) charttype = "lineChart" chartcontainer = 'linechart_container' # container name return JsonResponse(list(data), safe=False) url.py url(r'^$', views.graph), url(r'^api/graph/$', views.play_count_by_month, name='graph'), graph.html {% load nvd3_tags %} <head> {# Jquery CDN : Needed when using jquery_on_ready=True #} <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> {% include_chart_jscss %} {% load_chart charttype chartdata chartcontainer extra %} </head> <body> {% include_container chartcontainer %} </body> Below is the output that i am getting on url [{"month": "April", "count_items": 3}, {"month": "February", "count_items": 5}, {"month": "January", "count_items": 6}, {"month": "June", "count_items": 1}, {"month": "March", "count_items": 3}] Please suggest how can i get graph instead of above output -
Changing Wagtail Userbar Icon
How to change Wagtail Userbar Icon? I want to make it more personalize but I don't know how since I am new in web development. Wagtail Userbar Icon -
What's the `save()` for in Django?
I am learning Django and have the following codes: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): #Redisplay the question voting form return render(request, 'polls/detail.html', { 'question':question, 'error_message':"You did'nt select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I am confused about the selected_choice.save(), as a simple example: counter = 0 for counter in range(9): counter += 1 print(counter) There's no save operation during the process. What's the save() for in Django? -
The ordering name order do not satisfy my requirement
My code is bellow: class SwitchesPort(models.Model): name = models.CharField(max_length=32, unique=True) desc = models.CharField(max_length=256, null=True, blank=True) class Meta: ordering = ['name'] The ordering is name, you see the snapshot, this do not satisfy my need. so, if I can add a ordering item base one the name's length? -
How Django 1.8 values get point_x point_y and get specific datetime timezone
Django 1.8 values can't get point and specifictimezone I have tried this, but it doesn't work... myqueryset.objects.filter(**kwargs).values('id', lon=F('point_x'), 'time') Does Django 1.8 not support this? and also in "values" to convert to any specific timezone? because Django default timezone is UTC, but I need to convert to specific timezone -
Django - Unique Together raises error.
I am following a book tutorial for Django applications (keyword: TDD, link: here, author: Harry Percival), and I made small changes which now break my code. Test def test_saves_same_game_with_different_players(self): player1 = Player.objects.create(name="Player1") player2 = Player.objects.create(name="Player2") Game.objects.create(player=player1, text="score: other_player") game2 = Game.objects.create(player=player2, text="score: other_player") game2.full_clean() # Should not raise. Models class Player(models.Model): name = models.TextField(default="") objects = models.Manager() def __str__(self): return self.name class Game(models.Model): player = models.ForeignKey(Player, default=None) text = models.TextField(default="", unique=True) objects = models.Manager() def __str__(self): return self.text class Meta: ordering = ("id",) unique_together = ("player", "text") Error ... game2 = Game.objects.create(player=player2, text="score: other_player") ... IntegrityError: UNIQUE constraint failed: games_game.text and also with sqlite. The error is with the unique_together constraint when creating the second game with the same text. But this happens even when the players have different names, and even use the name as a string representation. Would anyone know how to go about this? Thank you for your patience. Cheers. -
Django Testing view template context
I'm trying to test the return render(request, 'template.html', context) and seem to be falling short. Is it not worth while testing this? Or if it is worth while testing this, how do I accomplish that? view.py def create_employee_profile(request): name_form = EmployeeNameForm() context = {'name_form':name_form} return render(request, 'template_create_employee_profile.html', context ) I know the if: else: statements are missing. I didn't think they were relevant to the test. test.py # TEST: context({'name_form':name_form}) def test_CreateEmployeeProfileView_context(self): name_form = EmployeeNameForm() response = self.client.get(reverse( 'create_employee_profile')) self.assertEquals(response.context['name_form'], name_form) This got me the closest to success. Here's my error: AssertionError: <Empl[27 chars]alid=False, fields=(employee_choices;first_nam[20 chars]ame)> != <Empl[27 chars]alid=Unknown, fields=(employee_choices;first_n[22 chars]ame)> -
How to return a query set in get_queryset() in Django
I'm currently trying to convert my FBV codes to CBV. get_context_data is working well by returning contexts that I put in. However, get_queryset() returns NOTHING for some reason. To double-check, I tried to print search_stores right before returning it and it printed the queryset that is supposed to be printed. However, when I printed it on Django template, by typing {{ search_stores }}, it shows nothing. Am I using get_queryset in a wrong way? class SearchListView(ListView): model = Store template_name = 'boutique/search.html' # paginate_by = 5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['search_text'] = self.request.GET.get('search_text') context['sorter'] = self.request.GET.get('sorter') if not context['sorter']: context['sorter'] = 'popularity' return context def get_queryset(self): search_text = self.request.GET.get('search_text') sorter = self.request.GET.get('sorter') if search_text: search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q(mKey__icontains=search_text)) if sorter == 'businessName': search_stores = search_stores.order_by(sorter) else: search_stores = search_stores.order_by(sorter).reverse() else: search_stores = '' for store in search_stores: store.mKey = store.mKey.split(' ') print(search_stores) return search_stores -
How to generate formset with the details of information store in database?
I will be explaining what's the logic behind my code. These are my models. class Module(models.Model): name=models.CharField(max_length=30) modulecode = models.CharField(max_length=100) class intake(models.Model): intakecode = models.CharField(max_length=100) modules = models.ManyToManyField(Module, through='IntakeDetails') class Student(models.Model): user = models.OneToOneField(UserType, on_delete=models.CASCADE, primary_key=True) intakecode = models.ForeignKey(intake, on_delete=models.CASCADE) class Lecturer(models.Model): user = models.OneToOneField(UserType, on_delete=models.CASCADE, primary_key=True) One intake can have multiple modules, each module is taught by a lecturer. so i have this model for that class IntakeDetails(models.Model): intake = models.ForeignKey(intake, on_delete=models.CASCADE) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) module= models.ForeignKey(Module, on_delete=models.CASCADE) Each module in a intake have only one assignment, which is assigned that particular lecturer. so i have this model for that. class AssignAssignment(models.Model): title=models.CharField(max_length=30) duedate=models.DateField() intakedetails=models.OneToOneField(IntakeDetails, on_delete=models.CASCADE,related_name='details') Each assignment have multiple marking criteria and and its associated marks. for example, (documentation, 30), (conclusion,25), (system,45).. like this lecturer can add as many as criteria but total marks not exceeding 100. to do that i created this model and view. class Marking(models.Model): criteria = models.CharField(max_length=60) marks = models.PositiveIntegerField() assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE) def adding_criteria(request,pk): assign = get_object_or_404(AssignAssignment, pk=pk) MarkingCriteriaFormset = formset_factory(MarkingCriteria,extra=3) if request.method == 'POST': formset = MarkingCriteriaFormset(request.POST) if formset.is_valid(): sumlist=[] for form in formset: if form.has_changed(): m=form.save(commit=False) sumlist.append(m.marks) sum=0 for x in sumlist: sum+=x if sum==100: for form in formset: …