Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: TypeError:string indices must be integers
i am getting following error- "Python: TypeError:string indices must be integers" and I can not see what's wrong. Am I being stupid and overlooking an obvious mistake here? class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_detail_query) order_detail_result = cursor.fetchall() order_detail_data = list(order_detail_result) # print(order_detail_data) cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) dic = {} for d in order_detail_query: if d['order_id'] not in dic: dic[d['order_id']] = [] dic[d['order_id']].append(d) return order_data.append(dic) totalData.append({"order_data":order_data, "order_detail_data":order_detail_data}) return Response({"totalData":totalData,},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
Django AttributeError: 'collections.OrderedDict' object has no attribute 'pk'
When I try to add an url attribute to my model I get this error: AttributeError: 'collections.OrderedDict' object has no attribute 'pk' These are the codes I use. I tried a lot of things but just get an error with everything I try.. Serializer: class GroupPatchSerializer(serializers.ModelSerializer): linked_sites = serializers.ListField() name = serializers.CharField(required=False) url = serializers.HyperlinkedIdentityField( view_name="group-detail", lookup_url_kwarg="group_pk" ) class Meta: model = Group fields = ("id", "url", "name", "linked_sites") def validate_linked_sites(self, sites): ** code ** return sites # noinspection PyMethodMayBeStatic def validate_name(self, name): ** code ** return name view: def patch(self, request, group_pk): """ Add site to group, change an existing group's name. -id: The group's id """ user = request.user group_id = int(group_pk) group = Group.objects.filter(pk=group_id).first() # Update the group serializer_class = self.get_serializer_class() serializer = serializer_class( data=self.request.data, context={"request": request, "user_pk": user.id, "group_id": group_id}, ) -
Submitting form without refreshing page using Django, Ajax, jQuery?
I am a newbie working with Django. I need a simple example. How to submit the form (post) without refreshing page using Django, Ajax, jQuery? This is my form, views, and template: views.py import json from django.shortcuts import * from django.template import RequestContext from linnea.web_interface import run_linnea from linnea_demo_app.forms import * def linnea_demo(request): if request.method == "POST": form = AdvertForm(request.POST) message = 'something wrong!' if(form.is_valid()): print(request.POST['title']) message = request.POST['title'] return HttpResponse(json.dumps({'message': message})) return render_to_response('linnea_demo.html', {'form':AdvertForm()}, RequestContext(request)) forms.py from django import forms from django.forms import ModelForm from linnea_demo_app.models import Advert class AdvertForm(ModelForm): class Meta: model = Advert models.py from django.db import models class Advert(models.Model): text = models.TextField() index.html <form action="" method="POST" id="post-form"> {% csrf_token %} {{form.as_p}} <input type="submit" id="btnGetKernel" class="" value="Generate Kernel"/> </form> .js $('#form').submit(function(e){ $.post('/url/', $(this).serialize(), function(data){ $('.message').html(data.message); }); e.preventDefault(); }); However, I got this error: django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form AdvertForm needs updating. am I doing it right? -
How to write unit test to test deleting a record in a model
I have a model, I would like to write a unit test to test delete operations on the model, I have written for create, read and update, but I cant seen to get a hang of how delete should work. here is my code. def create_pay(self): pay = Pay.objects.create(user=self.user, amount=2000, appointment_count=2) return payout here is were I call the create_pay method to test for delete operation def test_payout_model_delete(self): payout = self.create_payout() get_payout = Payout.objects.get(pk=payout.pk) del_pay = get_payout.delete() self.assertEqual(del_pay, (None)) But it gives me this error AssertionError: (1, {'doctors.Payout': 1}) != None -
How to display categorized images (Batsman, Bowler, Wicket keeper) using checkboxes in django by clicking on button
I have designed a django application, html page contains 3 checkboxes (Category: Batsman, Bowler, Keeper) also a click button and wants to display categorized images on another web page by choosing checkboxes and clicking on button. How to make a view and another html page. -
How to make custom response in djangorestframework
So I like the idea of using class-based views and ModelSerializers but I have an issue with it for my particular use case. Maybe I am not using it as it's intended to be used. class CarSerializer(serializers.ModelSerializer): class Meta: model = CarModel fields = ['car_name'] # A car can have build for multiple years class MakelHistorySerializer(serializers.ModelSerializer): car = CarSerializer(many=True, read_only=True) class Meta: model = MakeHistoryModel fields = ['model_year', 'car'] The response is: { "car": { "car_name": "Fiesta" }, "model_year": "2020" } My two model classes, CarModel and MakeHistoryModel have ["id", "car_name", "manufacturer"] and ["id", "car_id", "model_year", "country_id"] fields respectively. What kind of a response I really want is: { "car_name": "Fiesta", "model_year": "2020" } How would I do this? -
django-import-export error while importing data into database
Line number: 1 - 'id' Traceback (most recent call last): File "/home/carlmark/Desktop/Final/realtyredefine/env/lib/python3.6/site- packages/import_export/resources.py", line 500, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/carlmark/Desktop/Final/realtyredefine/env/lib/python3.6/site- packages/import_export/resources.py", line 277, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/home/carlmark/Desktop/Final/realtyredefine/env/lib/python3.6/site- packages/import_export/resources.py", line 266, in get_instance self.fields[f] for f in self.get_import_id_fields() File "/home/carlmark/Desktop/Final/realtyredefine/env/lib/python3.6/site- packages/import_export/resources.py", line 266, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' I'm trying to import data from a CSV file to my Django database but whenever I tried to import I got "KeyError: 'id'" although there's no "id" field in my model. I'm this issue only when I using PostgreSQL, there's no error when I import the same data in sqlite3. -
In changing Django project from sqlite to Postgres, ModuleNotFoundError: No module named 'mysite.settings'
On my first Django project, I got started with a sqlite database, and now I'm switching to Postgres. The first part of the code that I wrote and tested was an import management command, to read records in from a file and create database records for them, and that's been working great. So to start making the change, I've updated the default database info in settings.py, and I ran migrations for it like so: python3 manage.py migrate --database=default I can see the correct table structure when I view the database in pgAdmin 4 (just with no rows populated yet)- and the field max values appear to all match what's in the model- hooray! I also added some code to get the ENV_ROLE and database password from environment variables, as recommended here: https://ultimatedjango.com/learn-django/lessons/handling-sensitive-keys/ Next I run my import management command, and the problem: I'm getting an error I never saw while running it using the sqlite database: 1) when I run it from within PyCharm: No manage.py file specified in Settings->Django Support /usr/local/bin/python3.8 /Library/Frameworks/Python.framework/Versions/3.8/bin/django-admin.py importgedcom Test_tree.ged Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command app_name = commands[subcommand] KeyError: 'importgedcom' During handling of the above exception, another exception occurred: … -
Displaying ManyToManyField correctly in DjangoAdmin
I'm trying to add a Likes model to a Posts application so that it records every time a User 'likes' a determined post. I have already added the likes field to the Posts model as a ManyToManyField and have tried to register it to display in the Django Admin, more exactly in the Post detail, but the result of the code I have only displays a list of all users where it should only be a list of the users that have liked the corresponding post. Here's the code for my Posts model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): # ForeignKey that relates the post to the user that published it and their corresponding profile. user = models.ForeignKey(User, on_delete=models.PROTECT) profile = models.ForeignKey('users.Profile', on_delete=models.PROTECT) title = models.CharField(max_length=255) photo = models.ImageField(upload_to='posts/pics') description = models.TextField(max_length=2000, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) # ManyToManyField that translates to the users that have liked the post likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return '{} by {}'.format(self.title, self.user.username) def get_likes(self): return '\n'.join([l.likes for l in self.likes.all()]) Also this is the code for the admin.py file. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ( 'pk', 'user', 'title', 'photo', 'created', 'modified', 'get_likes', ) list_display_links = … -
500 Error in django on heroky when debug = False
When I run with DEGBU=True everything works fine but when I set DEBUG = False I have only Server Error 500. I am using the latest Django version (3.x.x) and deploying my project to heroku. I have no idea why this is happening. My settings.py file (some parts) as follows import django_heroku 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__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['research-and-development.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ # static and media files and urls set-up STATIC_URL = '/static/' STATIC_MEDIA = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # end of static and media files and url set-up django_heroku.settings(locals()) Please help me to solve this problem. -
Django project architecture advice
I have a django project and I have a Post model witch look like that: class BasicPost(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) published = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) body = models.TextField(max_length=999) media = models.ImageField(blank=True) def get_absolute_url(self): return reverse('basic_post', args=[str(self.pk)]) def __str__(self): return self.title Also, I use the basic User model that comes with the basic django app. I want to save witch posts each user has read so I can send him posts he haven't read. My question is what is the best way to do so, If I use Many to Many field, should I put it on the User model and save all the posts he read or should I do it in the other direction, put the Many to Many field in the Post model and save for each post witch user read it? it's going to be more that 1 million + posts in the Post model and about 50,000 users and I want to do it the right way If I should use the first option, how do I expand the User model? thanks! -
Which is better django or node js?
As, i have used express js now trying to learn django. So, is django better than node js , so i should stick with node js or learn a new framework of node js. -
i got this error after creating each django project and try to run the server
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200301_0817 dependencies reference nonexistent parent node ('users', '0001_initial') -
Using pipenv as a virtual environment on a production server
There is a local project on gitlab that I want to put on the production server (Ubuntu 18.04). When developing it, I used pipenv to control versions of libraries. I had some problems with pipenv library on the server. what steps I have already taken pip3 install pipenv git clone ... project from gitlab I have Pipfile and Pipfile.lock in my project folder. But when I run pipenv shell error is appears -bash: pipenv: command not found Checked if there is such a package via pip3 list and it is on the list ... pipenv 2018.11.26 ... how do I set up pipenv and install dependencies from Pipfile? -
Override Django queryset update method
I want to override Django Queryset Update method , to log the model changes in another table.I have override the method , but not able to find the id's of the rows which are going to get update.I am getting the fields which are getting changed from kwargs I'm using Django v1.9.5. I went through the docs of django-simple-history and django-reversion , but they don't log changes on update method. class PollQuerySet(QuerySet): def update(self, *args, **kwargs): # save data into other table whose schema is #(model_name,field_name,model_pk_id,old_value,new_value) super().update(*args, **kwargs) class ModelWithCustomManager(models.Model): objects = PollQuerySet.as_manager() class Meta: abstract = True -
django for loop optimize
I have a loop in my html like this <table> {% for behaviors in behavior %} <tr> <th>{{name.Behavior}}</th> </tr> {% endfor %} {% for names in name %} <tr> <td>{{names.Name}}</td> </tr> {% endfor %} </table> the result in my html is Aggressive Assertive Passive Passive-Aggressive ... how to loop just like this Name | Aggressive | Assertive | Passive | Passive-Aggressive | ... Mirly | | | | | Marta | | | | | this is my models.py class Employee(models.Model): Name= models.CharField(max_length=255,null=True, blank=True) Behavior = models.CharField(max_length=255,null=True, blank=True) ... -
Change queryset in django to string
I would like to get my queryset in the example below and then use it in html code. 'electronics, toys, tools' I'm trying to do something like that TAGS = [('%s,'%(category.name))for category in Category.objects.all()] But it returns something like this in the html code: <input type="text" name="category" data-toggle="tags" value="[&#39;electronics,&#39;, &#39;toys,&#39;, &#39;tools,&#39;]" placeholder="Wpisz kategorie..." required id="id_category"> How can I change my question set to pure string form. Any help will be appreciated. -
Generating PDF with the same headers throughout with ReportLab
I am working with reportlab. I am exporting a Pandas DataFrame to PDF using reportlab to have it dynamic and automate the task anytime I need to have them in an organized way. Already a lot of data wrangling with Pandas have been involved. Right now, I would like to have the table headers repeating across the pages with PDF using reportlab. Below is the way the DataFrame looks with the columns headers styled Whenever the number of rows are more than 22, it continues at the next page and this is completely normal, the problem now is that I want to retain my column headers and style and the headers and logo for each page. See below: Here is my code below for your review: doc = MyDocTemplate(pdf_name,pagesize=landscape(letter), rightMargin=50,leftMargin=50, topMargin=18,bottomMargin=18) dataTable_1 = [] dataTable_2 = [] dataTable_3 = [] dataTable_1.append(['Versicherer','Produkt Bereich','Produkt Typ','Produkt','Vertragsart','Steuersatz','AP gesamt','BP gesamt','Anteil Partner']) dataTable_2.append(['Versicherer','Produkt Bereich','Produkt Typ','Produkt','Vertragsart','Steuersatz','AP gesamt','BP gesamt','Anteil Partner']) dataTable_3.append(['Versicherer','Produkt Bereich','Produkt Typ','Produkt','Vertragsart','Steuersatz','AP gesamt','BP gesamt','Anteil Partner']) # iterate through each insurance and add a seprate sheet for all of them for Versicherer_names in Different_Versicherer: frame = commissions_df[commissions_df['Versicherer'] == Versicherer_names] df = pd.DataFrame(frame) dataTable = [] dataTable.append(['Versicherer','Produkt Bereich','Produkt Typ','Produkt','Vertragsart','Steuersatz','AP gesamt','BP gesamt','Anteil Partner']) for index, row in df.iterrows(): a=row['Versicherer'] b=row['Produkt … -
uwsgi worker not distributing evenly
I have a Django project configured with nginx and uwsgi. There isn't much cpu processing involved in the website. There is mostly simple read, but we expect lot of hits. I have used apache bench mark for load testing. Giving a simple ab -n 200 -c 200 <url> is making the website slower (while the benchmark test is on, not able to open the website in any browser even from a different ip address). I have given number of processes as 16 and threads as 8. my uwsgi.ini file is given below. [uwsgi] master = true socket = /tmp/uwsgi.sock chmod-socket = 666 chdir = <directory> wsgi-file = <wsgi file path> processes = 16 threads = 8 virtualenv = <virtualenv path> vacuum = true enable-threads = true daemonize= <log path> stats= /tmp/stats.sock when i check the uwsgitop, what is seen that workers 7 and 8 are handling most of the requests, rest of them are processing less number of requests compared to them. Could this be the reason why i cannot load the website in a browser while benchmark is run ? How can i efficiently use uwsgi processes to serve maximum number of concurrent requests ? this the result of … -
E11000 duplicate key error collection in PyMongo
I am developing my app with Djnago and for database mongo db . Its basically a subscription buying platform. On 2nd time buying a subscription Its throwing error . In order model I have: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) subscriptions = models.ManyToManyField(OrderSubscription) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) amount = models.FloatField() billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) When someone brought a subscription and want to buy again another Sub Its throwing duplicate key error where Its creating another order table with the same user. def finalcheckout(request): if request.method == "POST": subscription = get_object_or_404(Subscription, slug = request.POST.get("sub_slug")) order_subscription, created = OrderSubscription.objects.get_or_create( subscription=subscription, user=request.user, ordered=False ) order = Order.objects.create(user=request.user) order.subscriptions.add(order_subscription) messages.info(request, "This subscription was added to your cart.") return redirect("core:order-summary") Error: Params: [2, None, datetime.datetime(2020, 3, 2, 12, 26, 53, 481937), None, False, None, None, None, None, False, False, False, False] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'backup_id': 1}, 'keyValue': {'backup_id': None}, 'errmsg': 'E11000 duplicate key error collection: hostmanager.subscription_order index: subscription_order_backup_id_79d0cc4e_uniq dup key: … -
name basestring is not defined when clicking save
if isinstance(request.session['initial_files'], basestring): # if this is a file path, we know it is a large file This was done in python2 and django 1.8, now that i moved to python 3.6.9 and django 2.2 its crashing there with message basestring is not defined. What am i MISSING to import? File "/home/bsd/.virtualenvs/BSD/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/bsd/.virtualenvs/BSD/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/bsd/.virtualenvs/BSD/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bsd/.virtualenvs/BSD/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/bsd/PycharmProjects/BSD/BSD_3_1/tifact/views.py" in update 465. if isinstance(request.session['initial_files'], basestring): # if this is a file path, we know it is a large file Exception Type: NameError at /tifact/update/submit/1515 Exception Value: name 'basestring' is not define -
Difference between select related and prefetch related in django
What is the difference between select related and prefetch related in django ? and why and when does it need ? -
How to send multiple form data in django?
I have created the form in django for transfering multiple data in the database. How can I achieve this? Since I want to create multiple choice question app and transfer the multiple data of form at once in th db. -
deloy keras NMT model on flask
after i have trained my machine translation model which build with keras now i just want to deploy it somehow in flask or django and input the values and get the translation my model can be saved as: model.h5 model.yml model.json the problem is i can not deploy it i mean there is no tutorial about it guys do you have any idea how to deploy it i asked also in https://www.kaggle.com/questions-and-answers/133380 https://datascience.stackexchange.com/questions/68957/deploy-keras-machine-translation https://ai.stackexchange.com/questions/18277/how-can-i-deploy-a-keras-machine-translation-model-on-flask-or-django any idea or any tutorial ? -
Django: Staticfiles are creating but django failed to find staticfiles and look inside static folder
It was working fine, but for some reason, I have to change the staticfiles code and from there problem occurs. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'blackportfolio/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' Staticfiles are creating my all css files are getting copy in staticfiles, browser also getting the staticfiles name <link rel="stylesheet" href="/static/style.2f83ab2e5052.css"> But its not searching them in static_root(staticfiles) it still searching them in static python manage.py findstatic --verbosity 2 styles.css but it returns with C:\Users\HP\Desktop\vir1\blackportfolio\blackportfolio/static C:\Users\HP\Desktop\vir1\venv\lib\site-packages\django\contrib\admin\static the command I type. manage.py collectstatic --clear manage.py runserver --insecure. project structure. C:. ├───blackportfolio │ ├───static │ │ ├───admin │ │ │ ├───css │ │ │ │ └───vendor │ │ │ │ └───select2 │ │ │ ├───fonts │ │ │ ├───img │ │ │ │ └───gis │ │ │ └───js │ │ │ ├───admin │ │ │ └───vendor │ │ │ ├───jquery │ │ │ ├───select2 │ │ │ │ └───i18n │ │ │ └───xregexp │ │ └───images │ └───__pycache__ ├───portfolio │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───staticfiles │ ├───admin │ │ ├───css │ │ │ └───vendor │ │ │ └───select2 │ │ ├───fonts │ │ ├───img │ │ │ └───gis │ │ └───js │ │ …