Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AnonymousUser Error when use django-rest-auth
I use the django-rest-auth to generate the token to certificate my APIs, all I have configured fine in my project. You see my snapshot top right corner, I have login my test01 account, using http://127.0.0.1:8000/rest-auth/login/(this is the django-rest-auth build-in link) But when I access the url to KoleListAPIView, there comes out issue, says the request is AnonymousUser: AttributeError at /api/userproducts/kole/list/ 'AnonymousUser' object has no attribute 'openstackcloud_id' Request Method: GET Request URL: http://localhost:8000//api/userproducts/kole/list/ Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute 'kole_id' My views.py is bellow: class KoleListAPIView(ListAPIView): """ list the Kole """ serializer_class = KoleListSerializer def list(self, request, *args, **kwargs): kole_id = self.request.user.kole_id # there comes the issue. if kole_id == None: return Response(data="please enter the password again", status=HTTP_511_NETWORK_AUTHENTICATION_REQUIRED, exception=Exception()) But I have login the test01 account. And my REST_FRAMEWORK in settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':[], #'rest_framework.permissions.IsAuthenticated' 'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework.authentication.TokenAuthentication'], 'PAGE_SIZE':10 } If I remove the 'rest_framework.authentication.TokenAuthentication' in the REST_FRAMEWORK of settings, its also this Error. -
Unable to add form data in the database in Django
Iam trying to save data from my forms to my database but somehow it is not happening. I have created forms in one of my apps which my admin uses.I am new to Django and any help would be greatly appreciated. Below is the relevant code: models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.hashers import make_password class Students(models.Model): username = models.CharField(max_length= 20) password = models.CharField(max_length=12) usn = models.CharField(max_length = 10, primary_key =True) def __str__(self): return self.username class Facultys(models.Model): username = models.CharField(max_length= 20) password = models.CharField(max_length=12) faculty_id= models.CharField(max_length = 10, primary_key =True) def __str__(self): return self.username class Admins(models.Model): username = models.CharField(max_length= 20) password = models.CharField(max_length=12) admin_id= models.CharField(max_length = 10, primary_key =True) def __str__(self): return self.username forms.py from django import forms from tcp.models import Login, Students, Facultys , Admins class StudentForm(forms.ModelForm): username = forms.CharField(max_length=128, help_text="Please enter the name.") password = forms.CharField(widget = forms.PasswordInput(), help_text = 'please enter the password') usn= forms.CharField(max_length=10 , help_text = "Please enter the USN") class Meta: model = Students fields = ['username' , 'password' , 'usn'] class FacultyForm(forms.ModelForm): username = forms.CharField(max_length=10 , help_text = "Please enter the name") password = forms.CharField(widget = forms.PasswordInput() , help_text = 'Please enter the password') faculty_id = forms.CharField(max_length=10, help_text= "Please … -
Django: Distinct Users Filtering
I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) In the template, {% for abc in data %} {{ abc.receiver }} <br/> {% endfor %} Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that? I'm hanged with this code from 1 month, I will be very thankful with every little help :) -
Django ReportLab PDF generation with SimpleDocTemplate
I am using SimpleDocTemplate to genetare and download pdf. My current code generating the PDF corectly but the pdf getting open in another tab of chrome browser with empty page and Its asking for 'Open' or 'Save' in FireFox browser. Where shoud i change my code to directly download the PDF without opening it in another Tab of Chrome. Thanks in advance. This is the code.. def GenerateTc(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename = "TC.pdf"' doc = SimpleDocTemplate(response,topMargin=20) doc.pagesize = landscape(A4) elements = [] data= [ ['---OFFICE USE ONLY---'], ['Date :','','ClassTeacher Signature: :',''], ['Principal Signature :','','Accountant Signature :',''], ['Student Name :'+' '+''], ['Remark :','','',''], ] style =TableStyle([ ('SPAN',(2,15),(3,15)), ('SPAN',(0,16),(1,16)), ('SPAN',(2,16),(3,16)), ('SPAN',(0,17),(3,17)), ('SPAN',(0,18),(3,18)), ]) #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' ps = ParagraphStyle('title', fontSize=15, alignment=TA_CENTER,) data2 = [[Paragraph(cell, s) for cell in row] for row in data] t=Table(data2) t.setStyle(style) getSampleStyleSheet() elements.append(Paragraph("TRANSFER/DISCONTINUATION ACKNOWLEDGEMENT",ps)) elements.append(Spacer(1,0.4*inch)) elements.append(t) doc.build(elements) return response Thanks You. -
Django-Rest-Auth authentication issue
I have created REST API using Django Rest Framework and used django-rest-auth for auth endpoints. I've also TokenAuthentication to secure the API. The problem arises when using APIDOC. I've added apidoc using coreapi. The documentation needs to be protected too. I can't use TokenAuth in the browser so I enabled SessionAuthentication. This resulted in login endpoint breaking with CSRF error. So how do I protect the endpoints with just TokenAuth and the documentation with SessionAuth separately? Or can I completely bypass security for login endpoint? -
GAE - Firebase Authentication using Retrofit
I have a Django webserver running on the standard Google App Engine environment. I've decided to use Firebase for authentication the Android application which has to get data using Retrofit from the webserver. public static Retrofit getClient(String baseUrl) { OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); String token = FirebaseInstanceId.getInstance().getToken(); Request.Builder builder = originalRequest.newBuilder().header("Authorization", token); Request newRequest = builder.build(); return chain.proceed(newRequest); } }).build(); if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } My Retrofit Client is created as shown above. This is called after a user has successfully logged in. I'm able to get the token and add that to the header in the OkHttpClient however on the webserver backend, I get the following error: AttributeError: 'WSGIRequest' object has no attribute 'headers' The Django code is: def index(request): id_token = request.headers['Authorization'].split(' ').pop() claims = google.oauth2.id_token.verify_firebase_token( id_token, HTTP_REQUEST) response_data = {} if not claims: logging.debug('Not Logged in') response_data['message'] = 'Not Logged In' else: logging.debug('Logged In!!!') response_data['message'] = 'Logged In' return JsonResponse(response_data) All I'm trying to do here is check if the authentication works. Any ideas what might be going wrong? Thanks -
no module - gunicorn
I am making a helloworld application in Django/python to test gunicorn integration. I have a directory and I have a start.sh file. I want to run a gunicorn server that will host a testing page. I am getting the following error: omars-mbp:helloworld omarjandali$ ../start.sh Starting Gunicorn. [2017-11-13 22:10:43 -0800] [1238] [INFO] Starting gunicorn 19.6.0 [2017-11-13 22:10:43 -0800] [1238] [INFO] Listening at: http://0.0.0.0:8000 (1238) [2017-11-13 22:10:43 -0800] [1238] [INFO] Using worker: sync [2017-11-13 22:10:43 -0800] [1241] [INFO] Booting worker with pid: 1241 [2017-11-13 22:10:43 -0800] [1241] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) ModuleNotFoundError: No module named 'helloworld' [2017-11-13 22:10:43 -0800] [1241] [INFO] Worker exiting (pid: 1241) [2017-11-13 22:10:43 -0800] [1242] [INFO] Booting worker with pid: 1242 [2017-11-13 22:10:43 -0800] [1242] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in … -
Django - Multi Table Inheritance with django admin
I am trying to learn django by creating a blog on my own, and I've tried some real simple steps before, but now I want to make something slightly more complex. Currently, I am thinking of dividing the blogs' 'Stories' into 'Blocks'. My idea is to have two child classes 'TextBlock' and 'ImageBlock', and my current models look like this. class Story(models.Model): writer = models.CharField(max_length=189) title = models.CharField(max_length=189) class Block(models.Model): story = models.ForeignKey(Story, related_name='+', on_delete=models.CASCADE) block = EnumField(choices=[ ('TXT', "text"), ('IMG', "image"), ]) serial = models.IntegerField(default=0) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class TextBlock(Block): type = models.CharField(max_length=128, blank=True, null=True, default='paragraph') content = models.TextField(blank=True, null=True) class ImageBlock(Block): src = models.URLField() type = models.CharField(max_length=128, blank=True, null=True, default='full') title = models.CharField(max_length=189, blank=True, null=True) photographer = models.CharField(max_length=128, blank=True, null=True) What I'd like to do now is to create blog entries from the django admin interface. Is it possible to create both types from the main Block? Or do I need to go to both TextBlock and ImageBlock? Any ideas on how I should proceed from here? Thanks. -
Django: Model.objects.filter(a=X, b=Y) not returning desired objects
So I'm trying to query my database for all submissions that have user=request.user and id=12. I know for certain that there are multiple submissions that match this, but filter() only returns one submission. What is wrong with my query? Thanks Submission.objects.filter(user=request.user, id=puzzleID) Edit: Thank you to all responders. Here is my model for Submission and Puzzle: class Submission(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, ) puzzle = models.ForeignKey( Puzzle, on_delete=models.CASCADE, ) userAnswer = models.TextField() datetime = models.DateTimeField(default=datetime.now, blank=True) class Puzzle(models.Model): title = models.CharField(max_length=30) question = models.TextField() datetime = models.DateTimeField( default=datetime.now, blank=True) # image = models.ImageField() answer = models.TextField(default="answer") trials = models.IntegerField( default=1, validators=[MinValueValidator(1)]) subject = models.CharField( default="CS", max_length=2, choices=( ("CS", "Computer Science"), ) ) Edit 2: Here is also the view in which the query is made puzzle = Puzzle.objects.get(id=puzzleID) form = SubmitForm() userTrials = len(Submission.objects.filter(user=request.user, puzzle=puzzle)) if userTrials >= puzzle.trials: limitReached = True else: limitReached = False return render(request, "puzzle.html", { "puzzle": puzzle, "form": form, "userTrials": userTrials, "remaining": puzzle.trials - userTrials, "limitReached": limitReached, }) -
Reverse for 'django_markdown_preview' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am using django_markdown but it is showing error when I am trying to render form. The error is on 17th line {{ form }} Error. The error is in reverse of 'django_markdown_preview', but I have included url('^markdown/', include('django_markdown.urls')), in my urls.py. Can anyone help me to resolve the error. {% extends 'qaforum/base.html' %} {% load django_markdown %} {% block content %} {% if message %} <strong>Enter a valid Question!</strong> {% endif %} <form method="post" action="{% block action_url %}{% url 'qaforum:qaforum_create_question' %}{% endblock action_url %}"> {% csrf_token %} {% for field in form.visible_fields %} <tr> <th>{{ field.label_tag }}</th> <td> {{ field.errors }} {{ field }} {{ field.help_text }} </td> </tr> {% endfor %} <input class="btn pull-right btn-success" type="submit" value="Submit Question" /> </form> </div> {% endblock content %} {% block extra_js %} {% markdown_editor "#id_description" %} {% markdown_media %} {% endblock extra_js %} -
Cant pull or push dockerhub repo to or from my local macine - docker
I have a local project I want to pus to docker hub. I have an account with docker gub and i created a respository for testing docker out. My local file with my project is called docker-test and it is a django application. My docker hub projects is also named docker-test. I am running the following commands and I am getting the following errors... Can anyone help me... This is the push docker push omaryap/docker-test The push refers to a repository [docker.io/omaryap/docker-test] An image does not exist locally with the tag: omaryap/docker-test this is the pull omars-mbp:docker-test omarjandali$ docker pull omaryap/docker-test Using default tag: latest Error response from daemon: manifest for omaryap/docker-test:latest not found This is the link to my docker hub repo: https://hub.docker.com/r/omaryap/docker-test/ -
How to dynamically add EC2 ip addresses to Django ALLOWED_HOSTS
We've recently changed our deployment strategy to use AWS auto scaling group. One problem we have in production is the new created EC2s, our Application starts to return Invalid HTTP_HOST header: <ip_address>. You may need to add <ip_address> to ALLOWED_HOSTS` because these EC2s are not in the original Django ALLOWED_HOSTS. But it doesn't make sense for each EC2 newly created we have to redeploy, that loses the sense for "auto scale". And we don't want to use wildcards or IP range for security reasons. -
How can I serialize a redundant object to the serializer?
I have a model name CloudServer, which has a openstackserverid field, through it I can get a object: class CloudServer(models.Model): openstackserverid = models.CharField(max_length=128) buytime = models.ForeignKey(to=BuyTime) expiration_time = models.DateTimeField() availablearea = models.ForeignKey(to=AvailableArea) profile = models.TextField() In the serializer: class CloudServerListSerializer(ModelSerializer): class Meta: model = CloudServer fields = "__all__" In the views: class CloudServerListAPIView(ListAPIView): serializer_class = CloudServerListSerializer I can use the bellow function to get the openstackserver object. def getOpenstackServer(openstackserverid): ... return openstackserver The openstackserver object is like bellow: openstack.compute.v2.server.ServerDetail(OS-EXT-STS:task_state=None, addresses={u'private': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:23:75:7b', u'version': 4, u'addr': u'192.168.1.8', u'OS-EXT-IPS:type': u'fixed'}]}, links=[{u'href': u'http://controller:8774/v2.1/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'self'}, {u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/servers/0672107f-e580-4a24-9d0a-867831d6b7d2', u'rel': u'bookmark'}], image={u'id': u'ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/images/ecbd1ef0-7dcf-41ff-8618-4501aa4e3945', u'rel': u'bookmark'}]}, OS-EXT-STS:vm_state=active, OS-EXT-SRV-ATTR:instance_name=instance-00000047, OS-SRV-USG:launched_at=2017-11-10T12:52:09.000000, flavor={u'id': u'a27c55bc-ef20-4dcf-a924-a02a4361fc01', u'links': [{u'href': u'http://controller:8774/99a50773b170406b8902227118bb72bf/flavors/a27c55bc-ef20-4dcf-a924-a02a4361fc01', u'rel': u'bookmark'}]}, id=0672107f-e580-4a24-9d0a-867831d6b7d2, security_groups=[{u'name': u'default'}], user_id=fb52853bde3d4d3e8e831749781f8671, OS-DCF:diskConfig=MANUAL, accessIPv4=, accessIPv6=, progress=0, OS-EXT-STS:power_state=1, OS-EXT-AZ:availability_zone=nova, metadata={}, status=ACTIVE, updated=2017-11-10T12:52:09Z, hostId=76f61a58cf6d411a30e3e34da4dd252a03aa0093d9dd19c653b234b3, OS-SRV-USG:terminated_at=None, key_name=None, OS-EXT-SRV-ATTR:hypervisor_hostname=controller, name=vm-00000, created=2017-11-10T12:51:44Z, tenant_id=99a50773b170406b8902227118bb72bf, os-extended-volumes:volumes_attached=[], config_drive=) So far, as all I know, I only can serialize the CloudServer model's fields. Where I can serialize the object, is in the serializers or views ? and how to do with that? -
Could not make migrations after deleting db.sqlite3 Django
After doing so many change in models, I could not access to use database.So, I applied solution that delete all migrations and db.sqlite3 database and make migrations again.But, unfortunately it doesn't work. I got the error like this: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-ackages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\makemigrations.py", line 96, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 244, in build_graph self.graph.validate_consistency() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration taggit.0003_tag_tags dependencies reference nonexistent parent node ('personal', '0006_auto_20171113_1322') How can I make migrations again?? -
I need help running a simple <h1>"Hello"</h1> through the views.py file
I am trying to run a simple Hello through the views.py file. Here is what the terminal is saying: SyntaxError: Non-ASCII character '\xef' in file /Users/carlosecharte/workspace/blog/blogone/blogone/urls.py on line 25, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details This is my urls.py file: from django.conf.urls import url from django.contrib import admin from posts.views import post_home urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/$', "posts.views.post_home"), ] -----------------------------------------// This is my views.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. def post_home(request): return HttpResponse("<h1>Hello</h1>") -------------------------------------------//------- As you can see the Hello is in the views.py file. Thanks! -
Django ORM: Tried to do inner join with foreign key but causes FieldError
I am new to django orm. I've tables look like this. class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=60) class ProductOption(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) product_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) I would like to query productoption id that related to product. I made query like this to do inner join. Query = Product.select_related(‘product_id’) And it gaves me error message saying django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'product_id'. Choices are: (none) I want to know if there is something wrong in models or query. -
TypeError: get_serializer_class() missing 1 required positional argument: 'self'
I get error when I use the view's function, the bellow is my traceback: File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 40, in <module> class UserListAPIView(ListAPIView): File "/Users/xxx/Desktop/xxx/Project/xxx/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView serializer_class = get_serializer_class() TypeError: get_serializer_class() missing 1 required positional argument: 'self' My views.py code ie bellow: class UserListAPIView(ListAPIView): """ """ queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4) filter_backends = [SearchFilter, OrderingFilter] search_fields = ['username', 'qq', 'email'] pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] def get_serializer_class(self): if self.request.user.is_superuser: return UserAdminListSerializer else: return UserListSerializer serializer_class = get_serializer_class() # this is the line 59 And if I write this line serializer_class = get_serializer_class() to in the front of def get_serializer_class(self): method, I will do not find error. -
Health App : Data saved for a specific patient is being shown in detail view for other patients.
In my health app I am attempting to allow the user to enter patient symptom data and save it. My app contains Identity, Symptom, and IdentitySymptom models. A ManyToManyField exists between the Identity and Symptom. The IdentitySymptom model contains both ForeignKey fields each referencing the Identity and Symptom model. In my views document I used class based views to ensure that each Symptom object I created was attached to a patient. ** PROBLEM ** Each time I save a symptom object data connected to one patient object, that data also shows up in the view of other patient objects. Each nomenclature and descriptionfield should be attached to the patient object for which it was created. However, each time the fields are populated and saved the nomenclature and description seen in all the patients created which is not what I want. Below both Tashoy and Qadi have the same nomenclature and description but I only clicked the Tashoy Beckford anchor tag nomenclature and description How do I ensure that only Tashoy Beckford has that Symptom object data. Essentially I want to ensure the relevant symptoms connect to the relevant patients. Here is the code : models class Identity(models.Model): NIS =models.CharField(max_length = … -
CSV not importing to django models
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt. settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/data') models.py: from __future__ import unicode_literals from django.db import models from django.contrib import admin class Data(models.Model): # A bunch of model objects (CharField/IntegerFields mainly) class Meta: verbose_name_plural = 'Data Sets' def __str__(self): return self.someobject views.py: from __future__ import unicode_literals from django.conf import settings from django.shortcuts import render, render_to_response from django.template import RequestContext from .models import Data import csv import os def landing(request): # Opens all csv files in specified directory directory = os.path.join(settings.STATIC_ROOT) for files in os.walk(directory): for … -
DisallowedHost error using PythonAnywhere
I'm new to Python and Django, and I'm following this tutorial to learn some Django basics. I keep getting a DisallowedHost error. (Screenshot: https://ibb.co/c1beYG) As per this post, I added 'chocoberrie.pythonanywhere.com' to the ALLOWED_HOSTS list in settings.py, and I made sure to include it in quotation marks and keep the brackets. I even added it to requests.py, at line 113 (indicated in the error message). Additional screenshots: https://ibb.co/jwUNnb and https://ibb.co/fbmrfw I also committed the changes to Git, and I double-checked the repository to make sure that the URL was added to ALLOWED_HOSTS. I also made sure to reupload the changes on PythonAnywhere. After all that, I'm still getting the error! It's really frustrating, and I don't know what else to do. Any help would be much appreciated! Note: I did see a way to "disable" this error in this post, but I'm using a newer version of Django, so I don't know how to apply this. -
How to order django model by foreign key image title alphabetically
I have model that I need to be able to order in the admin panel alphabetically by the title of the image foreign key. Currently with the code below the models get ordered by when the associated 'logo' images were added to the database, as opposed to by the titles of the associated 'logo' images. class Client(models.Model): logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) homepage_visible = models.BooleanField(default=True) panels = [ MultiFieldPanel([ ImageChooserPanel('logo'), FieldPanel('homepage_visible'), ], heading='Client information'), ] def __str__(self): return self.logo.title class Meta: verbose_name = 'Client Logo' verbose_name_plural = 'Client Logos' ordering = ['logo'] -
Django - MySQL: 1045 Access Denied for 'user'@'localhost'
I have a Django app using a MySQL database. I created a database foo, then created a new user foo_user, granted all privileges on foo.* to foo_user, and flushed privileges. I can log in from the command-line as foo_user and SHOW GRANTS; which gives me this: +-----------------------------------------------------------+ | Grants for foo_user@localhost | +-----------------------------------------------------------+ | GRANT USAGE ON *.* TO 'foo_user'@'localhost' | | GRANT ALL PRIVILEGES ON `foo`.* TO 'foo_user'@'localhost' | +-----------------------------------------------------------+ I can connect from Python using this snippet: import MySQLdb try: db = MySQLdb.connect('localhost', 'foo_user', 'verysecurepassword', 'foo') cursor = db.cursor() cursor.execute('SHOW GRANTS;') results = cursor.fetchall() for r in results: print(r) except MySQLdb.Error as e: print(e) This prints the privileges for foo_user as one would expect. settings.py db_pass = '' db_pass_file = os.path.join(os.path.expanduser('~'), 'db.passwd') with open(db_pass_file, 'r') as dbpf: db_pass = dbpf.read() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'foo', 'USER': 'foo_user', 'PASSWORD': db_pass, 'HOST': 'localhost', 'PORT': '3306', }, } However, when I try to makemigrations I get django.db.utils.OperationalError: (1045, "Access denied for user 'foo_user'@'localhost' (using password: YES)") I've followed the advice of every SO answer I could find. I've dropped databases and users and then recreated them several times. I can't find anything obviously wrong with it and … -
Internal server error when set cookie in Django
In URL maybe additional parameters for example like utm_campaign In view i get this parameters: utm_campaign = request.GET.get('utm_campaign',None) But when i wanna set this information in cookie i get Internal Server Error without traceback or another information I was trying several solution: response.set_cookie('utm_campaign',utm_source) response.set_cookie('utm_campaign',utm_source.encode('utf-8')) response.set_cookie('utm_campaign',utm_source.encode()) response.set_cookie('utm_campaign',request.GET.get('utm_source')) What is the problem? The problem is that if I write English text or numbers - everything works. If I try write cyrillic text - there is an error without details. Python3 CentOs7 (default "utf-8") Django 1.11 (default "utf-8") -
Image paths in Django view are relative to directory instead of MEDIA_URL
I've been struggling with this problem for a few days and unable to solve it on my own. I am working on a blog site. The post view is rendered at a URL such as this: domain.com/blog/specificpost/ I have an ImageField in my model. The images upload properly and I can address the images at the correct URLs. domain.com/media/asset.jpg In my settings.py I have defined the media paths. When I access the image files from the Admin, they work properly. MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' When rendering the view of the post, the image path is rendered incorrectly in the DOM. It is: domain.com/blog/media/asset.jpg It should be: domain.com/media/asset.jpg In my urlpattern I have appended: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and added the relevant imports to urls.py. I believe this code is supposed to serve the files at the domain root during development. I have tried all the solutions here, but the image URLs still render relative to the directory. Any help to set me on the correct path would be useful, thank you very much. -
TypeError : 'manuscript' is an invalid keyword argument for this function
In my health app I am attempting to allow the user to enter patient symptom data and save it. My app contains Identity, Symptom, and IdentitySymptom models. A ManyToManyField exists between the Identity and Symptom. The IdentitySymptom model contains both ForeignKey fields each referencing the Identity and Symptom model. In my views document I used class based views to ensure that each Symptom object I created was attached to a patient. Problem : Each time I created a Symptom object and click to save it, it returns this error : Traceback: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/iivri.andre/vision_Map/iivri/script/views.py" in post 115. medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/query.py" in create 392. obj = self.model(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/base.py" in __init__ 573. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) Exception Type: TypeError at /script/medical-document/O910231/ Exception Value: 'manuscript' is an invalid keyword argument for this function I …