Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python- Django local server refuses to connect to admin page
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.3 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/admin/sites.py in has_permission, line 186 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 Python Version: 3.5.2 Python Path: ['/Users/zeinalabidin/Desktop/website', '/Users/zeinalabidin/Desktop/website', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages'] Server time: Thu, 15 Mar 2018 03:13:25 +0000 I am running the latest version of django and everything is setup correctly. When I try to run the local django server it runs fine. but when I try to access the admin page it shows the error above. I have looked for other solutions online but non of them seem to fix my problem. can anyone help? -
How do I create a demo account in Django?
I have visited a couple of sites and they offer the option to try their site without registering, but you can login with something like someusername@somesite.com and somesiteguest. I want to implement this for my own site. Currently I am using django-allauth for handling registration and logins. I am just not sure how to handle users login with the same credentials. -
attempting to delete an object in many to one relation but will not delete django. Django rest framework
I am deleting a model in a many to one relation. Youll notice in the delete method I am exposing the parent model. This is for permissions which I will write later. The code is not deleting the objects. As in method runs and my javascript removes the object. But If I reload the page, I get the objects back. what could be happening? def delete(self, request, *args, **kwargs): venuepk = kwargs.get('venuepk', None) venue = get_object_or_404(Venue, pk=venuepk) venuerooms = venue.room_set.all() roompk = kwargs.get('roompk') roomobject = None for room in venuerooms: if room.pk == roompk: roomobject = Room.objects.get(pk=roompk) roomobject.delete() return Response({}) return Response(status.HTTP_404_NOT_FOUND) -
An alternative query to postgres' distinct in Django
Given this django model: def Price(model.Model): date = models.DateTimeField() item = models.ForeignKey('Item', on_delete=models.CASCADE) price = models.IntegerField(blank=True, null=True) The goal is to get the most recent price for each item which can be queried quite simply.. assuming the orm is using postgresql: Price.objects.all().order_by('date').distinct('item') When using other database engines, it isn't possible to distinct on specific fields, and I'd like to avoid locking myself into postgres so I've been looking for a query that emulates it. I've written/found a query that does the job: Price.objects.raw(''' SELECT P1.* FROM `merchapi_pricelog` P1 LEFT JOIN `merchapi_pricelog` P2 ON P1.item_id = P2.item_id AND P1.date < P2.date WHERE P2.date is NULL ''') The raw query is faster than loading and filtering the data in code but I am interested to see if there is a better way to do this in a db-agnostic way that doesn't resort to using raw sql. -
Django- Testing file returned in httpresponse
I have a django test method that checks to see if an image returned as an httpresponse equals the image as it was opened before the http request was sent to the view: def test_uploaded_file(self): c = Client() originalFilePath = '../static_cdn/test_img.jpg' image_data = open(originalFilePath, "rb") with open(originalFilePath, "rb") as fp: response = c.post('/', {'image': fp}) self.assertEqual(image_data,response) For some reason, the test is returning this error: AssertionError: <open file u'../static_cdn/test_img.jpg', mode 'rb' at 0x7fed326b6a50> != <HttpResponse status_code=200, "image/jpg"> I think the issue has to do with the fact that the image returned from the view is an httpresponse and while the other image being opened in the test method is not. Why could this test be failing? -
Django user sign up crashes with `TypeError: 'field_name' is an invalid keyword argument for this function`
I would like to add an additional information to user profile during registration. I've created class Profile and defined Django signals: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) public_email = models.EmailField(null=True, blank=True) extra = models.CharField(max_length=100, default='') def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_user_profile(sender, instance, **kwargs): instance.profile.save() post_save.connect(create_user_profile, sender=User) post_save.connect(save_user_profile, sender=User) During the registration form processing I call User.objects.create_user(username=username, password=password, email=email, extra='Extra info') and get TypeError: 'extra' is an invalid keyword argument for this function I've seen a lot of tutorials use this method, moreover Django documentation recommends this method. But I do not understand why it crashes for me. -
objects not deleting from database. Django, Django Rest Framework
I have the following models: class Venue(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000, null=True, blank=True) streetaddress1 = models.CharField(max_length=150) streetaddress2 = models.CharField(max_length=150 ,null=True, blank=True) approved = models.BooleanField(default=False) declined = models.BooleanField(default=False) eventplannerstaff = models.BooleanField(default=False) declineddate = models.DateField(null=True, blank=True) declineddatestring = models.CharField(max_length=50, blank=True, null=True) declinereason = models.CharField(max_length=200, blank=True, null=True) class Room(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) online = models.BooleanField(default=False) description = models.CharField(max_length=1000, blank=True, null=True) privateroom = models.BooleanField(default=False) semiprivateroom = models.BooleanField(default=False) seatedcapacity = models.CharField(max_length=10, null=True, blank=True) standingcapacity = models.CharField(max_length=10, null=True, blank=True) I have a REST endpoint with a delete method. I am trying to delete a room. A room is tied to a venue. I am not deleting the room directly as I want to expose the venue in this method. The permission code isn't written yet, but I will be wanting to see if the user has the permissions to mess around with the venues room. The delete method is working but it is not actually deleting the rooms from the database. What am I doing wrong? def delete(self, request, *args, **kwargs): venuepk = kwargs.get('venuepk', None) venue = get_object_or_404(Venue, pk=venuepk) venuerooms = venue.room_set.all() roompk = kwargs.get('roompk') roomobject = None for room in venuerooms: if room.pk == roompk: roomobject = … -
how can i test my custom model manager in django
following is my custom manager class DefaultModelManager(models.Manager): def get_or_none(self, **kwargs): try: return self.get(**kwargs) except self.model.DoesNotExist: return None Model class TestModel(models.Model): objects=DefaultModelManager() how can i test this code? Following is my code class ModelManagerTest(TestCase): def test_can_get_or_none(self): TestModel.create('...') test = TestModel.objects.get_or_none('...') test2 = TestModel.objects.get('...') self.assertEqual(test, test2) def test_cant_get_or_none(self): test = TestModel.objects.get_or_none('...') self.assertEqual(test, None) is it correct??? or another method... What is the best way to test custom model manager -
How to get filename of image in httpresponse
I have a file django view that takes a form request with an image as the submitted content and then returns an httpresponse of the image to be displayed back in the template. I'm new to testing in django and I'm trying to essentially assert that the file that was originally uploaded in the form request is the same one that is being returned back to the user. Here is the code in the view that handles the http request and returns the response: form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): print request instance = form.save(commit=False) instance.save() instance = PhotoUploader.objects.get(id=instance.id) image_full_path = instance.image.path image_data = open(image_full_path, "rb").read() return HttpResponse(image_data, content_type="image/png") In my test function , I have the following code: c = Client() originalFileName = 'Keep-Calm-and-Carry-On.jpg' with open('../../static_cdn/Keep-Calm-and-Carry-On.jpg', "rb") as fp: response = c.post('/', {'image': fp}) self.assertEqual(originalFileName,response.image.path) In order to test whether the original file uploaded is coming back in the response, I'm trying to check that the original filename and the one in the response match. I'm not sure how to get the file name from the response since it is just an image though. How can I get the … -
How to connect canvas with django model
I am having trouble with getting canvas insert to django model field. I'm using forms to get informations from user to create new object and one of them is FileField, which in this case will be canvas. Here's the most important canvas.js var png = ReImg.fromCanvas(document.getElementById('canvas')).toPng(); views.py: form.instance.comics = request.POST("png") create.html: `<form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button id = "png" name = "png" >Save</button> </form>` Is it possible to do something like that? I've looked everywhere for answers, but without result. Form is working, everything is insert to object, but not FileField (canvas in this case). -
How does 'max_length' affect Django models?
Does max_length affect anything outside of the maximum number of characters you can add to a specific database field (i.e. does it affect the amount of memory that is set aside for the database?). Would there be any unintended consequences for setting all fields to the maximum CharField length, which is ~65,000, even if it was completely unnecessary (apart from being bad practice)? -
Django get() model query not returning object
What I have is a basic forum. Now, what I'm trying to do is retrieve the Post from a Topic within the Board. Everytime I hit localhost:8000/boards/1/topics/1 I get the following: "No Topic matches the given query.". I'm suspicious of the get parameters may be the culprit but I'm unsure of what parameters I must specify in order to retrieve the desired object. Below is the full flow of code, please advise. Thank you urls.py: path('boards/<board_id>/topics/<topic_id>', views.topic_posts, name = 'topic_posts') views.py: def topic_posts(request, board_id, topic_id): topic = get_object_or_404(Topic, board_id = board_id, topic_id = topic_id) return render(request, 'topic_posts.html', {'topic': topic}) models: from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. class Board(models.Model): ''' id auto generated ''' name = models.CharField(max_length = 30, unique = True) description = models.CharField(max_length = 100) def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length = 255, default = '') last_updated = models.DateTimeField(default = datetime.now(), blank = True) board = models.ForeignKey(Board, related_name = 'topics', on_delete = models.CASCADE) starter = models.ForeignKey(User, related_name = 'topics', on_delete = models.CASCADE) class Post(models.Model): message = models.TextField(max_length = 4000, default = '') topic = models.ForeignKey(Topic, related_name = 'posts', on_delete = models.CASCADE) created_at = models.DateTimeField(default = … -
Django overriden template testing
What would be a "django-pythonic" way to test a simple template view that is overriden in an app. Say we have an app X with a template view rendering a simple html (containing just a word "foo"). One can write a test to verify its contents in app X using the test client: def test_myview(self): response = self.client.get(reverse(some_view_name)) self.assertContains( response, 'foo' ) Then we have another app Y which simply overrides this template (and includes only "bar" text) and the following test passes in app Y: def test_myview_overriden(self): response = self.client.get(reverse(some_view_name)) self.assertContains( response, 'bar' ) However, if we run all tests (simple manage.py test) on a project which has both apps enabled (X and Y), the former test (test_myview) will not pass, as the view shows only overriden template contents (i.e. "bar" text). Any suggestions on how to deal with such a situation in a "pythonic" way so both tests pass? -
Django Jquery/Ajax File Upload No File In POST
i am trying to work on uploading a csv to a django app. The issue that i'm having is I can't seem to pass the file and be able to access it with my view. There are no errors form.py: class FileUploadForm(forms.Form): csv_file = forms.FileField() HTML: <form action="{% url 'ajax-view' %}" method="post" enctype="multipart/form-data" id="fileForm">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload" /> </form> js file: // i've tried to add this as well passing file and data to the ajax var file; $('#id_csv_file').on('change', function(){ file = event.target.files; }); $('#fileForm').on('submit', function(e){ e.preventDefault(); var data = new FormData($('#fileForm').get(0)); data.append('file', $('#id_csv_file')[0].files); var csrftoken = getCookie('csrftoken'); $.ajax({ type: "POST", headers: {'X-CSRFToken': csrftoken}, url: '/ajax/success/managers/tool', data: {'file': data}, processData: false, contentType: false, dataType: "json", success:function(data) { // display the new data console.log(data) } }); }); My views are: def view(request): form = FileUploadForm() return render(request, 'template.html', { 'form':form }) def ajax_view(request): if request.method == "POST": print request.POST print request.FILES the above prints just show: <QueryDict: {}> <MultiValueDict: {}> -
unable to connect to google cloud sql on flexible env python 3.5
Im trying to deploy an existing django app into google cloud platform. I ran into an error when following their instructions online: https://cloud.google.com/python/django/flexible-environment I deployed the app successfully, but am having trouble connecting to the sql database i created on the google cloud. In my ipython book, i am able to connect however using pymysql. My database on cloud sql is called "retail_service_data", with username: root and password: secret In my ipython file, i can successfully connect using following: host = '127.0.0.1' user = 'root' password = 'secret' conn1 = pymysql.connect(host=host, user=user, password=password, db='retail_service_data') cur1 = conn1.cursor() I type the above after i go to google cloud shell and type: cloud_sql_proxy.exe -instances="scoviileapp:us-east1:retail18"=tcp:3306 After entering above, i get a notification in my google cloud shell "listening on 127.0.0.1:3306 for scoviileapp:us-east1:retail18 ready for new connections" Hence, I am able to connect in my computer. I ran python manage.py run server to make sure it works on my end, and it does. Then i typed: gcloud app deploy it successfully deploys the app. But upon, testing, i get this error as shown by this website: https://scovilleapp.appspot.com/search/?fname=james&mname=g&lname=stahl&street_num=1045&street_name=beck&street_type=rd&state=OH&zip=48277 Im not sure exactly what to do. Heres my app.yaml file and the settings file. Im using … -
Can websocket access be restricted to my mobile app when using django channels and Ionic 3
I am creating a mobile app with a django channels backend. Typically the solution provided to allow the mobile app to communicate with the backend is: Access-Control-Allow-Origin: * However I believe this would allow any origin to connect to the websocket and have access to the data. How can I restrict websocket access to only my app? What would a company like google do? -
Firebase Token Authentication using Django
I am new to django and am trying to get the user authenticated using firebase admin sdk. I am trying to do token authentication and have setup the admin sdk in my django app. Also I have received the client id token in the android app. Now I am unable to understand how to send this id to the backend and verify it as a user and create users accordingly.I did find this answer but couldn't really understand how to go about this. Also if a user is verified how do I add and update its data. Do I pass the token again or is there any other way to do it? -
Modify url path generated by serializers.HyperlinkedIdentityField
Is there an easy way to modify the hyperlink generated by serializers.HyperlinkedIdentityField? Specifically, I want to append /download to the url path. > class AbcSerializer(serializers.HyperlinkedModelSerializer): > url = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail") > url_download = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail") #append /download to this url > > class Meta: > model = abc > fields = ('url', 'url_download') -
Creating a base response for API calls
I want to create an API by using django-rest-framework. So far I've managed to setup one endpoint of API and managed to fetch all items. A basic response (without the BaseResponse class described later) would look like this: [ { "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83", "created_at": "2018-03-12T19:25:07.073620Z", "updated_at": "2018-03-12T19:25:37.904350Z", "deleted_at": null, "random_name": "random name" } ] The result I would like to achieve would be something like this: [ "success": true "message": "Some exception message", "data" :{ "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83", "created_at": "2018-03-12T19:25:07.073620Z", "updated_at": "2018-03-12T19:25:37.904350Z", "deleted_at": null, "random_name": "random name" } ] I managed to achieve this by creating a BaseReponse class and in view I simply return BaseResponse.to_dict() (a method that I have created inside of class). class BaseResponse(object): data = None success = False message = None def __init__(self, data, exception): self.data = data self.message = str(exception) if exception is not None else None self.success = exception is None def to_dict(self): return { 'success': self.success, 'message': self.message, 'data': self.data, } View: class RandomModelList(APIView): def get(self, request, format=None): exception = None models = None try: models = RandomModel.objects.all() except Exception as e: exception = e serializer = RandomModelSerializer(models, many=True) base_response = BaseResponse(data=serializer.data, exception=exception) return Response(base_response.to_dict()) I want to mention that with the current code … -
Django SECRET_KEY called in os.environ but isn't an environment variable
I've been asked to look at a Django project where the developer has disappeared. I cannot work out how they've set the SECRET_KEY. In settings.py we have SECRET_KEY = os.environ['SECRET_KEY'] It is running on a Ubuntu 14.04.05 server. I understand the code above to mean the SECRET_KEY has been set as an environment setting so in terminal I type printenv to see the environment settings and SECRET_KEY isn't there. How might it be being set? -
server couldn't stop sending emails after cron job and django q were started
I am coming here in real desparation. I am receiving 100+ emails from my test server. We have a feature that will notify members somethings once in a week. It is a django app and we are using django_q with reddis. To start, I decided to send hardcoded emails from a sample function. Set up scheduled tasks for django_q in admin area Started qcluster with python manage.py (probably made a mistake as it was started with a cron job that meets the time of schedules above) Now i do get the emails as intended and it started at the scheduled time. But now, I cant stop it. Deleted the schedule; deleted the cron job; stopped reddis (which is the worker for qcluster of django_q) and finally, the function that contains hardcoded emails. I have restarted server itself but still I am getting emails. My fear is it might behave the same with the real application. I am in ubuntu, running ngix, djang_q 0.8 and django 1.11 -
Django REST Framework : ListCreateAPI and RetrieveUpdateDelete Api for complex foreign key relationships
Apologies if this seems trivial but i want to know what is the most Django way to do this. Below are the models, views and serializers listed for reference. There are 3 models. I am just showing the relevant fields for each, though they have multiple fields. Now, one blog can have multiple authors contribute to it. Similarly one author or contributor can contribute to multiple blogs. class Blog(models.Model): title = models.CharField(max_length="120") ... class Author(models.Model): title = models.CharField(max_length="120") ... class BlogAuthor(models.Model): blog = models.ForeignKey('Blog') author = models.ForeignKey('Author') creator = models.ForeignKey('auth.User') # Should the above relations be a Foreign Key or ManyToMany Field I am using DRF 3.0 to create the below APIs: GET /blogs/1/author : to get a list of authors for the blog identified by id 1 POST /blogs/1/author: create which authors are related to the blog 1 GET /blogs/1/author/1: show details of the author 1 in context of the blog 1; for ex, author 1 may have contributed 300 words to blog 1 so this would return that along with some other details, say name of the author, picture of the author etc DELETE /blogs/1/author/1 : deletes the relation between blog 1 and author 1, thought both entities … -
How to install downloaded django project in virtualenv
I am trying to follow the instructions from this Django/Ajax tutorial: https://realpython.com/blog/python/django-and-ajax-form-submissions/. They say: Download the compressed pre-ajax Django Project from the repo https://github.com/realpython/django-form-fun/tree/master/part1 Activate a virtualenv Install the requirements Sync the database Fire up the server Here is what I am doing: Create new virtualenv using virtualenv -p /usr/bin/python3 ajaxenv inside home/ajaxtutorial/ folder Download the repo and unpack its django-form-fun/part1/pre-ajax/talk_project/ folder in the home/ajaxtutorial folder. Put the requirements.txt provided with the downloaded repo in ajaxenv/bin Run pip install -r requirements.txt inside ajaxenv. At this point I can see that Django gets installed, but I don't think anything else does. At this point the tutorial says to "sync the database". The only way I know how to do this is to use python manage.py migrate, but this throws an error. I guess this method requires starting the project or an app first, which is not a case here, since both the app and the project are downloaded, not created by me. I don't know how to proceed from here. python manage.py migrate throws the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/bart/ajaxtutorial/ajaxenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/bart/ajaxtutorial/ajaxenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 392, in … -
Matplotlib not working with Python 2.7 and Django on OSX
I am trying to use matplotlib and mpld3 to produce some html plots on my Django report app. Basically I have a controller for the plot that is the following: from django.shortcuts import render import mpld3 from matplotlib.pyplot import figure, title, bar def cpfLogin(request): mpl_figure = figure(1) xvalues = (1,2,3,4,5) yvalues = (1,2,3,4,5) width = 0.5 # the width of the bars title(u'Custom Bar Chart') bar(xvalues, yvalues, width) fig_html = mpld3.fig_to_html(mpl_figure) context = { 'figure': fig_html, } return render(request, 'reports/CPFReport.html', context) The code for reports/CPFReport.html is: {% load i18n %} {% block extrahead %} <style type="text/css"> .chart_title { font-weight: bold; font-size: 14px; } </style> {% endblock %} {% block content %} <div id="content-main"> <div class="chart_title"> {% trans "Custom Bar Chart" %} </div> {{ figure|safe }} </div> {% endblock %} The code is executed right and the plot is displayed correctly but after a couple of seconds the app terminates with the following error: Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1561.20.106/AppKit.subproj/NSView.m, line 14480. I found out that if I comment all the code this exception is thrown when any of the matplotlib libraries are called. Does anyone has a workaround or solution for this problem? -
How to test form submission of image in django
I have a file django view that takes a form request with an image as the submitted content and then returns an httpresponse of the image to be displayed back in the template. I'm new to testing in django and I'm trying to essentially assert that the file that was originally uploaded in the form request is the same one that is being returned back to the user. Here is the code in the view that handles the http request and returns the response: form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): print request instance = form.save(commit=False) instance.save() instance = PhotoUploader.objects.get(id=instance.id) image_full_path = instance.image.path image_data = open(image_full_path, "rb").read() return HttpResponse(image_data, content_type="image/png") I'm following the guide in the django docs for simulating a client request but I'm not clear on how to match up the submitted request with the http response. For the test, I have the code to make the request right now (where I have a test image stored in the static_cdn): with open('../../static_cdn/Keep-Calm-and-Carry-On.jpg', "rb") as fp: form_request = c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp}) form_request = form.save(commit=False) form_request.save() instance = PhotoUploader.objects.get(id=form_request.id) image_full_path = instance.image.path image_data = open(image_full_path, "rb").read() #assert HttpResponse = …