Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add myself's logic when I access the `ListAPIView`?
I use the BannerListAPIView when access the banner list: class BannerListAPIView(ListAPIView): serializer_class = WebsiteBannerSerializer permission_classes = [] queryset = WebsiteBanner.objects.all() But I want to add my logic when access this ListAPIView, such as I want to record the remote_ip. How to add myself's logic when I access this ListAPIView? -
Django nested serializers update
I have two models in my models.py: class City(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=28) class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) Since I only want to get the name of the city if i fetch a Person from the API, i implemented it like this in the serializer: class PersonSerialzer(serializers.ModelSerializer): city = serializers.SerializerMethodField('_city') class Meta: model = Person fields = ('username', 'city') def _city(self, obj): return obj.city.name I have an endpoint to update the instance which is an generics.UpdateAPIView class, but when I send the following response it cannot update the city: { "city": "Hamburg" } I think I need to create a CitySerializer and nest it into the PersonSerializer instead of the SerializerMethodField and implement a custom update method in the CitySerializer. But is it possible to nest the serializer but only print out the name string instead of an object containing that string in the API? -
Django stops recieving/sending MQTT messages after 500 error
I am trying to implement Paho MQTT on Django but Django stops receiving/sending MQTT messages after a 500 error. I am using Paho MQTT client 1.3.0 along with Django 1.10.8, Python 3.6.2 Here are my MQTT settings: mqtt.py from django.conf import settings import paho.mqtt.client as mqtt SUB_TOPICS = ("device/vlt", "device/auth", "device/cfg", "device/hlt", "device/etracker", "device/pi") RECONNECT_DELAY_SECS = 2 # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. for topic in SUB_TOPICS: client.subscribe(topic, qos=0) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) def on_publish(mosq, obj, mid): print("mid: " + str(mid)) def on_subscribe(mosq, obj, mid, granted_qos): print("Subscribed: " + str(mid) + " " + str(granted_qos)) def on_log(mosq, obj, level, string): print(string) def on_disconnect(client, userdata, rc): client.loop_stop(force=False) if rc != 0: print("Unexpected disconnection: rc:" + str(rc)) else: print("Disconnected: rc:" + str(rc)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish client.on_subscribe = on_subscribe client.on_disconnect = … -
Fix a user to its specific blog when logged in
Here is my view for blog_create. I want to fix this for a specific user when he/she is logged in. @login_required def blog_create(request,blogger_id): blog=Blog.objects.all() user=get_object_or_404(User,pk=blogger_id) form=BlogForm(request.POST) if request.method=="GET": return render(request,'winterblog/blog_create.html',{'form':form}) if request.method=="POST": if form.is_valid(): blog=form.save(commit=False) blog.save() return redirect('winterblog:blog_list') else: form=BlogForm() return redirect('winterblog:blog_create') And for the form is: class BlogForm(ModelForm): class Meta: model=Blog fields=['headline','blog_text','user'] Thanks! -
create multiple same html page in django
I am new to Django and I am going to create a website with multiple same html pages. I got a text file which contains the number of how many same html pages is going to create. And the following one is the view.py. And the t=a.split()[7] get the number of pages needed to be created def bb(request): form=BBForm(request.POSt or None) if(form.is_valid()): my_file=open("./input_data.txt",'r') a=my_file.read(); my_file.close(); t=a.split()[7] form.save() context={"form":form} return render(request,'bb/bb.html',context) And the bb.html is like the following: <form method='POST' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit /> </form> If I only use those code, I can generate the website with the form.However, it only appears once. What can I do if I want to create multiple same forms within one html page or multiple html page with the same html code -
MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform
i downloaded MySQL_python-1.2.5-cp27-none-win_amd64.whl to help with connection between mysql and django. But there is an error : MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform. what should i do now ? -
Reorder app and models in Django admin
I want to reorder my apps in my Django admin panel, I saw some responses from another similar question here in SO, so I go for install this method: django-modeladmin-reorder I follow all the steps and it's not working. Here's my actual Django panel #settings.py MIDDLEWARE_CLASSES = ( 'admin_reorder.middleware.ModelAdminReorder', ) ADMIN_REORDER = ( # Keep original label and models 'organization_owners', 'panel', 'clients', ) and also is in my requirements.txt Django==2.0.1 django-extensions==1.9.8 django-modeladmin-reorder==0.2 djangorestframework==3.7.7 flake8==3.5.0 -
Django ORM calculations between records
Is it possible to perform calculations between records in a Django query? I know how to perform calculations across records (e.g. data_a + data_b). Is there way to perform say the percent change between data_a row 0 and row 4 (i.e. 09-30-17 and 09-30-16)? +-----------+--------+--------+ | date | data_a | data_b | +-----------+--------+--------+ | 09-30-17 | 100 | 200 | | 06-30-17 | 95 | 220 | | 03-31-17 | 85 | 205 | | 12-31-16 | 80 | 215 | | 09-30-16 | 75 | 195 | +-----------+--------+--------+ I am currently using Pandas to perform these type of calculations, but would like eliminate this additional step if possible. -
Django ModelForm not displaying all fields
I'm trying to build forms linked to a PostgreSQL database using Django ModelForms. The template is rendering two of the fields(the ones with ManyToMany relationships), but it only gives me an empty box for "title". This is my forms.py: Forms.py: class ProgramForm(forms.ModelForm): class Meta: model = Program fields = ['function','task', 'title'] widgets = { 'function' : forms.Select, 'task' : forms.Select, 'title' : forms.Select, } This is my Models.py: class Program(models.Model): title = models.CharField(max_length=255) function = models.ManyToManyField(function, related_name='programs') task = models.ManyToManyField(Task, related_name='programs') def __unicode__(self): return self.title class Task(models.Model): tasknum = models.CharField(max_length=20) taskname = models.CharField(max_length=100) task_num_name = models.CharField(max_length=100) function = models.ForeignKey(Function, related_name="tasks") def __unicode__(self): return self.task_num_name class Function(models.Model): function = models.CharField(max_length=50) function_abrev = models.CharField(max_length = 25) def __unicode__(self): return self.function Views.py: def main(request): return render (request, 'assignments/main.html') def add_program(request): form = ProgramForm() return render (request, 'assignments/ad_form.html', {"form":form}) def link(request): if request.method == 'POST': form = ProgramForm(request.POST) if form.is_valid(): return HttpResponse("we maybe getting somewhere") else: return HttpResponse("keep working") I need a couple of things to happen: I need for the "title" to render in the html page as a scroll down(the same way "function" and "task" appear. I need to be able to save the relationships. The models are populated with all the … -
How to test redirection in Django using pytest?
I already know that one can implement a class that inherits from SimpleTestCase, and one can test redirection by: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True) However, I am wondering what is the way I can check for redirection using pytest: @pytest.mark.django_db def test_redirection_to_home_when_group_does_not_exist(create_social_user): """Some docstring defining what the test is checking.""" c = Client() c.login(username='TEST_USERNAME', password='TEST_PASSWORD') response = c.get(reverse('pledges:home_group', kwargs={'group_id': 100}), follow=True) SimpleTestCase.assertRedirects(response, reverse('pledges:home')) However, I am getting the following error: SimpleTestCase.assertRedirects(response, reverse('pledges:home')) E TypeError: assertRedirects() missing 1 required positional argument: 'expected_url' Is there any way I can use pytest to verify redirection with Django? Or I should go the way using a class that inherits from SimpleTestCase? -
Django http request to api error
As this is the first time i'm trying this out, i do not know what is wrong with the problem. So it would be great if someone can help me solve this problem The code im using is at the bottom page from this website: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html Where it give example on how you can make http request function and retrieve data base on your query. The code in the website is this. query.py import requests import json BASE_URL = 'http://pokeapi.co' def query_pokeapi(resource_url): url = '{0}{1}'.format(BASE_URL, resource_url) response = requests.get(url) if response.status_code == 200: return json.loads(response.text) return None charizard = query_pokeapi('/api/v1/pokemon/charizard/') sprite_uri = charizard['sprites'][0]['resource_uri'] description_uri = charizard['descriptions'][0]['resource_uri'] sprite = query_pokeapi(sprite_uri) description = query_pokeapi(description_uri) print charizard['name'] print description['description'] print BASE_URL + sprite['image'] In my edit, i only change these print line at the bottom to this query.py print(charizard['name']) print(description['description']) print(BASE_URL + sprite['image']) But i got this error instead Traceback (most recent call last): File "query2.py", line 46, in sprite_uri = charizard['sprites'][0]['resource_uri'] TypeError: 'NoneType' object is not subscriptable -
Why does Django trigger GET after POST?
I have the following view which takes either a URL or an uploaded text file, creates a Word Cloud and finally displays the generated image to the user. def create(request): """ Displays the generated WordCloud from the given URI or uploaded file """ response = HttpResponse(content_type="image/png") # in order to avoid KeyError myfile = request.FILES.get('myfile', None) if request.POST['uri'] == '' and myfile is None: return render(request, 'nube/index.html', { 'error_message': NOTHING_TO_PROCESS }) try: if myfile: cloud = WordCloud(myfile, type="upload") else: cloud = WordCloud(request.POST['uri'], type="internet") except (MissingSchema): return render(request, 'nube/index.html', { 'error_message': URI_COULD_NOT_BE_PROCESSED }) else: img = cloud.get_word_cloud_as_image() img.save(response, 'PNG') return response The image is displayed with no problems; the POST request is processed properly, as can be seen from the log: [16/Jan/2018 22:53:25] "POST /nube/create HTTP/1.1" 200 216961 However, even though the server didn't crash, I noticed an Exception was raised everytime inmediately after: Internal Server Error: /nube/create Traceback (most recent call last): File "C:\repos\phuyu\venv\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__ list_ = super().__getitem__(key) KeyError: 'uri' After debugging the code I noticed that my create view was being called once again, but this time as a GET request, and of course, the parameters uri and myfile didn't exist this time, thus raising the … -
How to transfer data from one database to another in Django?
I am recreating a web app in Django that was running in a server but it was terminated, fortunately, I did a backup of all the code. My problem comes with the database because but I do not know how to transfer all the data from the old db.sqlite3 Django database web app into the new one. I found a similar question as mine Django: transfer data from one database to another but the user wanted to transfer data from specific columns because their models.pyfrom the old and new databases were slightly different. In my case, my models.py from the old and new databases are the same. I am using the DB Browser for SQLite to explore the content of the old database and I could add manually each row into the Django administration but this will take me too much time. How should I proceed for transferring data from the old database to the new one? -
Migrate to GeoDjango Points from longitude/latitude?
Using the Django ORM, Postgres/PostGIS, and Django migrations, how do I convert my existing longitude and latitude float fields into a single GeoDjango Point field? I was looking for something like Location.objects.update(point=(F('longitude'), F('latitude'))). -
How to link users from other Django model?
I am trying to link two apps with different databases models. I already routing but when I want to link the users.user models with myapp.UserView gives me this error: Error: Field defines a relation with model 'users.User', which is either not installed, or is abstract. Myapp.model.py class UserView(models.Model): user = models.OneToOneField('users.User', on_delete=models.CASCADE) view_id = models.CharField(max_length=45) view_name = models.CharField(max_length=255) users.model.py from django.contrib.auth.models import User from django.db import models Any clue ? -
Django model function to return an array (model function or manager?)
Say I have a model with many attributes that are somewhat related class ManyFields(models.Model): a = models.CharField(…) b = models.CharField(…) c = models.CharField(…) d = models.CharField(…) … # This works -ish, but am unsure if it is what is convention/needed def many_fields_simple_array(self): return [self.a,self.b,self.c,self.d,] and later in the view, where there isn't much real estate (say mobile), I want to just provide some sort of concatenated version of the fields. Instead of <td>{{many_fields.a}}<td> <td>{{many_fields.b}}</td> <td>{{many_fields.c}}</td> … I would like to just have <td>{{many_fields.many_fields_simple_array()}}<td> and it will look AWESOME :) I think I can handle the rendering of HTML/text, CSS, visual part (kind of going for a red light green light for each field), but I don't know the repercussions of writing a Model function or a Manager. I am unsure after reading the docs/intro. Notes/Assumptions: I come from a JS/Angular world, so I would assume an array would be perfect for what I need, but I think I might be missing something I assume an array, because in the template I could iterate over them quite easily. Open to other suggestions -
Django - postgres: How to create an index on a JsonB field
I want to allow indexing on JsonB field on an ID which is a few levels deep into the json data in our Django project. Here's what the JSONB data looks like: "foreign_data":{ "some_key": val "src_data": { "VEHICLE": { "title": "615", "is_working": true, "upc": "85121212121", "dealer_name": "CryptoDealer", "id": 1222551 } } } I want to index on the field id using Django views but not sure how to achieve that. Happy to post my Django ViewSet if it helps. -
Getting field name by value in Django
I have these lines : my_field = days user_model = User.objects.get(pk=2) I want to do something like this : user_model.my_field += 7 I can do it using update() keyword instead of get() and passing it a kwargs but since i want to get multiple values from the model, after the update() i can't get any value from it, then i have to make another call to database for the same model. correct me if i'm wrong, i'm still trying out django. -
Django view not working for project
Context: I am creating a website to house some webcomics I made as a project to practice Django. I am adapting Django's tutorial to create the site (https://docs.djangoproject.com/en/2.0/intro/tutorial03/ About halfway down the page under "Write views that actually do something"). I am having some difficulty getting part of my view to work as expected. Expectation: What I see when I go to http://127.0.0.1:8000/futureFleet/ : latest_comic What I want to see: A dictionary of my 2 comics. Question: I think I am doing something wrong at this line context = {'latest_comic': latest_comic}. I am adapting this line from the tutorial. I think the line needs to be run to connect to the template. What do I do? What am I missing? Models.py class Comic(models.Model): #title comic_title_text = models.CharField(max_length=200) #date comic_pub_date = models.DateTimeField('comic date published') #image comic_location = models.CharField(max_length=200) #explanation comic_explanation_text = models.CharField(max_length=400, blank=True) def __str__(self): return self.comic_title_text def was_published_recently(self): return self.comic_pub_date >= timezone.now() - datetime.timedelta(days=1) views.py def index(request): latest_comic = Comic.objects.order_by('-comic_pub_date')[:2] context = {'latest_comic': latest_comic} return HttpResponse(context) # return render(request, 'futureFleet/index.html', context) This sends to the template but doesn’t work at the moment Database "Welcome Aboard" "2018-01-15 21:02:54" "/home/user/Desktop/django/djangoFutureFleet/mysite/futureFleet/static/futureFleet/images/1.JPG" "this is the first comic" "Space Vaccine" "2018-01-15 23:02:22" "/home/user/Desktop/django/djangoFutureFleet/mysite/futureFleet/static/futureFleet/images/2.JPG" "This is … -
Cannot save an image to database using django
I project is supposed to be able to upload an image with a name then display the uploaded image and name. I have tried looking online for an answer to my problem but have found none. The problem basically is my django webapp is not saving a name(CharField)an and image(ImageField) to the database. I tried to do everything necessary for it to work but it's still not working. The following is my project. Thanks for your time. My projectl directories: Image shows project structure views.py from django.shortcuts import render from ImgApp.forms import ImageForm from ImgApp.models import ImageModel from django.http import HttpResponseRedirect def upload(request): if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('ImgApp:home') else: form = ImageForm() con = {"var_form": form} return render(request, 'upload.html', con) models.py from django.db import models class ImageModel(models.Model): name = models.CharField(max_length=44) image = models.ImageField(upload_to='media/',null=True) def __str__(self): return self.name forms.py from django import forms from ImgApp.models import ImageModel class ImageForm(forms.ModelForm): class Meta: model = ImageModel fields = "__all__" settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
Django unittest with not raising exception as expected with assertRaises()
I'm writing a unittest class to ensure a method tests for a success, and then tests for an Exception. I'm passing a response that should trigger the exception, but in the testing method it does not get raised. Of note, I can manually make the exception raise in the actual method. Test class: class TestAPI(TestCase): def test_send_method(self): with mock.patch('requests.post') as mock_request: mock_response = mock.Mock() mock_response.json.return_value = { "success": "true" } mock_request.return_value = mock_response test_send_method() // THIS WORKS NICELY # Test that errors from the API are handled correctly. with self.assertRaises(SendException): mock_response.status_code = 500 mock_response.json.return_value = { 'errors': 'An error has occurred.', } test_send_method() // THIS RAISES NO EXCEPTION As I said, It's odd because I can manually trigger the 500 status code in the actual method and it raises fine. I can even change the initial mock response success to err and it will raise in the actual method. Why would it not raise in the unittest? -
Django REST Framework form data no submit with x-www-form-urlencoded
I am trying to post data using postman with x-www-form-urlencoded. When I send request an eroor is occuring saying- { "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter." } post data is contained {'name': 'hello'} this is my view: serializer = Web2TypeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) NOTE: Post data not containg any file. -
Django Custom Field that creates a new table
I have been noticing that I keep creating duplicated models that look exactly like this: class Environment(m.Model): slug = m.SlugField(primary_key=True) name = m.CharField(max_length=32) class Session(m.Model): environment = m.ForeignKey(Environment, on_delete=m.PROTECT) They have a slug as a primary key and a char field and they are referenced from the other model with a foreignKey. Would it be possible to create a custom field that automatically creates the new table with those 2 columns and sets a foreign key to it? Sort of like: class Session(m.Model): environment = m.SlugForeignKey() I have been looking through the docs but all the custom fields I have seen talk about storing things in a column as oppose to a different table. Any ideas how to do this? -
possible to bulk save query in django?
I am just wondering if it's possible to bulk save queries in django. for example, usually I would have to loop through each object for obj in queryset: if condition: obj.field = True obj.save() would there be a faster way to do this? Thanks in advance for any advices -
how to query this model by user
I'm struggling getting this view to work. In the code I have included a comment that indicated where the issue is. Basically I can not for the life of me get the TeamsWeeklyMasterSchedule object that relates to the EmployeeProfile.team Models class Team(models.Model): name = models.CharField(max_length=10) def __str__(self): """Return a string representation of the model.""" return self.name class TeamsWeeklyMasterSchedule(models.Model): """Hours Available For That Day""" team = models.ForeignKey(Team, on_delete=models.CASCADE) class EmloyeeProfile(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, ) team = models.ForeignKey(Team, on_delete=models.CASCADE,) View @login_required def employee(request): """The home page""" profile = EmployeeProfile.objects.filter(owner=request.user) # I Cannot make this get() work! teams_weekly_master_schedule = TeamsWeeklyMasterSchedule.objects.get() context = { 'profile': profile, 'teams_weekly_master_schedule': teams_weekly_master_schedule, } return render(request, 'portal/employee.html', context) What I've Tried teams_weekly_master_schedule = TeamsWeeklyMasterSchedule.objects.get(team=profile.team) teams_weekly_master_schedule = TeamsWeeklyMasterSchedule.objects.get(team=request.user.team)