Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with ModelSerializer and Post method
I am pretty new to Django and now I am implementing a REST API for a backend server, and having troubles with setting up the POST methods. It all stops when requested json string goes through serialization. Here is a snippet of my code class Sighting (models.Model): userID = models.IntegerField() registeredID = models.IntegerField() cardID = models.IntegerField() class SightingSerializer (serializers.ModelSerializer): class Meta: model = Sighting fields = "__all__" class SightingsList (QGAPIView): def get (self, request, userID, format=None): self.check_user(userID) data = Sighting.objects.filter (userID = userID) if not data: return Response (None) else: serializer = SightingSerializer (data, many=True) return Response (serializer.data) def post (self, request, userID, format=None): self.check_user(userID) self.check_token (request, userID) obj = Sighting.objects.filter (userID = userID) data = self.parse_data (request) print (data) return self.get_serialized_responds (SightingSerializer, obj, data[0], True) And here is the method get_serialized_responds: def get_serialized_responds (self, serializerClass, obj, data, many=False): print ("Serializing") serializer = serializerClass (obj, data, many=many) print (data) if not serializer.is_valid(): print ("I am here") return Response ('Wrong data type', status=406) else: serializer.save() return Response (serializer.data) I am passing the following string '{"Items":[{"userID":0,"registeredID":0,"cardID":0}, {"userID":0,"registeredID":1,"cardID":0}]}' which later is stripped to: [{'registeredID': 0, 'userID': 0, 'cardID': 0}, {'registeredID': 1, 'userID': 0, 'cardID': 0}] And at the end I am getting this β¦ -
install application made in Django
Excuse me how I can create an installer for an application made in Django with PostgreSQL as a database. how to create an .exe or something similar that is easy to install all the dependencies I'm using. -
Model str method based on Foreign key to that model causing error
I have several models for a books library. Each author can have a different position for a book (author, editor) and he can be an author for one book and an editor for another book. Each author can also have several spellings for his name, AuthorName is used for that. Each book can have several authors, AuthorAndPosition stores the authors with their positions. This design fulfills the requirements I need for the library. But because of the ForeignKey relationships it costs a lot to look up the str methods for AuthorMulti and the AuthorAndPosition models. This is causing an error in the Admin when adding a new AuthorMulti instance: "RuntimeError at /admin/myapp/authorandposition/add/ maximum recursion depth exceeded while calling a Python object" It is understandable because it is costing to look up the __str__ method but it is also necessary to see which author object I am choosing in the admin and the only way I see to do that is to show the AuthorName. Any idea how to get around this? These are the models: class AuthorAndPosition(models.Model): position = models.ForeignKey('Position') #author, editor author = models.ForeignKey('AuthorMultiName') def __str__(self): author_name = AuthorName.objects.filter(author=self.author).first() if author_name is not None: return "name: " + author_name.name β¦ -
Get EXIF Data from ImageField Django 2.0
im on this task of extracting the exif data of a photo uploaded through DJANGO 2.1.2, here's my model.py class UploadedImage(models.Model): image = models.ImageField( "Uploaded image", upload_to=scramble_uploaded_filename, height_field='height', width_field='width') uploaded_at = models.DateTimeField(default=timezone.now) width = models.PositiveIntegerField() height = models.PositiveIntegerField() meta = (get_exif(image)) the fuction im using to get the data def get_exif(fn): ret = {} i = Image.open(fn) info = i._getexif() for tag, value in info.items(): decoded = TAGS.get(tag, tag) ret[decoded] = value return ret The error im getting AttributeError: 'ImageField' object has no attribute 'read' Some guidance of how to work with this model would gladly help. -
Django Unable to connect to MS SQL hosted on a remote server
I have a django app thats works correctly when I am connecting it to the local database. But I am not able to connect when I move the same database to a remote server. I am attaching the both the database parts. Please let me know if there is any issue with the setting parameters. Local: 'testdb':{ 'NAME': 'Production', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'PORT': '1433', 'USER': 'test', 'PASSWORD': 'xyz', 'OPTIONS': { 'use_legacy_date_fields': True, 'provider': 'SQLOLEDB' } } Remote: 'testdb':{ 'NAME': 'Production', 'ENGINE': 'sqlserver_ado', 'HOST': '10.120.12.33', 'PORT': '1505', 'USER': 'test', 'PASSWORD': 'xyz', 'OPTIONS': { 'use_legacy_date_fields': True, 'provider': 'SQLOLEDB' } } I have checked the connection and I am able to connect to the database using SSMS with the same port. So I am sure there is no firewall or tcp/ip enabling issue. Any help would be appreciated. -
why domain name will be removed automatically from my django.setting
i use bitnami-django-stack to set up website on google-cloud-platform and have bought a domain name from namesilo. But i can't link domain name to my site. i have added ip and domain name in ALLOWED_HOSTS: ALLOWED_HOSTS=[ip, domain name, www.domain name] LOGIN_URL = '/account/login/' i can login with ip/account/login But if i use domain name/account/login "Invalid HTTP_HOST header" occurs and debug setting shows ALLOWED_HOSTS=[ip] why? domain name and www.domain name disappear ? Please help me fix it. Thanks -
Sending image file via ASJAX. request.FILES is empty?
I am trying to send image data using Ajax. But request.FILES that I get at the backend is empty. I have added multipart/form-data to my form and the method is POST. here is my AJAX call: $(document).on('submit', '#profile_edit_form', function(event){ event.preventDefault(); $.ajax({ url : "/users/update_profile_info/", type : 'post', dataType: 'json', data : $(this).serialize(), success : function(data) { $('#profile_name_tag').html(data.username); $('#username_navbar').html(data.username); //SENDING THE IMAGE VIA AJAX HERE var img_data = $('#id_image').get(0).files; formdata = new FormData(); formdata.append("img_data", img_data); $.ajax({ url : "/users/update_profile_image/", type : 'POST', enctype : "multipart/form-data", data : formdata, cache : false, contentType : false, processData : false, success : function(data) { console.log('success'); //$('#profile_picture').html(data.) }, error: function(data) { console.log('fail'); } }); }, error: function(data) { console.log('fail'); } }); }); and here is my form: <form id="profile_edit_form" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb4"> Profile Info </legend> {{u_form|crispy}} {{p_form|crispy}} </fieldset> <button class="btn btn-outline-info" type="submit"> Update Info </button> </form> I have checked so many similar question. but in all of them the solution was adding multipart/form-data to the form which I have already done. So any ideas where the problem is? thanks! -
Django queryset on model with User as foreign key
My model: class FitDataModel(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) date = models.DateField() steps = models.IntegerField(default=0) distance = models.FloatField(default=0) calories = models.FloatField(default=0) def __str__(self): return f'{self.user} {self.date} {self.steps}' class Meta: ordering = ['-user'] My user model is standart django User model from django.contrib.auth.models. Queryset: FitDataModel.objects \ .filter(date__gt=since_data, user__profile__location=user.profile.location) \ .values('user__username') \ .annotate(Sum('steps')) \ .annotate(Sum('distance')) \ .annotate(Sum('calories')) \ .order_by('-steps__sum') And the result is: { "user__username": "_id.auth_user.username", "steps__sum": 17004, "distance__sum": 9411.850049376488, "calories__sum": 22582.57051609428 } This is data for one user, but the problem is I am expecting real username value under the 'user__username' key, not "_id.auth_user.username". I am using mongodb. What am I doing wrong, how do I extract real username? -
Django per-view cache isn't caching queryset
From the docs, I'm caching my api endpoint. I have it set to 2 minutes, but when I update anything in my admin section the change is reflected immediately. It seems the view cache is not caching my queryset. Is that normal behavior? views.py @cache_page(60 * 2) def get(request): data = [] all_places = Place.objects.all() for item in all_places: current_place = {} current_place['id'] = item.id current_place['name'] = item.name current_place['latitude'] = item.latitude current_place['longitude'] = item.longitude data.append(current_place) return JsonResponse(data,safe=False) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } urls.py urlpatterns = [ path('get/', views.get, name='get'), ] Accessing example.com/get gets me my JSON data. But as I said, updating any Place object has the change immediately visible, without any caching. -
Django w/ Docker, Nginx, Gunicorn and SSL
this may be a duplicate but I didn't find a good answer in previous questions, and I am totally new to sysadmin and Django. Docker, Nginx etc. but am trying to troubleshoot HTTPS deployment w/ Django from this guide here The connection to my server isn't working and visiting my FQDN in a browser times out. Here's my project structure: project_dir βββ assets β βββ imgs βββ auth β βββ apps.py β βββ auth_forms.py β βββ __init__.py β βββ migrations β βββ __pycache__ β βββ urls.py β βββ views.py βββ changelog_6_3_2018.txt βββ changelog.txt βββ sub_app1 β βββ tests.py β βββ urls.py β βββ views.py β βββ wsgi.py βββ docker-compose.yml βββ Dockerfile βββ subapp2 β βββ tests.py β βββ urls.py β βββ views.py β βββ wsgi.py βββ main β βββ admin.py β βββ apps.py β βββ fields.py β βββ forms.py β βββ __init__.py β βββ migrations β βββ models.py β βββ __pycache__ β βββ templatetags β βββ tests.py β βββ urls.py β βββ views.py βββ manage.py βββ nginx β βββ nginx.conf β βββ nginx.dockerfile βββ __pycache__ β βββ wsgi.cpython-36.pyc βββ README.md βββ requirements.txt βββ sheets β βββ LTMonServer.xlsx βββ start.sh βββ static β βββ admin β βββ imgs βββ templates β β¦ -
How to send back an uploaded file through HTTP request in Django?
I am trying to realize the function of uploading the file from the front-end and save in my Django backend. But I got stuck when I tried to retrieve my file from my backend, it literally just gave back the path to the file I saved but I cannot get it by using that path or use HTTP.GET with that URL. model.py class User(models.Model): name = models.CharField(max_length=50) image= models.FileField(upload_to='image/', default=None) intro= models.FileField(upload_to='info/', default=None) view.py class UserViewSet(viewsets.ModelViewSet): serializer_class = LsRequestSerializer queryset = User.objects.all() http_method_names = ['post'] serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User field = '__all__' def create(self, validated_data): newUser = User.objects.create( name = validated_data['name'] image = None intro = None ) try validate_data['image']: newUser.image = validate_data['image'] except: newUser.image = None try validate_data['intro']: newUser.image = validate_data['intro'] except: newUser.intro= None newUser.save() return newUser This is original code which can be used to upload the file successfully, and once I send out the HTTP.POST request, the file will exist under the media folder. However, it seems like because in my MySQL database it only save the path to the file as a string, it cannot be opened. So I tried to open the file and save to my object before return back, β¦ -
Get inputs from user into profile model of Django
I have a registration form which is an extension of UserCreationForm and i have a UserProfileForm . I am rendering both the forms to the same html during user registration. The problem is , inputs are getting saved to the inbuilt users model but not to the Profile Model. No data is showing up in Profile Model . I have tried many ways and looked for many solution but unable to find the mistake, need help urgently. My forms.py looks like this - class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) username = forms.CharField(required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2' ] def save(self,commit): user = super(RegistrationForm,self).save(commit=False) if commit: user.save() return user class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ['user'] def save(self,commit): user = super(RegistrationForm,self).save(commit=False) USN =self.cleaned_data['USN'] year = self.cleaned_data['year'] sem = super(RegistrationForm,self).save(commit=False) if commit: user.save() return user Have created UserProfile model in models.py class UserProfile(models.Model): alphanumeric = RegexValidator(r'^[0-9A-Z]*$', 'Only alphanumeric characters are allowed.') user = models.OneToOneField(User, related_name = 'profile',on_delete=models.CASCADE) USN = models.CharField(max_length=50, blank=True, null=True, validators= [alphanumeric]) year = models.IntegerField(default=0) sem = models.IntegerField(default=0) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: objects=models.Manager() user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender = β¦ -
Django And Aframe - OBJ, MTL files not being rendered in the AFrame scene
I am building an application wherein the django and Aframe frameworks are being used. The idea is to a load an apple object (.obj and .mtl file included) when I traverse to a new page. The problem is that I Django gives me the following warning : Not Found: /education/Apple.mtl. I have placed the object in the same folder as that of the html page I want to load. The problem is that although the enitre html file is running properly, the obj files does not seem to load when I run them in Django but they normally run when Just ran through running on the web browser. So the main question is: Does Django support rendering of obj files and if they do then what exactly is the problem? Please help. Thanks in advance. Here is a screenshot and the code. The file directory structure and the error in the console <html> <head> <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script> </head> <body> <a-scene> <a-entity obj-model="obj: apple.obj; mtl: apple.mtl; scale: 0.1 0.1 0.1; position: 0 5 -2" ></a-entity> <a-entity position="0 70 150"> <a-camera></a-camera> <a-entity> </a-scene> </body> </html> -
How to use UNION in Django + add fake columns
I am trying to convert the following query in django ORM: SELECT MONTH(date) AS Month, col1, col2, col3 col3, SUM(col4) col4, SUM(col5) col5 FROM table1 WHERE date BETWEEN '2018-07-19' AND '2018-10-17' GROUP BY 1 , 2 , 3 , 4 UNION ALL SELECT MONTH(date) AS Month, col1, col2, 0 col3, SUM(col4) col4, 0 col5 FROM table2 WHERE date BETWEEN '2018-07-19' AND '2018-10-17' GROUP BY 1 , 2 , 3 , 4 in MySQL Workbench that works good. But in django I see errors - I cannot do this like this: result2 = table2.objects.\ filter( date__range=( self.data['start_date'], self.data['end_date'] ) ).\ annotate(month=TruncMonth('date')).\ values("month", "col1", "col2", "0").\ annotate( col4=Sum('col4'), col5=Sum(0)) Because "Cannot resolve keyword '0' into field." Do you have any ideas for this one ?would like to create 2 the same objects and then use union() to merge tables I am using django 1.11 -
Memcached with large objects (NetworkX graphs)
I have a NetworkX graph (g) with ~ 25k nodes and 125k edges. I want to cache g using memcached but g is too big. The most I am able to increase the memcached limit per item is to 32MB which doesn't do it. Should I even try and get this to work with memcached? What are my other options, if I want to be able to store a networkx graph that could have upto 1m nodes and 10m edges? How might I chunk the graph to make it smaller without (a) knowing anything about the graph, and (b) in a way that causes minima performance degradation putting the chunks back together. I'm working with python. Sample code to create the graph is attached. import sys import pickle import random import networkx as nx from django.core.cache import cache class Qux(object): def __init__(self, foo, bar): self.foo = foo self.bar = bar for n, v in {1: 500, 2: 5000, 3: 50000}.items(): g = nx.Graph() nodes = [Qux(randstring(), randstring()) for _ in range(v)] g.add_nodes_from(nodes) for node in g.nodes: g.add_edges_from([(node, random.choice(nodes)) for _ in range(random.randrange(25))]) print len(g.nodes)), sys.getsizeof(pickle.dumps(g))) cache.set('{}/graph'.format(n), g, 3600) -
CSRF token is not being verified
I have a form: <form action="{% url "some_url" %}" method="post"> {% csrf_token %} <input type="text">Text Input <button type="submit">Submit</button> </form> Which is being submitted via AJAX: $(function () { $('form').submit(function (e) { e.preventDefault(); $.post($(this).attr('action'), $(this).serialize(), function (response) { console.log(response); }); }); }); The URL routes to this view: class SomeView(View): def post(self, request, *args, **kwargs): context = dict(**some_data) rendered_html = render_to_string('some_template.html', context, RequestContext(self.request)) return JsonResponse(dict(html=rendered_html)) All this works. The problem is that it also works when the CSRF token is not sent: $.post($(this).attr('action'), function (response) { console.log(response); }); I would expect some kind of error to be raised because the CSRF token is missing. What can I do to enforce its verification? -
Field value not changing on logout although user_logged_out signal is received
I am making a Django app for listing all active (logged in) users. For each user, I am trying to maintain a field which stores whether the user is logged in or not. When a user logs in, the field value does change to True but on logging out it doesn't change to False. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isAvailable= models.BooleanField(default= False) @receiver(user_logged_in, sender=User) def on_login(sender, request, user, **kwargs): user.profile.isAvailable=True @receiver(user_logged_out, sender=User) def on_logout(sender, request, user, **kwargs): if user.is_authenticated: print(user.profile.id,"is logged in") user.profile.isAvailable=False print("Logout Successful") The following lines do give the desired output (eg. '2 is logged in', 'Logout Successful') if user.is_authenticated: print(user.profile.id,"is logged in") print("Logout Successful") -
FileNotFoundError: [Errno 2] No such file or directory: '/home/ubicomp/ubicomp/questions_check'. (Put files in SFTP server. )
I am trying to put files in sftp server using the following code. I am using ubuntu 16.04. import pysftp as sftp def sftp_file_transfer(): s = sftp.Connection('ip_address', username='username', password='password') remote_path = '/var/sftp/uploads/' local_path = '/home/ubicomp/ubicomp/questions_check.csv' s.put(local_path, remote_path) s.close() I have varied the path which exists. But I am getting the error. And I can not find the problem. Traceback (most recent call last): File "/home/ubicomp/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ubicomp/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubicomp/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubicomp/ubicomp/import_files/views.py", line 34, in sftp_file_transfer s.put(local_path, remote_path) File "/home/ubicomp/lib/python3.5/site-packages/pysftp/__init__.py", line 364, in put confirm=confirm) File "/home/ubicomp/lib/python3.5/site-packages/paramiko/sftp_client.py", line 757, in put file_size = os.stat(localpath).st_size FileNotFoundError: [Errno 2] No such file or directory: '/home/ubicomp/ubicomp/questions_check' -
How do I have users per domain name in Django?
I'm building an application using Django in which each customer will have their own domain name (subdomain in our domain, such as customer.example.com or their own domain, such as customer.com). Ignoring the problem of web server configuration, SSL (that'll be fun, thank god for Let's Encrypt), etc, in Django, how can I have users per domain? The customers would be one type of user and the customer's users would be a different type. The same username should be useable in each of the served domains. Is there anything prebuilt that can help? If not, how do I modify the way auth happens in Django to limit it to the current domain. -
Assertions during Django test case setUps
I'm just learning the approaches for testing in Django using the built-in testing tools, particularly the django.test.TestCase. I'm wondering if it is best-practice to use assertion methods during the initial setUp of a new test class? For example, I have the following models: class TestProduct(BaseModel): name = models.CharField(...) class TestPrimaryImage(BaseModel): url = models.TextField(...) product = models.ForeignKey('TestProduct', ...) It's a product that will have a primary image specified by a ForeignKey relationship with a TestPrimaryImage class entry. Following the examples here: https://docs.djangoproject.com/en/2.1/topics/testing/overview/ I am creating a testing class as such: class NewProductTestCase(TestCase): def setUp(self): models.TestProduct.objects.create( name='TestProductName' ) def TestMainImage(self): models.TestPrimaryImage.objects.create( url="https://example.com/test-image-url.jpg", product=? ) The part that I'm not sure of centers about the TestMainImage method which requires a TestProduct class to reference. Is it appropriate to do the following during setUp: def setUp(self): self.test_product = models.TestProduct.objects.create( name='TestProductName' ) self.assertIsInstance(self.test_product, models.TestProduct) Assigning the newly created object to a class variable and asserting its creation? The assertion would imply that if the new product isn't successfully created none of the other testing methods would be able to run at all. For example, TestMainImage would have no product to create a reference to during creation. This seems like a sensible approach to me but β¦ -
Hostgator VPS, centOS 6, installing pip for django 3.7
Hey i have a hostgator vps with centOS 6, it comes with python 2.x preinstalled. I installed python 3.7 in /usr/src/Python-3.7.0, but now how can i install pip for the python 3.7 ?? I installed the epel things sudo yum install python37-pip and so many more i cant even remember is there and easy way to add pip(pip3) to my python3.7 thanks -
loading (possibly) vary large result sets in django
i am developing an application in Django for learning vocabulary in foreign languages. i have a use case in which the user asks for a word as next question, which is expected to happen iteratively, 2-4 times per minute per user. i have a fairly complex filtering i need to do for each word selection/iteration. it would be much simpler if could load all candidate words, and do the filtering on the server programmatically, as opposed to doing the filtering in the query, but i am not sure it would be reasonable to load that much data. each round i have a few thousands candidate word, each one is related to up to 100 records of guessing history for given word and user. each word is just a short text (200 bytes) and a couple of numeric fields. the text can actually be ignored at the selection, but i am not sure django will query only the fields that are needed. so in summary, if i am doing it this way, i will need in each iteration to load thousands of words, each of which joined with up to 100 history records. so overall, magnitude of hundred-thousands records, each of β¦ -
javascript django JSON response
I have a JSON response from a django view that either returns valid geoJSON for web mapping or returns this {"json": 0}. the code below handles both the valid geoJSON and also strangely the {"json": 0}' var intersection= new L.GeoJSON.AJAX("http://127.0.0.1:8000/intersection_data/",{ style: color(intersection,"purple"), onEachFeature: function(feature,layer){ layer.bindPopup("Intersection") } }); intersection.addTo(map); it throws no error. so what I need is a way to not add the empty JSON to the map -
zip choices of formfield with other data
I have a table where I would like to show some data in first two columns, and a radio choice in the last one so that a user can choose one of the rows. I can loop through the choices of a field with radio select widget like that: {% for choice in form.user_choice %} <td>{{ choice }}</td> {% endfor %} But how can I get the choices as a set of inputs in get_context_data of a django view so that I can zip them with some other data. If I do something like that: frm = self.get_form() return {'data':zip(SomeDataListHere, frm.fields['user_choice'].choices)} it returns my SomeDataListHere zipped with the list of tuples (which are choices initially). So I definitely miss something here. What am I doing wrong? -
Django Allauth and G suite, how to handle multiple domains?
We are currently working on a Django CRUB style webapp where multiple 'tenants' each have their own 'members' (users linked to that tenant), 'Courses', etc. We want to include a 'login with google' option and have thus turned to Django-allauth. Most Tenants use Google G suit with their own [name]@[tenant].com address. A user is assigned to their tenant after their account has been created, to prevent users of tenant B from creating a account in tenant A, we've included a function that checks if the domain of the email matches the 'domain' field in the Tenant object. Only if this match does indeed occur is the account created. However recently one of our tenants has begun using more than 1 email domain which required us to update the code and Tenant Object. (Making the code handle multiple email domains, chancing the models so tenants can have multiple email domains) This left us to wonder if there is a better way to do this - we've been investigating if Google provides a company_id response, or anything that would help us identify a company aside from their email domain. Those values could help us check if a users does indeed belong to β¦