Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Can I rely on self.request in django class-based views?
I see code all the time that relies on using an instance variable to get the request, like: class MyView(): def get(self, request): return foo() def foo(): request = self.request return bar(request) My question is, can I rely on self.request being set for every view instance? I can't find anything in the documentation that even references this attribute, and while I see it being set in some places in the source I can't tell if it is always being set. -
Django: which plot library is needed to build website like quantopian?
I'd like to build web plot-application, something like Quatopian, which uses a lot of interactive plots. After I searched in Google for making easy to introduce plot in django, I found out some options: django-chartit bokeh (Not sure whether this library can be used smoothly with django... Do I have to use django-rest-framework?) plotly (Not sure whether this library can be used smoothly with django... Do I have to use django-rest-framework?) django-rest-framework and D3.js(or other plot js lib) Which one is the most suitable one and following modern trend? I'd like to choose the one which is easy to implement, too. Thanks -
Running Django on a Linux Server using Apache with HTTPS
I've been trying to figure this out for a while now and nothing I've found has really been helping. I've got a remote Linux server running with Apache installed, and right now everything going to the server is redirected to HTTPS through Apache. This all works fine and I can access the files I need to normally, but now I'd like to also add in a Django site to my server under a new "subdomain". (For example I'd like to still be able to access non-Django files as usual 'https://www.thesite.com/path/to/file.php' and also be able to access the Django site like 'https://www.thesite.com/djangosite/some/site/page') Could someone please give me some direction as to how I'd be able to do this? I can supply more information if it's needed. Thanks in advance! -
Django - hashtag links on all templates
I want to have whenever someone writes "#id_of_model" automatically the link to the model. The idea behind is I have a chat where people are discussing stuff and to make communication easier, I would like to provide more user friendly links. My first idea was that I would check every sent message - which is stored in an model - if it contains a #id_of_model, then convert it to an link and finally save it. Does anyone know an easier solution? -
Django: from implicit through model to ManyToManyField field that created it
Given the following models and instances (as an example, the involved models vary dynamically) class Foo(models.Model): # ... class Bar(models.Model): foos = models.ManyToManyField(Foo, related_name='bars') foo = Foo.objects.create() bar = Bar.objects.create() and one of these cases (examples again, could be any of add, remove, clear) bar.foos.add(foo) # case 1 foo.bars.add(bar) # case 2 I am handling the respective m2m_changed signal where I want to access the ManyToManyField underlying the relation: Bar.foos. Sounds simple enough, or so I thought. The signal kwargs give me access to: sender: Bar_foos # The implicitly created through model instance: 1. bar, 2. foo # instance being modified reverse: 1. False, 2. True # indicating direction wrt to original field model: 1. Foo, 2. Bar # model of instances being added The only two ways I could come up with in order to get to the original field were: src_model = model if reverse else instance.__class__ # 1 field_name = sender._meta.model_name[len(src_model._meta.model_name) + 1:] field = src_model._meta.get_field(field_name) # 2 field = next(f for f in src_model._meta.many_to_many if sender == f.remote_field.through) Both approaches are highly unsatisfying! On the one hand, relying on the naming convention of the auto-created through model seems bound to break and is downright ugly. On … -
Should I use django admin panel for regular users?
I am currently trying to make a learning app. The three main users would be the Admin, Teacher and Student. Should I use the django admin panel for the teachers ? It has a lot of features and is fully customizable and I can choose what a teacher can do or not from there. Is this a correct approach ? -
Celery logger configuration
I'm using Django 1.10, python 3.5 and celery 4.1.0 I'm trying to log celery tasks info into a file. So I tried as suggested in celery documentation - from celery.utils.log import get_task_logger logger = get_task_logger(__name__) and tried to log a message inside the task - logger.info(message) I expected it to log to my default logger. But it didn't. So I added to settings a dedicated logger named 'celery.task' (as I understand from documentation): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_test_false': { '()': 'myapp.utils.classes.logging.RequireTestFalse', }, 'suppress_deprecated': { '()': 'myapp.utils.classes.logging.SuppressDeprecated' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'json', 'filters': ['suppress_deprecated'] }, 'celery_file': { 'level': 'INFO', 'class': 'myapp.utils.classes.logging.SBRotatingFileHandler', 'maxBytes': 1024 * 1024 * 200, # 200 MB 'backupCount': 10, 'formatter': 'json', 'filename': BASE_DIR + '/../log/celery.log', } }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': LOG_LEVEL, 'propagate': True, }, 'celery.task': { 'handlers': ['console', 'celery_file'], 'level': 'INFO', 'propagate': True, }, } But I still don't see logs from celery task not in the celery.log file nor in the default log file. Only when starting celery worker with '-f' - it writes logs to that file Any ideas? -
Django runserver getting [Error 126] The specified module could not be found
I can't seem to figure out what the missing module actually IS though. Here is the error that prints to the console: Unhandled exception in thread started by <function wrapper at 0x04EF32B0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\users\username\desktop\sandbox-code\company\more_company\community\models.py", line 5, in <module> from django.contrib.gis.geos import Point File "C:\Python27\lib\site-packages\django\contrib\gis\geos\__init__.py", line 18, in <module> HAS_GEOS = geos_version_info()['version'] >= '3.3.0' File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 188, in geos_version_info ver = geos_version().decode() File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 156, in __call__ self.func = self.get_func(*self.args, **self.kwargs) File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 161, in get_func func = GEOSFunc(self.func_name) File "C:\Python27\lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 39, in __init__ self.cfunc = getattr(lgeos, func_name + '_r') File "C:\Python27\lib\site-packages\django\utils\functional.py", line 234, in inner self._setup() File "C:\Python27\lib\site-packages\django\utils\functional.py", line 380, in _setup self._wrapped = self._setupfunc() File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 63, in load_geos _lgeos = CDLL(lib_path) File "C:\Python27\lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could … -
ManyToManyField with extra information
I'm working on a django website and I need to store some information about the user like a isVerified BooleanField and a profile picture in an ImageField as well as ratings which stores ratings a user has given different elements. So I made a model like this: class UserProfile(AbstractBaseUser): is_verified = models.BooleanField(default=True) current_profile = models.ImageField(default=static('img/default_profile.jpg')) ratings = models.ManyToManyField(Element, on_delete=models.CASCADE) however I'd like to save some more about these ratings (like a timestamp and the actual value the user rated) Do I need to make a seperate model just for that or can this be acchieved in a better way? -
Django user authentication working properly EXCEPT 1 view/template
I am working with Django 1.11.5 and logging-in and validating users via Social Auth. The user authentication, log-in and logoff are working as expected in 12/13 of my templates. All my templates extend my navbar and footer base.html template. In 'base.html' I have the following code for the navbar: {% if user.is_authenticated %} <li class="nav-item"> <span class="nav-link" id="user-name">{{ request.user.username }}</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Logoff</a> </li> {% else %} <li class="nav-item log-in-link"> <a class="btn btn-primary nav-link log-in" href="{% url 'social:begin' 'google-oauth2' %}"><span>Log-In <i class="fa fa-google-plus" aria-hidden="true"></i></span></a> </li> {% endif %} Now, this navbar code works properly in 12/13 of my templates. It is only for 1 template/view/URL where the user is not authenticated. I have tried debugging by printing out the user name and information in the template giving me errors but it looks like the user is getting logged out when reaching that template via its URL and view. I am totally lost. Could someone point out things I can check/do to debug and locate the source of this logoff error? I can provide the relevant code if needed. -
How to execute a decorator function at startup in a Django/Python Application?
I have a number of classes for which I wish to run a decorator function on. As I am aware decorators only run when the class/function/whatever they label is loaded into the code. e.g. def decorator(cls): print("Decorator executed") return cls @decorator class Example: pass Example() How can I trigger the decorator function on all the classes a decorator labels without having to load each class separately? (or without having knowledge of the classes for which a decorator labels)