Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to replace the logo title of 'django administrator'
my purpose is remove the the title of "Django administration" with yellow color in every admin page like following screen, please help. thanks. -
Requests parameters with non alphanumeric characters never match on lookup
I'm trying to retrieve a user based on their e-mail address using rest-frameworks ModelViewSet. Things work fine when there are only alphanumeric characters present in the request, however, it fails when characters such as @, . and _ are included. The response returned: { "detail": "Not found." } Where the e-mail address in the request exactly matches that in the database. Here is my current view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'email' -
Java HTTP Request with Token Authentication
I am trying to make a GET request to a local server I have running. I am having trouble returning the correct data, I am seeing an 'Unauthorized' response. Can anyone spot any glaring issues with this given that the String 'token' is correct. protected Object doInBackground(Void... params) { try { String url = "http://192.168.0.59:8000/events/"; URL object = new URL(url); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Authorization:", "Token " + token); //Display what the GET request returns StringBuilder sb = new StringBuilder(); int HttpResult = con.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); } else { System.out.println(con.getResponseMessage()); } } catch (Exception e) { Log.d("Uh Oh","Check your network."); return false; } return false; }* I was able to get a curl request working from the command line: curl -H "Authorization: Token token" http://0.0.0.0:8000/events/ -
Django: UpdateView for FormSet returns error when delete one or more
First of all, my models simply has a User model and Phone model which is a one-to-many relationship, where each user has many phones. I used the formset feature of django to create a user with many phones in one form with validating duplicates using the class below "CustomBaseInlineFormSet". It is working well, but my problem is in updating the user phones. In the UpdateView: I am getting the phones in the get request, then when adding or updating any field of the phone numbers, even when deleting one of them using the "x" button, it is working well. But, when just clear one of the phone number fields using the keyboard, the formset failed in validation step and returns error (This field is required), although if I added any new empty field, it ignores it. Finally, I want it to regard it as valid if any field is empty and save just the fields that have values. I searched a lot but I am stuck with it. Here is my code: forms.py: class PhoneForm(forms.ModelForm): class Meta: model = Phone fields = ("number",) from django.forms.models import BaseInlineFormSet class CustomBaseInlineFormSet(BaseInlineFormSet): def clean(self): values = set() for form in self.forms: value = … -
Django User Profile Model not saving
I have successfully created a profile model linked with the default Django user model, but I am having some trouble to save the profile with data. When I try to create a user, the default user is created with the data from the requests, but the profile model remains blank. The only field populated is the ID and the FK poiting to the user. HELP! The model: class StudentProfile(models.Model): user = models.OneToOneField(User, unique=True) address = models.CharField(max_length=100, null=True, blank=True) classroom = models.ForeignKey(Class, null=True, blank=True, related_name='classes', on_delete=models.CASCADE) birth = models.CharField(max_length=10, null=True, blank=True) isStudent = models.BooleanField(default=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: StudentProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The creation method: user, created = User.objects.create_user(username=request.POST['username'], email=None, password=request.POST['password'], is_staff=True) StudentProfile.objects.create(user=user) student = StudentProfile.objects.last() user = User.objects.last() user.profile.address = 'aeaeaeae' student.birth = request.POST['birth'] student.classroom = request.POST['class'] user.save() -
`-p` is for what in creating virtual environment command of Django
Django creates virtual environment alternatively applies command: virtualenv -p python3 . I have typed over 30 times of the commands. The meaning of -p is a ghost for me.To search it several times,I failed to get its explanation. I wonder it might be out of the scope of my concepts and vocabulary. -
Connect Django to existing Docker Postgres container
I have a situation where I need to connect my Django to existing Docker Postgres container. In simple words, when i execute "python manage.py dbshell", django should connect to existing Docker Postgres container. Currently my django is connected to sqlite3 db. Below is my settings.py snippet for connecting to db. DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'etag_auth', # 'USER': 'etag_master', # 'PASSWORD': 'thisismypass', # 'HOST': 'cybercom_postgres', # 'PORT': '5432' 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } # 'etag': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'etag', # 'USER': 'etag_master', # 'PASSWORD': 'thisismypass', # 'HOST': 'cybercom_postgres', # 'PORT': '5432', # } } I also tried with docker-compose, but i am not able to make docker-compose to connect to existing container. Below is my docker-compose.yml code snippet postgres: external: name: etag_postgres image: postgres ports: - "5432:5432" volumes: - /data/db Kindly help to solve the issue. -
DJango giving me an error when I use user.isAuthenticated
I am working on getting my Clubs website back up and running after our previous coder left. He left nothing behind so now hen I run it Django gives me the error File "/home/serverad/django14_project/my_django15_project/tsa/events/views.py", line 112, in custom500 return render_template('errors/500.mako', request, parent='../base.mako' if request.user.is_authenticated() else '../layout.mako') AttributeError: 'WSGIRequest' object has no attribute 'user' I have no idea what is wrong seeing as though our last programmer left no notes behind. -
import a python file ; custom hashing generator into hashers.py
hye again . how to import my custom password hasher generator ? i have been trying to do it for days now . it still give an error . my project name : tryFOUR my custom password hasher app name: honeywordHasher my custom password hasher generator file name : honey_gen.py i tried : from honeywordHasher.honey_gen import honey_gen it give an error . im confused because the honey_gen.py dont have a class . error : ImportError at /accounts/register/ cannot import name 'honey_gen' Traceback: File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save(commit=False) File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password1"]) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in make_password 79. hasher = get_hasher(hasher) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in get_hasher 124. return get_hashers()[0] File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in get_hashers 91. hasher_cls = import_string(hasher_path) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\module_loading.py" in import_string 20. module = import_module(module_path) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\Adila\Documents\tryFOUR\src\honeywordHasher\hashers.py" in <module> 4. from honeywordHasher.honey_gen import honey_gen Exception Type: ImportError at /accounts/register/ Exception Value: cannot import name 'honey_gen' -
connection to postgres database fails infrequently
I am connecting to a Postgres database on windows using Django/Pycharm. I have done this plenty of times on other computers and am pretty confident I configured the connection correctly. Every once in a while the database connection fails and returns an error. It happens both in my Django app as well as using the pycharm UI. It is odd because it works at least every 9/10 times I interact with the database, but I've noticed that maybe it usually happens when I try to interact with the db multiple times in quick bursts, but this is not always the case. In the pycharm database connection UI, when I test the connection it usually works, but sometimes fails. I am using the default 'postgres' user, and I suspect that may be the issue. The following is the db configuration in my Django app, though I'm pretty positive this problem is unrelated to my code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'contract_directory_site', 'USER': 'postgres', 'PASSWORD': 'my_password', } } Everything except the password is exactly how it looks in my code and in my PyCharm database connection properties. -
Django admin Inline Forms not working on production
I have a django admin inline form that works locally but doesn't work on production. Locally: And on Heroku: I don't have a clue why this could be. Any ideas? Any advice will help. This is the code: class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline, TiptiItemInline, MessageInline] search_fields = ['client', 'shopper', 'state'] list_display = ['date', 'client', 'state', 'address', 'payment_method'] readonly_fields = ['client', 'address', 'billing_info', 'payment_methods', 'history', 'rate'] -
Django Restful Framework Update Object
I am a Beginner in Django Restful Framework. I want to create a BookAPI, here is my model: models.py book_id = models.AutoField(primary_key=True) book_name = models.CharField(max_length=64, null=False) order = models.IntegerField(null=True) Now I can get the list of books by GET http://localhost:8000/api/books/. And I want to modify the order of books and let every book has a unique order by PUT http://localhost:8000/api/books/orders "Response": [ { "book_id": 1, "order": 1 }, { "book_id": 2, "order": 2 } ] And Here is my serializer.py class OrderSerializer(ModelSerializer): class Meta: model = Book fields=['book_id','order'] so what should I do for update function in serializer.py -
Best way to implement django model that need several layers of relation
I am building a quiz application using Django and can’t figure out the best way of building the models in regard to question category. A question will be related to one domain, for example it could be IT, Aviation or Science etc. This will be unique field. A topic will relate to a domain, for example meteorology could be part of the Aviation domain but could also be part of Science domain. For this reason this can’t be a unique field. A sub-topic will directly relate to a topic (and consequently a domain), for example climate or atmosphere would be part of Aviation->Meteorology Here are some example of combination of categories Aviation->Meteorology->Climate Aviation->Meteorology->Atmosphere Aviation->Mass and Balance The sub-topic is optional but all combination must be unique i.e. I can’t have two “Aviation->Meteorology->Climate” or two “Aviation->Mass and Balance” I am not sure how to implement this in the models but was thinking of doing one of the two solutions below 1) class Question(models.Model): question_text = models.TextField('What is the question?', max_length=4000) question_category = models.ForeignKey(Category) question_type = models.CharField('Question Type', max_length=50) question_comment = models.TextField(('Question Comments/Explanations', max_length=4000) question_created = models.DateTimeField(auto_now_add=True) class Category(models.Model): domain = models.CharField(max_length=255, unique=True) topic = models.CharField(max_length=255) sub_topic = models.CharField(max_length=255) 2) class Question(models.Model): … -
Using Django's ImageFile and/or plain Pillow... how can I get the image size in inches?
This means: Images formats like PNG or JPEG have size metadata somewhere that allow to tell how many pixels per inch the image has. Right now I can only tell the pixel size of an image (my_model_instance.my_image_field.width and height). What I'd like to know actually comes in two parts: Validate that the uploaded image file supports pixels-per-inches somehow in its metadata, header, ... Be able to obtain such values and calculate something like iwidth = width / pixels_per_inch. -
Django unable to install Channels (websockets) with pip
pip install channels, in python 3.6.2, django 1.11.6 Failed building wheel for twisted Then a lot of random status updates about copying/creating etc.. Then: Command ""c:\program files\python36\python.exe" -u -c "import setuptools,tokenize;__file__='C:\\Users\\Phil\\AppData\\Local\\Temp\\pip-build-vrw7n8yu\\twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Phil\AppData\Local\Temp\pip-ybcrap_c-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Phil\AppData\Local\Temp\pip-build-vrw7n8yu\twisted\ My best attempt at implementing websockets into a django server, not going well! -
Authentication using Django’s sessions db from Apache
I have a Django application which I now want to integrate it with Kibana. So when authenticated users click on a link, they will be directed to Kibana. But this option should not be available to anonymous users. My stack is Psql + Django + mod_wsgi + Apache. The solution I came up with was restricting access to Kibana via Apache, and authenticating users in Django before giving them access. This HowTo in Django website says how you can authenticate against Django from Apache, but that one uses Basic authentication. When I use this approach, even for users who already have an active session in my Django app, they will be asked to enter their username/password in a browser dialog! I was hoping the authentication to happen using the current Django active sessions. I believe for that I need to use AuthType form and mod_session, instead of AuthType Basic, but it seems mod_wsgi has no plan to support mod_session (as discussed here). I checked other WSGI alternatives as well (gunicorn and uWSGI), but couldn't find anything. So my question is how I can Authenticate against Django session db? Is using mod_session + AuthType form correct? and if yes, what's the … -
In a Django admin, add an inline of a generic relation
Here are my simplified models : from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation) from django.db import models from django.utils.translation import ugettext_lazy as _ class Thing(models.Model): ''' Our 'Thing' class with a link (generic relationship) to an abstract config ''' name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Name of my thing')) # Link to our configs config_content_type = models.ForeignKey( ContentType, null=True, blank=True) config_object_id = models.PositiveIntegerField( null=True, blank=True) config_object = GenericForeignKey( 'config_content_type', 'config_object_id') class Config(models.Model): ''' Base class for custom Configs ''' class Meta: abstract = True name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Config Name')) thing = GenericRelation( Thing, related_query_name='config') class FirstConfig(Config): pass class SecondConfig(Config): pass And Here's the admin: from django.contrib import admin from .models import FirstConfig, SecondConfig, Thing class FirstConfigInline(admin.StackedInline): model = FirstConfig class SecondConfigInline(admin.StackedInline): model = SecondConfig class ThingAdmin(admin.ModelAdmin): model = Thing def get_inline_instances(self, request, obj=None): ''' Returns our Thing Config inline ''' if obj is not None: m_name = obj.config_object._meta.model_name if m_name == "firstconfig": return [FirstConfigInline(self.model, self.admin_site), ] elif m_name == "secondconfig": return [SecondConfigInline(self.model, self.admin_site), ] return [] admin.site.register(Thing, ThingAdmin) So far, I've a Thing object with a FirstConfig object linked together. The code is simplified: in an unrelevant part I manage to create my abstract Config at a Thing creation and … -
django python manage.py createsuperuser: AttributeError: module 'os' has no attribute 'PathLike'
so I'm trying a django tutorial. for some reason my existing superuser got deleted. creating that went fine. but I can't make another one. this also happens when I try to use pip. didn't change anything in the libraries so not sure why this happens now but didn't before. on windows 7 btw(python 3.6.3 django 1.11). I've seen similar but not the exact same problems for windows. still I checked the file and there seems to be a PathLike class. I've also tried to repair my python installation but it didn't help. any ideas? god bless -
How To Implement A SAAS App In Django Without Using Subdomains
This article makes a good argument for avoiding subdomains in a SAAS app. All of the SAAS solutions I've found for Django so far all use subdomains. Is there a reliable way to implement a multi-tenant app in Django that doesn't use subdomains? -
difficulty with bootstrap container - django-bootstrap3
I have the following template schema: layout.html is my base template And I have another templates which inherit from layout.html I am using third party package application django-bootstrap3 My layout.html is: (The divs amount of navbar and django variables templates does not matter - are just for demonstration) {% load staticfiles %} {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} <html lang="es"> {% block head %} <head> <title>{% block title_tag %}My APP{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> {% endblock %} <body> <div class="wrapper"> <!-- Nav menu --> <header> {% if request.user.is_authenticated %} {% if userprofile %} <div class="profile-options"> {% comment %} Begin settings drowdown {% endcomment %} <div class="name-options-cont"> <div class="name"> <p>{{ userprofile.user.email }} - {{ userprofile.user.enterprise_name }}</p> </div> <div class="options"> <div class="drop-down"> <ul> <li><a href="{% url 'some-url' %}" >Some option</a></li> <li><a href="{% url 'some-url2' %}" >Some option2</a></li> <li><a href="{% url 'accounts:logout' %}">Exit</a></li> </ul> </div> </div> </div> </div> {% endif %} {% else %} <div class="registration"> <a href="{% url 'accounts:signup' %}">Registrarse</a><a href="{% url 'login' %}">Iniciar sesión</a> </div> {% endif %} </header> <div class="container"> {% if messages %} {% for message in messages %} <div class='alert {% if "success" in message.tags %}alert-success{% elif "warning" in … -
Django : cannot retrieve numbers of objects
I am working on a project in django 1.11.0, and I have this model called Album, every user can add albums. Well I wanted to show numbers of authentificated user, but nothing !! Here's the view : @login_required() def user_account(request): user = request.user user_albums = Album.objects.filter(user=request.user) nb_albums = 0 for i in user_albums: nb_albums = nb_albums + 1 context = { 'nb_albums': nb_albums } return render(request, 'music/user_account.html', {'user': user}, context) and here is the bit code in the page html : <td>{{ request.user }}</td> <td>{{ request.user.first_name }}</td> <td>{{ request.user.last_name }}</td> <td>{{ request.user.email }}</td> <td>{{ nb_albums }}</td> -
return float(value) ValueError: could not convert string to float in Django models
I try to makemigrations / migrate on this Django models : from django.db import models from myapp.models import Site class GscElement(models.Model): ctr = models.FloatField('Taux de clic', default=0.0) impressions = models.IntegerField('Nombre d\'impressions', default=0) position = models.FloatField('Position moyenne', default=0.0) clicks = models.IntegerField('Nombre de clics', default=0) site = models.ForeignKey( Site, models.SET_NULL, blank=True, null=True ) class Page(GscElement): page_field = models.TextField('Url de la page', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'page_field',)) class Query(GscElement): query_field = models.TextField('Requête', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'query_field'),) and I get this error : [...] , line 1781, in get_prep_value return float(value) ValueError: could not convert string to float: Do you have any idea why ? FYI I tried to restore the databased I had before my models changes and tried to squash migrations too, but the same error always occured. Thank you ! -
Django import errors for app csvimport
I really don't know where to start with this error message so wondering if anyone's seen similar before? The weird thing is that my CSV import itself actually works fine, but I am a tad concerned by the error messages: Applying csvimport.0002_test_models...Traceback (most recent call last): File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "csvtests_country" LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 93, in __exit__ self.execute(sql) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/utils.py", … -
Remote Debugging Visual Studio Code, Django, Daphne, Daphne Workers running in Docker Containers
Just started using visual studio code for python development and I like it so far. I am having issues doing remote debugging in a django app running on docker. Was hoping someone would point me in the right direction to setup V.S debugging in django through docker. I am running Django rest framework in docker container. I am using asgi server daphne because of websocket connections. I want to know if there is a way to use remote debugging in django running in docker with daphne workers. I have looked at some tutorial but they are for wsgi part. The problem I am having is that daphne uses workers to connect to daphne server and process the requests that way. Things I have tried: Able to use pdb to debug. Have to connect to the worker container and also specify stdin_open: true and tty: true. It works but is a tedious process. Tried the steps involved in the tutorial URL specified but it didn't work for Visual Studio Code. Also tried using remote debugging in pycharm but the background skeleton processes make my computer really slow. But I was able to make it work. Hoping I could do the same … -
django object data disappears when I refresh page
When I load the page for the first time, the object data is there (so three links in the example below), after starting runserver on my computer. If I reload the object data is not longer there (so zero links in the example below). template {% for url in urls %} <a href="{{ url }}"> link </a> {% endfor %} view class IntroView(View): template_name = '[app_name]/template.html' model_names = ['shoe', 'hat', 'bag'] urls = [reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names] dict_to_template = {'urls': urls} def get(self, request, *args, **kwargs): return render(request, self.template_name, context=self.dict_to_template) It's probably something really simple, but it's got me. Thank you for your time.