Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'list indices must be integers, not str' after converting string to dictionary
Using POST request i recieve this one respond <?xml version="1.0" encoding="UTF-8"?> <response version="1.1"> <accommodations> <accommodation name="accom1"> <concepts> <concept name="concept1-1"> <boards> <board name="board1-1"> <description>description</description> </board> <board name="board1-2"> <description>description</description> </board> </concept> <concept name="concept2-1"> <boards> <board name="board2-1"> <description>description</description> </board> <board name="board2-2"> <description>description</description> </board> </boards> </concept> </concepts> </accommodation> <accommodation name="accom2"> <concepts> <concept name="concept3-1"> <boards> <board name="board3-1"> <description>description</description> </board> <board name="board3-2"> <description>description</description> </board> </concept> <concept name="concept4-1"> <boards> <board name="board4-1"> <description>description</description> </board> <board name="board4-2"> <description>description</description> </board> </boards> </concept> </concepts> </accommodation> </accommodations> </response> Here is code of request: my_request = urllib2.Request(url, message) response_xml = urllib2.urlopen(my_request) my_response = response_xml.read() Then i convert string to dictionary: def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(list) for dc in map(etree_to_dict, children): for k, v in dc.iteritems(): dd[k].append(v) d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d my_result = ET.fromstring(my_response.decode('ascii', 'ignore')) d = globalvars.etree_to_dict(my_result) Then i try to save some data from dictionary to data base. When i try to save name="accom1", everythig works fine: … -
Django, How to create a manytomany objects while in the form of the object it's connected to?
I'm new to django and I've read alot of documentation on the manytomany relationship but I can't seem to make it work with my problem. So I have a Recipe class that has a manytomany relationship with ingredients because I figure many recipes will use things like chicken or steak, and each one has nutrition facts linked to it. I want to make it so that I can create the recipe and the ingredients for the recipe at the same time. If chickens already in the database it just links to that but if it isn't it gets added like a flyweight. Here is what I got so far. models.py class Ingredient(models.Model): name = models.CharField(max_length=100) class Recipe(models.Model): creationTime = models.DateTimeField(default=timezone.now, blank=True) title = models.CharField(max_length=150) description = models.TextField() ingredients = models.ManyToManyField(Ingredient) rating = models.FloatField() picture = models.ImageField() tags = models.ManyToManyField(Tag) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['title', 'description', 'ingredients', 'picture', 'tags'] views.py def create(request): recipeForm = RecipeForm() recipe = Recipe() ingredientSet = IngredientForm() instructionInline = inlineformset_factory(Recipe, Instruction, fields=('step', 'instruction')) if request.method == "POST": recipe = RecipeForm(request.POST) if recipe.is_valid(): created_recipe = recipe.save(commit=False) ingredient = IngredientForm(request.POST) formset = instructionInline(request.POST, request.FILES, instance=created_recipe) if formset.is_valid() and ingredient.is_valid(): … -
Displaying user profile for custom form
I added custom attributes like age, but when I try to display <p>{{user.username}}</p> <p>{{user.email}}</p> <p>{{user.age}}</p> Only the username and email show correctly (is this an indication that I may have incorrectly set up the form because username and email are default values?). The user.age displays as (<django.db.models.fields.CharField>,) as text instead. How do I get the age to display correctly as well? -
MaxRetryError with Docusign in Django
I am working on a webapp for my company. After the user enters information into the form that I provide, a pdf form is generated (using weasyprint), filling in the customer's information into the fields necessary. However, I am needing to integrate docusign's webapi into my project. I have messed around with the code a bit, and have gotten to the current point below: def Signview(request): loa = LOA.objects.filter().order_by('-id')[0] file_contents = loa.pdf.read() # create an envelope to be signed envelope_definition = docusign.EnvelopeDefinition() envelope_definition.email_subject = 'Please Sign The Following Document' envelope_definition.email_blurb = 'Thank you for choosing Leap Networks as your carrier! Please sign the following Letter of Agency (LOA) to complete the process!' # add a document to the envelope doc = docusign.Document() base64_doc = base64.b64encode(file_contents).decode("utf-8") doc.document_base64 = base64_doc doc.name = 'LeapNetworks_Signed_LOA.pdf' doc.document_id = loa.id envelope_definition.documents = [doc] # Add a recipient to sign the document signer = docusign.Signer() signer.email = loa.email signer.name = loa.ainame signer.recipient_id = loa.id # Create a signature tab somewhere on the document for the signer to sign sign_here = docusign.SignHere() sign_here.document_id = loa.id sign_here.page_number = loa.id sign_here.recipient_id = loa.id sign_here.x_position = '100' sign_here.y_position = '100' sign_here.scale_value = '0.5' tabs = docusign.Tabs() tabs.sign_here_tabs = [sign_here] signer.tabs = … -
In Django, how to find rows which would violate a unique together constraint?
For the following API endpoint, import json from django.contrib.auth.decorators import login_required from django.http import JsonResponse, HttpResponseBadRequest from django.views.decorators.http import require_POST from lucy_web.models import UserApn @login_required @require_POST def save_apn(request, version): player_id = json.loads(request.body).get('player_id') if player_id: UserApn.objects.get_or_create(user=request.user, player_id=player_id) return JsonResponse({'status': 'success'}) else: return HttpResponseBadRequest() Here is the underlying model: from django.contrib.auth.models import User from django.db import models from .timestamped_model import TimeStampedModel class UserApn(TimeStampedModel): user = models.ForeignKey(User) player_id = models.CharField(max_length=255) The call to get_or_create() has been raising some MultipleObjectsReturned errors. To fix this, I'd like to impose a unique_together constraint on the user and player_id. Firstly, however, I have to write a data migration that eliminates rows that violate this unique together constraint. How could I write a query that selects these? Right now the following has been proposed: def remove_duplicate_apns(apps, schema_editor): UserApn = apps.get_model('lucy_web', 'UserApn') previous_user_id = None previous_player_id = None for apn in UserApn.objects.all().order_by('user_id', 'player_id'): if apn.user_id == previous_user_id and apn.player_id == previous_player_id: print(f'deleting {apn} (id: {apn.id})') apn.delete() else: previous_user_id = apn.user_id previous_player_id = apn.player_id It seems, though, that this could also be done in a single query. -
How do I query the django notification JSON data using Postgresql JSONField syntax?
I'm sitting over this for a few hours now and am not getting anywhere. I'm working on a Django app (Django 1.10, Postgres 9.6.5) which uses Django Notifications. Their documentation says, that I can send arbitrary data along with a notification. If I follow their docs and send a notification, the admin panel notification shows my data successfully made it into the data field, which the admin panel requires to be in JSON format: { "flag":"can_localise_user:00c3b6f2-33d0-43e7-814c-f448040750fd" } I checked the database too, the schema says, CREATE TABLE "notifications_notification" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "unread" bool NOT NULL, "actor_object_id" varchar(255) NOT NULL, "verb" varchar(255) NOT NULL, "description" text NULL, "target_object_id" varchar(255) NULL, "action_object_object_id" varchar(255) NULL, "timestamp" datetime NOT NULL, ... "data" text NULL, "level" varchar(20) NOT NULL ); I'm a bit confused django-notifications say that it would use postgres JSONField to store the information when in the schema they only reference text, but as the admin-panel requires valid JSON and my extra parameters are parsed into JSON, plus the migration says it's a JSONField, I rest my case. However, I cannot query the content of this field no matter what I try... the Django documentation says it should … -
Test Django url 'name' is correct url
I think what I'm trying to is self evident: urls.py urlpatterns = [ path('', views.home_page, name='home_page'), ] test.py def test_home_page_view_name_uses_correct_url(self): name = self.client.get(reverse('home_page')) path = self.client.get('/') self.assertEqual(name, path) But I get this error: AssertionError: <HttpResponse status_code=200, "text/html; charset=utf-8"> != <HttpResponse status_code=200, "text/html; charset=utf-8"> How can I test this correctly? -
Sharing Django migrations files in ENV directory
I am trying to share a Django project. My coworker is getting errors than migration files are missing. The missing files are in my ENV/ directory which is in my .gitignore. What is the proper way to share those migration files with him? The files comes from django packages which we are using like alluath and default Django apps like admin. -
Django recommendation system
My question today is that i want to build a remmendation system for my django application My models.py: class Jobs(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True, default='') company = models.ForeignKey(Company, on_delete=models.CASCADE) price = models.IntegerField(default='') Description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time') applyed_users = models.ManyToManyField(User) tags = models.CharField(max_length=100,default="") My recommendations system should get all objects tags that user apllyed for and get all objects with this tags -
How to filter objects in Django models.py using querysets from views.py
I need to show the ratings left by one User for another User for a post that the member has written. The models.py are below. I have 3 functions in my models.py def average_rating(self):, def total_ratings(self):, def total_posts(self) All 3 of these functions use the forloop Review.objects.all(): which I believe may be wrong. In my views.py I have the context as Review.objects.filter(review_for__username__iexact=self.kwargs.get('username')) return context I thought that the views will filter the ratings of the user that belong to the person getting rated. Example if there are 4 ratings 2 for Admin and 2 for other users. If I see Admins Profile page. The template should show only the average ratings of the 2 ratings for the admin. Instead it shows average of all 4 ratings (2 for Admin and 2 for other un-related users). How can I fix this Below are my models.py class Review (models.Model): review_from = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_from') review_for = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_for') item = models.ForeignKey(OrderItem, related_name='items') created = models.DateTimeField(auto_now_add=True) feedback = models.TextField(blank=True, null=True) feedback_image = models.ImageField(blank=True, null=True) feedback_video = models.FileField(blank=True, null=True) rating_choices = ( ('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four'), ('5', 'Five'), ('6', 'Six'), ('7', 'Seven'), ('8', 'Eight'), ('9', 'Nine'), ('10', … -
How to return zero - Django annotation Count date range
The code attached doesn't return zero values for each day of a date range (15 to 19) How can I return zero values : results expected : [{'day': datetime.datetime(2018, 7, 16),'name':'ramu','count': 1}, {'day': datetime.datetime(2018, 7, 17),'name': 'raju','count': 0}, {'day': datetime.datetime(2018, 7, 18),'name': 'rani','count': 1}] But :( I'm getting following out put with out zero (0) [{'day': datetime.datetime(2018, 7, 16),'name':'ramu','count': 1}, {'day': datetime.datetime(2018, 7, 18),'name': 'rani','count': 1}] Code qst.filter(datetime__range=(first_date,last_date)).order_by('datetime').extra(select={"day": "DATE(datetime)"}).values('day','name','count').annotate(count=models.Count("id")) -
How do I get django User model to only return First and Last Names (default to email) while getting a list of users?
So, I have a model form: NewAccountForm(ModelForm): class Meta: model = Account fields = ['owner', 'account_name'] def __init__(self, *args, **kwargs): super(NewAccountForm, self).__init__(*args, **kwargs) The Model for Account: class Account(models.Model): owner = models.ForeignKey(User, limit_choices_to={'is_staff': True}) account_name = models.CharField(max_length=32) In my template: {% render_field account_form.owner class="form-control m-b" name="owner" %} This gives me a dropdown with all the users that are staff, but it gives me something like this: <select class="form-control m-b" id="id_owner" name="owner"> <option value="" selected="selected">---------</option> <option value="1">Carl Rogers (carl_rogers@myorg.com)</option> How can I have it return only Carl Rogers without the email in the bracket? Something like this: <option value="1">Carl Rogers</option> I read other answers to similar question that suggest editing the django User model and adding a meta __str__ method there, but that will affect my entire project across all areas and I don't want that. Any other approach I can take? -
Admin Interface Theme-ing?
I was wondering how themable the admin interface was? I ran across this doc and it seems to talk about a few options. It's huge step up from the django admin default interface but i was wondering if anyone knew of any drop in replacement. For example one pet peeve I have is the size of the content box. See attached . Is the size of the body driven by the data model and I goofed up somehow? Or is there something else I missed? -
django filter_horizontal with preload data
I have a question and I do not know the best way to proceed. Imagine the following scenario: I have 2 models in 2 different apps. One of the relationships between those models is a manytomany. In 'Bill' model form showed in the django admin panel, I want to bring preload results according my 'Person' model. In the filter_horizontal of 'Bill', I would like to show just results with 'is_partner=True' from Person, but all are showed. What is the best and 'right' way to do this in django? Is very important preload/filtering data in filter_horizontal. person/models.py: class Person(models.Model): title = models.CharField(max_length=256) is_partner = models.NullBooleanField(default=False) is_feature = models.NullBooleanField(default=False) business/models.py class Bill(models.Model): total_value = models.PositiveIntegerField() client = models.ManyToManyField('person.person') business/admin.py class BillAdmin(admin.ModelAdmin): filter_horizontal = ('client',) search_fields = ['__all__'] enter image description here -
Django model design assistance for an inventory app
I am making an inventory app for tools in my workshop and this is what i want to do: 1.- I want to have tool carts so I can check what tools are in what cart. 2.- I want to be able to keep a record of what tool gets damage, what cart was the tool in and the reason the tool got damaged also want to check if it a consumable item or not. 3.- I also want to be able to increase or decrease the quantity for each tool in the cart example (lets say I added 2 1/8" cutters in the cart and one gets damage in want it to read that there is still one 1/8" cutter ) What I'm currently are able to do is: 1- create a cart. 2- assign cart to employee. 3- assign tools to the cart. What I am having issues with is increasing or decreasing the tool quantity and recording the tool that goes bad I have some vague idea of what I need to do ( I need to create a table that assigns a unique id to every tool the goes in the cart) how ever I cant … -
Django is not sent logs to logstash
I begin sort out with logstash, but can not send logs with my project. Logstash is work fine, since I open l27.0.0.1:5000 on my browser and get new index. What I doing wrong? settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': 'velname)s %(message)s' }, }, 'handlers': { 'logstash': { 'level': 'ERROR', 'class': 'logstash.TCPLogstashHandler', 'host': '172.0.0.1', 'port': 5000, 'version': 1, 'message_type': 'django', 'fqdn': False, 'tags': ['django.request'], # list of tags. Default: None. }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'ERROR', 'propagate': True, } } } test.py import logging logger = logging.getLogger(__name__) def test (0): logger.error('test') -
Django recommendation system
I have this code recommendation.py from .models import Jobs def reco(request): def get_user_jobs(): user = request.user jobs = Jobs.objects.filter(applyed_users=user) for i in jobs: tags = i.tags reco = Jobs.objects.filter(tags=tags) return reco return get_user_jobs() Views.py def index(request): context = { 'reco_jobs': reco(request) } return render(request, 'index.html', context) but i get all job objects only if they have the same tags how i can find this -
update don't work in Django
I am reading the data from a worksheet and trying to update a table. ... try: equipment = Equipment.objects.filter(location=0, branch=branch).update( has_microphone = has_microphone, has_horn = has_horn, has_camera = has_camera, door_amount = door_to_str) equipment.save() except Exception as e: print e Error in console: 'int' object has no attribute 'save' Somebody can help me please? -
ubuntu django 1.11 install django-leaflet
I am playing around with geodjango and django > 1.11 is giving me ton of problems so I am using django 1.11 pip3 install django==1.11 now I am trying to install django-leaflet which I installed like pip3 install django-leaflet but this command upgraded to django 2 and broke my app. so how do I install django-leaflet without upgrading my django -
Django Heroku unable to verify first certificate
I am trying to deploy my django webapp on heroku. But when I try to login with Heroku credentials, It gives me the error : Unable to verify first certificate. (myDjangoEnv) C:\Python27\WebsiteWithDjango\DjangoStuff\mproj>heroku login heroku: Enter your login credentials Email: changaikwad@gmail.com Password: ************ Error: unable to verify the first certificate (myDjangoEnv) C:\Python27\WebsiteWithDjango\DjangoStuff\mproj> I tried many solutions online and also those available here but still I am not getting past this. I tried updating pip. Uninstalling heroku and reinstalling it but still no luck. Please help. -
My website serves properly on IP address but not on domain name
I am using nginx, ubuntu 14, gunicorn, django 1.11, python 2.7. I have put my domain in Allowed_HOSTS in the settings for django. This is what I have under sites-available: server { listen 8000; listen 80; server_name IP domain.com; location /static/ { root /home/username/website/src; } location / { include proxy_params; proxy_pass http://unix:/home/username/website/website.sock; } } When I put in the IP address into a computer connected to the network, the site comes up just fine, but when I type in the domain I set up, it shows me this: . -
Creating superuser error - no such column: app_profile.password
I'm trying to create a custom user registration model, but when I try to create a superuser I get the following error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) . File "/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 117, in handle self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 44, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 397, in get num = len(clone) File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 254, in __len__ self._fetch_all() File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 1179, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1068, in execute_sql cursor.execute(sql, params) File "/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in … -
How to serve complete htmlapp with django server using views.py
I have a folder which contains complete frontend built in oraclejet, you can get copy from here (http://www.oracle.com/technetwork/developer-tools/jet/downloads/index.html) download base distribution to get an idea. Folder contains index.html js and other files. To serve this file with django I kept all files from this inside "myapp/template/myapp" folder. contents from folder admin CONTRIBUTING.md css index.html js LICENSE.md metadata package.json README.md revnum scss THIRDPARTYLICENSE.txt myproject - contains manage.py I want to serve all files using django without using webserver or static mechanism provided by django, as I don't want to modify anything frontend files Now, in Flask I simply did this, and it worked no issues. @app.route("/demo/<path:path>", methods=['GET']) def static_resource(path): return send_from_directory('./demo/', path) But how to achieve same thing in Django ? urls.py urlpatterns re_path (r'^$', views.index , name='index'), re_path (r'^(?P.*)$',views.test_files1 , name='name' ) views.py def test_files(request , name): fname = "/home/archit/django_src/mysite/myapp/templates/myapp/" + name fsock = open(fname,"rb") return HttpResponse(fsock) I think there should be something simliar to "send_from_directory('./demo/', path)" in django as well Please Don't suggest answer for with below solutions as answers already available on stackoverflow How to serve web pages with apache server Don't want to change even single line with default oraclejet code, so adding {{ % static }} … -
Django: login page is not authenticating when the user exists in the database
I am very new to this so sorry if it bleedingly obvious. The sign_up method in my views works perfectly, it adds a user to the database with all the correct credentials. However, the log_in does not. It seems to keep telling me that I have invalid login details (the printed statement in views.log_in) and when I try to log in that way with the superuser I get a "Reverse for WSGIRequest: POST '/login/' not found." It could be something to do with the forms? Thanks very much for the help. models.py from django.db import models from django.db.models import CASCADE class User(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50) username = models.CharField(max_length=255) password = models.CharField(max_length=10) def __str__(self): return self.first_name + " " + self.last_name views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from accounts.forms import SignUpForm def sign_up(request): form = SignUpForm if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() return index(request) else: print("form invalid") return render(request, 'html/sign_up.html', {'form': form}) def log_in(request): print("here?") if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print("got to the login request") if user is not None: print("getting close...") if user.is_active: print("it worked") login(request, … -
Django - Trouble calling function in templates and return rendering the value of that function to the same page
I have a page that renders a list of objects from my database. I need to press a button that queries my database for a specific object, does some stuff in my views, and return a price value that I would like displayed on that same page in a pop-up bubble without reloading it, in place of the filler text I have. I've tried doing this by creating a form with a button that has the object's id in the value field, and sending that value to my original page's view, and then I call a function that handles the thing I want to do with that id. I request the object's id, pass it to the new view function , and query my database and try to return the value. I make an if request.POST statement in original page's view t, and change the rendered variable to the new value I want displayed. When I press the button, I get the same filler text in my pop-up bubble, and in my console I get the following error: ValueError: The view engine.views.search_list didn't return an HttpResponse object. It returned None instead. So it seems that I have to return a …