Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i create the same app multiple times in django?
I've created a fully functioning blog application in django . But i want to create multiple blogs like i can create multiple posts on blog. How to approach this problem? -
How can i patch Session().get
I currently have a program that has a function like this. def requester( url ): session = requests.Session() retries = Retry( total=3 backoff_factor=1 status_forcelist=[500] ) adapter = HTTPAdapter(max_retries=retries) session.mount = ('https', adapter) session.get(url) I'd like to patch the session.get in order to test out that it actually retries if the url returns a 500 or something of the sort. -
How to use apache mod wsgi for a django project
If i have a python django project running on my local server and in production i am using heroku to deploy my project so where can i use apache in all that. I am very new to all this. I am just i learning phase can any one help me here! -
Django Rest Framework - How to save using id and retrieve other columns as well?
This question is a continuation of other question from this link here(Django Rest Framework how to save a model with Related Field based on ID) My situation got solved when I used PrimaryKeyRelatedField() to store data using id on a POST request. This, in turn, created another issue. I was using the same API's GET option to list all the columns from the related (Foreign Key referred)model, after using PrimaryKeyRelatedField() the other columns got disappeared and ID is only showing up. Need help on this. To be more clear need ID column of the referred table during POST call and need other columns of the model/table during GET call. PS: I have used serializers.ModelSerializer method -
How to save HTML5 geolocation data to python Django admin?
Is it possible to save the javascript html5 geolocation latitude and longitude to the django admin when user uses the geolocation website. The web page goal is to save the user's longitude and latitude values so that the data can be accessed later on when user signs in again. I found a similar question being asked in stackoverflow years ago but there hasn't been any answer. The link is : Save JavaScript GeoLocation data to Django admin page It would be great if there this an answer based on this code link. Another option I read about is to create a html form and set the form to be autopopulated by jQuery from data produced by the javascript html5 geolocation. Again this is quite complicated for a beginner like me. I would appreciate any bit of help whether by code, tutorial, blog post, examples or links. I don't expect all the programming code to be provided (although I do learn better from examples) but it would help if there are some material/example I could go to, to implement my programming tasks. Thank you. -
placeholder attribute is invalid when check it in browser
I assign values to placeholder within every tag like: <div class="form-group"> <label for="firstname" class="col-sm-1 control-label">FirstName</label> <div class="col-sm-11"> <input type="text" class="form-control" id="firstname" value= {{ form.first_name.value }} name="first_name" placeholder="first_name"> </div> </div> <div class="form-group"> <label for="lastname" class="col-sm-1 control-label">Lastname</label> <div class="col-sm-11"> <input type="text" class="form-control" id="lastname" name="last_name" value= {{ form.first_name.value }} placeholder="last_name"> </div> </div> However, when I check it on browser, it displays None. How to solve such a problem? -
Django many to many serializer invert nested json representation
in Django have a many to many relatonship where I use selected_related to fetch the related tables data. However, the related tables data is nested inside each record, I'd like to inverse the relationship, is this possible without a custom serializer? to go from : [ { "id": 1, "item": " Sub item", "parent_items": { "id": 1, "description": "Parent Item Number 1", } }, { "id": 2, "item": " Sub item 2", "parent_items": { "id": 2, "description": "Parent Item Number 2", } ] to invert the parent relationship: [ { "parent_items": ""Parent Item Number 1", "id": 1, "item": { "id": 1, "description": "Sub Item 1", }, { "item": { "id": 2, "description": "Sub Item 2 ", }, }, { "parent_items": " Parent Item Number 2", "id": 2, "item": { "id": 1, "description": "SubItem Item 2", } ............ ] -
LiveServerTestCase ignoring fixture
I didn't see anywhere that LiveServerTestCase wasn't loading fixtures, but when i execute the following : class FrontTest(LiveServerTestCase): fixtures = ['event.json'] @classmethod def setUpClass(cls): super().setUpClass() print(Event.objects.all()) The output is : Using existing test database for alias 'default'... [] While when i use TestCase class FrontTest(TestCase): fixtures = ['event.json'] @classmethod def setUpClass(cls): super().setUpClass() print(Event.objects.all()) The ouput is : [<Event: event search>] Do you know why my fixture is loaded only in TestCase ? I'd really like to make it work to use Selenium. Thanks ! PS : event.json : { "model": "mezzanine_agenda.event", "pk": 1, "fields": { "comments_count": 0, "keywords_string": "", "rating_count": 0, "rating_sum": 0, "rating_average": 0.0, "site": 1, "title": "event search", "slug": "event-search", "_meta_title": "", "description": "event search", "gen_description": true, "created": "2018-05-25T15:49:55.223Z", "updated": "2018-05-25T15:49:55.257Z", "status": 2, "publish_date": "2018-05-25T15:49:32Z", "expiry_date": null, } }, -
how to relate user when login with image profile in django?
model.py class Avatar(models.Model): user_avatar = models.OneToOneField(User, on_delete = models.CASCADE) photo = models.ImageField(blank = True, null = True, default = 'default.jpg', upload_to = 'Avatar') -
Digital Ocean, Django and Nginx not finding all static files
I have tried a lot of different things but all of the solutions I found are not helping. I putting my corporate site on a digitalocean site on ubuntu 16.04 by following the digitalocean directions (which have worked well before) but it is only serving some of the static files. Here are the links to the images. <h3>Here is the image that doesn't load</h3> <img src="http://206.189.161.104/static/images/frac_stack_1.jpg" alt="Image that doesn't load"> <h3>Here is the image that does load in the same folder</h3> <img src="http://206.189.161.104/static/images/coil_pic.jpg" alt="Image that doesn't load" style="width:200px;height:200px;> Here is my nginx config: server { listen 80; server_name 206.189.161.104; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/dmckim/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/dmckim/myproject/myproject.sock; } } I tried removing the trailing slash off the static (as shown above). I also tried changing root to alias and adding the static folder to the path but I had the same results. Here is the code from my settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/home/dmckim/myproject/static/', '/home/dmckim/myproject/static/images/', ) I also tried clearing collectstatic before collectingstatic again and I always run these commands after and make sure my browser cache is cleared. sudo systemctl … -
Django app falls down after exception at model method
After simple assertion error at model method caused by bad data application stop working until restart of UWSGI. The following exception raises on requests to any URL of app. The stack is: Django 2.0.3 UWSGI 2.0.15 nginx 1.12.1 PostgreSQL 9.6 psycopg2 2.7.4 Environment: Request Method: GET Request URL: https://<...> Django Version: 2.0.3 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'bootstrap3', 'global_permissions', 'core', 'reports', 'django_celery_results', 'django_celery_beat', 'django_filters', 'rest_framework', 'rest_framework_filters', 'api', 'debug_toolbar'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/opt/oda_venv/lib/python3.5/site-packages/django/contrib/sessions/backends/base.py" in _get_session 191. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/opt/oda_venv/lib/python3.5/site-packages/django/db/backends/base/base.py" in _cursor 234. return self._prepare_cursor(self.create_cursor(name)) File "/opt/oda_venv/lib/python3.5/site-packages/django/db/backends/postgresql/base.py" in create_cursor 212. cursor = self.connection.cursor() The above exception (connection already closed) was the direct cause of the following exception: File "/opt/oda_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/opt/oda_venv/lib/python3.5/site-packages/django/utils/deprecation.py" in __call__ 97. response = self.process_response(request, response) File "/opt/oda_venv/lib/python3.5/site-packages/debug_toolbar/middleware.py" in process_response 132. panel.generate_stats(request, response) File "/opt/oda_venv/lib/python3.5/site-packages/debug_toolbar/panels/request.py" in generate_stats 59. for k in sorted(request.session.keys(), key=force_text)] File "/opt/oda_venv/lib/python3.5/site-packages/django/contrib/sessions/backends/base.py" in keys 126. return self._session.keys() File "/opt/oda_venv/lib/python3.5/site-packages/django/contrib/sessions/backends/base.py" in _get_session 196. self._session_cache = self.load() File "/opt/oda_venv/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py" in load 34. expire_date__gt=timezone.now() File "/opt/oda_venv/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), … -
Django cannot read Arabic from uploaded .xls file
When uploading a .xls file containing Arabic to my Django website, I get the following error when running code: UnicodeDecodeError 'charmap' codec can't decode byte 0x81 in position 655224: character maps to Here is my python / django code (it is original without any decoding as I tried many variants they all failed): #certain_file is the uploaded file certain_file = TextIOWrapper(request.FILES['certain_file'].file, encoding=request.encoding) with certain_file as f: soup = BeautifulSoup(f, "html.parser") #rest of code My goal is to parse uploaded file. Many thanks for the help in advance! -
Django Test form ValidationError
In my application I've extended UserCreationForm in a RegisterForm and i'm trying to test if register form returns ValidationError if password1 is not equal to password2. In each test attempt i received AssertionError: ValidationError not raised. class RegisterViewTestCase(TestCase): def setUp(self): self.data = { 'email': self.email, 'password1': 'valid_password1', 'password2': 'valid_password2' } def test_register_registers_invalid_data(self): form = RegisterForm(self.bad_data) self.assertFalse(form.is_valid()) with self.assertRaises(ValidationError): form.full_clean() Any clue why it's not passing the test? -
Validator on a Django form field gives Attribute Error
I made a validator for a field on a Django form I made. Here is the validator: from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy def validate_value(value): if value.isalpha(): if len(value) != 1: raise ValidationError( ugettext_lazy('Invalid zone value: %(value)s'), params={'value': value} ) elif value.isdecimal(): if int(value) == 0: raise ValidationError( ugettext_lazy('Invalid zone value: %(value)s'), ) else: raise ValidationError( ugettext_lazy('Invalid zone value: %(value)s'), params={'value': value} ) What this validator does is take in a string and see if it's either a single letter or a number. If it's none of those or that number equals zero, then it raises the validation error. For example, "a" and "3" will be accepted, but "a1" will raise the error. Below is the form that the validator is attached to: from django import forms from values.validators import validate_value class LetterOrNumberForm(forms.Form): value = forms.CharField(validators=[validate_value]) The problem comes when I test the form. What the form should do when a bad input is entered is show the validation error above the field. When I put in a value that is supposed to pass, like "a" or "3", the form works fine. But when I put in a bad input such as "a1", Django crashes and I get … -
MySQL + Django -- Many-to-many relationship involving 3 tables
I'm creating a web app for which I need to design a MySQL DB that has 3 tables linked by many-to-many relationships. Records in each table are unique and thus each table work as a catalog. Tables are: ~Books ~Authors ~Affiliations One Book can have many Authors, and an Author can have many Books. For a given Book, Authors can have multiple affiliations (e.g. New York University). My question is how can I represent better these relationships? I have thought 2 different approaches: 1) Intermediate table between Books and Authors (Books_Authors), and then use the PK of such table to connect it with another intermediate table between Books_Authors and Affiliations (say, Books_Authors_Affiliations). Records in table Books_Authors would look like (book1, author1), (book1, author2), whereas records in Books_Authors_Affiliations would look like ((book1, author1), affiliation1), ((book1, author1), affiliation2), ((book1, author2), affiliation1), etc. 2) Intermediate table among the 3 tables (Books_Authors_Affiliations) in which each record would look like (book1, author1, affiliation1), (book1, author1, affiliation2), (book1, author2, affiliation1), etc. My question is which approach is better in terms of DB design? and what is the best way to implement this in Django (explicit intermediate table using the "through" statement)? Cheers! -
How to dynamically remove or add a Django form for profile editing?
I'm creating a page where a user can edit certain fields of their profile by clicking where that field's current value is displayed. As such, I need to be able to display a model form for only that field dynamically. My first instinct was to dynamically add and remove the relevant html for the form using jQuery. This doesn't work because adding html client-side means that I can't use Django templating for the form. So, I guess that leaves me with my only option as showing/hiding the Django form. I would like input on the best way to achieve this goal (I know how to show and hide and disable, but I'm wondering if this is the best way; see below.) Furthermore, I have visited pages where I can open multiple of these "edit particular field" forms on a page clicking submit for a particular field and saving changes without reloading the current page (and keeping the other edit forms open). It almost seems like they are updating the database in real time without actually navigating to a new url. So my ultimate aim is to get something working like this with Django, and I would appreciate input. -
Django: Load javascript
I try to load the bootstrap-datepicker.js (Located: ...\AEB\static\date_picker\js) {% load staticfiles %} <script type="text/javascript" src="{% static "Leaflet_modi.js" %}"></script> <!-- Files for date time picker----------------------> <link rel="stylesheet" href="{% static 'date_picker/css/datepicker.css' %}" type = "text/css"/> <script type="text/javascript" src="{% static "date_picker/js/bootstrap-datepicker.js" %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#Start_Date').datepicker({ format: "dd/mm/yyyy" }); }); $(document).ready(function () { $('#End_Date').datepicker({ format: "dd/mm/yyyy" }); }); </script> But I always get the following error message: "Uncaught TypeError: $(...).datepicker is not a function" Where is my mistake? Thanks for your help. -
Downloading image creates grey artifacts in new file
Im trying to save an image from a url to a Django model. When I try this code, I get grey pixels in the bottom of the image, like it is saved before reading the whole image. Anyone see what could be wrong with this code, or know a better way to do this? def save_image(img_url, img_pk): file_name = img_url.split('/')[-1] external_image = requests.get(img_url, stream=True) if external_image.status_code == 200: # Create a temporary file lf = tempfile.NamedTemporaryFile() # Read the streamed image in sections for block in external_image.iter_content(1024 * 8): # If no more file then stop if not block: break # Write image block to temporary file lf.write(block) image_obj = Image.objects.get(pk=img_pk) image_obj.image.save(file_name, files.File(lf)) image_obj.save() return image_obj -
Django m2m_changed signal is never called
I can't understand why my signal is not triggered. Here is the code: models.py class Badge(TimeStampable, Expirable, Deactivable, SafeDeleteModel): _safedelete_policy = HARD_DELETE owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.PROTECT) restaurants = models.ManyToManyField(Restaurant) identifier = models.CharField(max_length=2048) objects = SafeDeleteManager.from_queryset(BadgeQuerySet)() signals.py from django.db.models.signals import m2m_changed from django.dispatch import receiver from .models import Badge @receiver(m2m_changed, sender=Badge.restaurants.through) def my_callback(sender, **kwargs): raise Exception("Triggered!") apps.py (this post advised to change this file) from django.apps import AppConfig class BadgesConfig(AppConfig): name = 'badges' def ready(self): import badges.signals When going in a shell, I create a Badge instance and a Restaurant instance, and then I run my_badge.restaurants.add(my_restaurant). No exception is raised, meaning the signal is not triggered! Why? I found similar post but did not found the answer in it. -
Python - Spoofing a single method in a library - Handling Dead Queue- Djangoq/qcluster/SQS
I am using djangoq in my project ,and using sqs as broker. As part of the system I enqueue some tasks which are taken by qcluster and executed. When some of the tasks are failed, they eventually end up in DEAD queue in SQS. Now, If I put a qcluster in that queue, the task would be tried to be executed again. But what I want is to take the task, inspect the arguments, take the PK of the object model and then mark it failed. And I found the thing that I need to do is, create a new worker function. and replace the default one. https://github.com/Koed00/django-q/blob/master/django_q/cluster.py#L341 The problem is the default one is called directly from the scope in the file, and not passed as arguments to other methods. So what I need to do is create an abstraction layer, which would import from djangoq package while injecting the new worker method into the package. And then I would run qcluster from that abstraction layer. But really dont know how to inject the new method and even that if it is possible or not. -
Nested Serializer for Many to Many
I am new to Python and Django. I am creating api using Django-Rest-Framework I want to serializer data that can accept json in below format: { "ingredients": ["Sugar","Egg"], "name": "Cake", "description": "Dinner Food", "directions": "direction1" } However I am able to persist data in db with below format: { "ingredients": [{"name":"Cake"},{"name":"Egg"}], "name": "Rice", "description": "Dinner Food", "directions": "direction1" } I am not sure how can I convert dictionary in to the set field. I am aware of List field and list serialiser but not sure how to use them. Is it possible to do this using model serialiser? Serializer.py class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = '__all__' class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True) class Meta: model = Recipe fields = '__all__' def create(self, validated_data): ingredients_data = validated_data.pop('ingredients') print(ingredients_data) recipe = Recipe.objects.create(**validated_data) for ingredient in ingredients_data: ingredient, created = Ingredient.objects.get_or_create(name=ingredient['name']) recipe.ingredients.add(ingredient) return recipe Model.py class Ingredient(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) directions = models.TextField() ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.name view.py class RecipieView(viewsets.ModelViewSet): queryset = Recipe.objects.all() serializer_class = RecipeSerializer class IngredientView(viewsets.ModelViewSet): queryset = Ingredient.objects.all() serializer_class = IngredientSerializer -
Apache is not serving static files from correct directory
I am actually not sure if the title of the topic is actually the source of my issue but there are serious indications for this. I am not an expert in application servers such as apache so any help is most welcome. I have installed successfully a Django application in a google cloud VM machine (Ubuntu 16.04 with static IP). I am able to access the page but there is no CSS loaded, missing javascript files (e.g. jquery) and several 500 Internal Server Errors. To give a better idea of the errors, I attach a screenshot The first think I thought is that I have not put the static files in the correct folder for the application server (www/../). But that was not the case. Then I thought maybe the www folder doesn't have the right permissions. But that wasn't not the case. The user was set correct to: www-data. My sites-enabled folder of apache2 include my project.conf file. Then I tried to run this command: /usr/sbin/apache2 -S and I got that back: VirtualHost configuration: *:80 localhost (/etc/apache2/sites-enabled/geonode.conf:3) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex proxy: using_defaults Mutex default: dir="/var/lock/apache2" mechanism=fcntl Mutex watchdog-callback: using_defaults PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS … -
Token authentification with DRF not active
I'm a beginner with DRF (Django Rest Framework). I'm trying to use an authentification with a Token in my api calls. I've done this : 1- When creating new user : from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings # This code is triggered whenever a new user has been created and saved to the database @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) 2- Create : ./manage.py createsuperuser --email f.user@blahblah.com --username fabrice The 2 tables (authtoken_token and auth_user) are ok. But when I call the API, if a don't add the token, the api's is working :( : $ http -a fabrice:azerty12 http://127.0.0.1:8000/firerisk/highway/ HTTP/1.1 200 OK Allow: GET Content-Length: 179 Content-Type: application/json Date: Thu, 31 May 2018 12:49:10 GMT Server: WSGIServer/0.2 CPython/3.5.2 Vary: Accept X-Frame-Options: SAMEORIGIN [ { "id": 1, "name": "XXX" }, { ... ... But, only this call must working, no ?? : http -a fabrice:azerty12 http://127.0.0.1:8000/firerisk/highway/ 'Authorization: Token a840a16a3cd43e346f7a3e1442fce0acdf51d609' And, if I don't use the authentification, it's fail, and it's ok : $ http http://127.0.0.1:8000/firerisk/highway/ HTTP/1.1 401 Unauthorized Allow: GET Content-Length: 58 Content-Type: application/json Date: Thu, 31 May 2018 12:25:44 GMT Server: WSGIServer/0.2 CPython/3.5.2 Vary: Accept, … -
React.js & Django S3 Upload Dilemma 403/Signature Does Not Match
I'm trying to have a functionality on my website where users can upload sounds (mp3/wav/etc.) and they will be stored in s3 under bucketname/audio/username/sound.mp3, but I keep getting 403 errors after my django backend returns the signed url. I've configured my bucket in 500 different ways to try and get this to work and I will share my current set up below so let me know if this could still be the problem but at this point I don't know where the problem lies at all. My django backend returns the signed url fine and both urls match but I get this error when clicking on the returned aws url . and this error in the console which is returned after the get request to django. I've been racking my brain trying to figure out what could possibly be wrong and I've run out of things to try. Here is my current bucket policy, IAM policy, as well as the django and react code (I am using a library called react-s3-uploader). CORS IAM Django (right above is the access key and secret imported from env variables so thats not the problem) React Component Any help would be greatly appreciated! -
Extracting specific data field from Django Rest Framework api
I've recently complete the Django Rest Framework api tutorial and am having a difficult time understanding specifically how it's used as a backend for an application I plan to develop (this is my first venture into backend development). To put more simply, I don't understand how querying will work from the front end. Navigating through the api with either the browser or httpie makes sense, but I'm at a loss for how a frontend extracts specified data from a model. For example, let's say I have the following: Models class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) highlighted = models.TextField() Serializers class SnippetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'url', 'highlight') Views class SnippetViewSet(viewsets.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer If I'm a user on the other end of an application, how would I query 'language' inside of the Snippet model? How would I have access to whatever information is in 'language', and in what way would a frontend need to interact with my api to obtain this information? My problem isn't necessarily how to …