Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Temporarily saving file objects and cleaning up once done (Django)
I'm creating a Django website where users post details of used items they want to sell/barter. When posting an item, the second-last step is to upload (upto 3) photos of the item on sale. The last step is to provide personal details (name, address, mobile). After this, the ad is finalized and goes into a "pending approval" queue. I don't want to save photos to the DB until an advert is finalized. Hence I'm thinking I'll return an InMemoryUploadedFile object and do: request.session["photo"] = InMemoryUploadedFile(thumbnail_string, None, 'temp.jpg', 'image/jpeg', thumbnail_string.len, None) Would this work? I've seen various criticisms that file objects aren't serializable, meaning I could be mistaken here. Next, once ad is final, I'll save the images in my backend and pop photo from the request.session dictionary. Even if saving in request.session works, how would I handle cases where a request.session["photo"] entry was created, but the user never finished the ad? I don't want to have such 'orphan' images lying in my server memory. -
Is it ok to change request.POST._mutable
Django 1.11.2 Do you think this is a good style or not: In CBV: request.POST._mutable = True request.POST['{}_date_day'.format(prefix)] = ceil_day(day=day, month=month, year=year) request.POST._mutable = False The program works well. I'm satisfied. What troubles me is whether this is ok or not. Maybe it is really a bad practice. I mean, is it acceptable that we should change the private property _mutable? -
How can I control Django-admin panel permissions across two apps?
I have two apps "App1" & "App2". Using "App2" views.py I want to display the information about models of "App1" but with only read-only permissions. like just display the info in the same manner Django-admin does. -
how can I securely perform Rest requests without authentication?
This is more a process logic question than a specific language-framework one. I am developing a mobile app and want the user to be able to use it without having to login (i.e. try it and offer a plus to the logged users), but I don´t want other persons to make post requests from let´s say Postman or any other platform than the app without having some sort of key, so what would be the approach here? I am thinking on basic auth with some secret username:password for guests, or some kind of token, but as I am totally new on this I am not sure if it´s the correct approach, I´ve read the authentication and permissions Django Rest Framework tutorial but haven´t found a solution -
Getting 415 code with django.test.Client's patch method
When I send a PATCH request to my Django app running on localhost via the command line like so: http -a <username>:<password> PATCH http://127.0.0.1:8000/post/1/ text="new text" It works as expected and I get a 200 OK code back. When I try to do the same thing in my unit test using the django.test.Client.patch method like this: In [1]: from django.test import Client In [2]: client = Client() In [3]: client.login(username='<username>', password='<password>') Out[3]: True In [4]: client.patch('/post/1/', {'text': 'new text'}) Out[4]: <Response status_code=415, "application/json"> I get a 415 (Unsupported Media) response code. If I try adding the parameter content-type='application/json' to the patch method (I shouldn't have to do this because I'm able to send GET, POST, and DELETE requests using the Client class without providing that parameter) I get a 400 error code. As I said, when I use the class's get, delete, and post methods, the behavior is as expected. Am I using the method properly? Is this a bug? -
CSS not working for one section in my HTML code
For some reason, my CSS code doesn't work for the .transform class, but it does for the rest of the code. HTML code {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Home{% endblock %}</title> <link rel = 'stylesheet' type="text/css" href="{% static 'change/css/bootstrap.min.css' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel = 'stylesheet' type="text/css" href='{% static 'change/css/base.css' %}'> </head> <body> <nav class="navbar-fixed-top navbar navbar-default navbar-inverse" id = 'navbar'> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Link</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <section id = 'cover'> <div id = 'cover-caption'> <div class = 'container-fluid'> <div class = 'col-md-12' id = 'text'> <h1>Get Fit Fast</h1> <p>Get a six pack, big arms, wide shoulders in less than 12 weeks.</p> <p>Live your life to the fullest!</p> </div> </div> </div> </section> {#Jumbotron beginning#} <section class = 'transform'> … -
get tuple list element by string name in python
I have the following tuple list: It is for choice fields in a django model. ENTITY_TYPE_CHOICES = ( (0,'choice1'), (1,'choice2'), ) I want to get the choices by their string name like: entity_type_index = ENTITY_TYPE_CHOICES['choice1'] I get the error: tuple indices must be integers, not str -
Changing field type in a Django view
I have a project, where people will be able to create variables for a form, and then other users will fill that form. When they create the said form, they can chose the answer to be of 3 different types : From a list of value, an integer, or a string. Basically, I create a formset of all the variables the user created for this form, but if it is a list, I want to change the type of the input from a CharField to a ChoiceField. So this is my view : def insererDonnee(request, modele, contexte=-1): variables = Variable.objects.filter(modele=modele) varIter = variables.iterator() DonneeFormSet = formset_factory(InsertDonneeForm, extra=variables.count()) submitAdress = "insererDonnee" if request.POST: formset = DonneeFormSet(request.POST) else: formset = DonneeFormSet() for formx in formset: formx.variable = varIter.next() formx.nomVar = formx.variable.nom formx.fields['valeur'].label = formx.nomVar # Here I call setList to change the type if formx.variable.type_variable in ["SOLIST", "LIST"]: formx.setList(formx.variable) And my form: class InsertDonneeForm(forms.Form): variable = Variable() nomVar = 'Variable' valeur = forms.CharField(label=nomVar, max_length=100) def setList(self, variable): choices = ListItem.objects.filter(variable=variable, modele=variable.modele) valeur = forms.ModelChoiceField(queryset=choices)# or None) print valeur The last print was just to see if the field was indeed changed, which it is, but if I do the same print in … -
Getting related_descriptors.RelatedManager instead of getting unique model object by id
I have a Patient and a Doctor model that inherits from django User class HmsUser(AbstractBaseUser, PermissionsMixin): # .... def real(self, ): try: return self.doctor except Doctor.DoesNotExist: try: return self.operator except Operator.DoesNotExist: try: return self.patient except Patient.DoesNotExist: try: return self.organization except Organization.DoesNotExist: return self class Person(HmsUser): image = models.ImageField(null=True, blank=True) class Meta: abstract = True # .... class Patient(Person): # .... class Doctor(Person): # .... I have different view for doctor and patient def patient(request, patient_id): patient = Patient.objects.get(id=patient_id) print(patient.real().__class__) def doctor(request, doctor_id): doctor = Doctor.objects.get(id=doctor_id) print(doctor.real().__class__) The doctor.real().__class__ returns <class 'identity.models.Doctor'> but patient.real().__class__ returns <class 'django.db.models.fields.related_descriptors.RelatedManager'> Why patient.real().__class__ is not <class 'identity.models.Patient'> -
Docker: How to rely on a local db rather than a db docker container?
Overall: I don't want my django app to rely on a docker container as my db. In other words, when I run an image docker run -p 8000:8000 -d imagename I want this to know to connect to my local db. I have my settings.py configured to connect to a pg db, so everything is fine when I do something like python manage.py runserver Feel free to call out any incorrect use of certain terms or just my overall understanding of docker. So from all the tutorials I've seen they usually make a docker compose file that is reliant on a db-image that will be spun up in a container separate from the web app. Examples of things I've gone through: https://docs.docker.com/compose/django/#connect-the-database, http://ruddra.com/2016/08/14/docker-django-nginx-postgres/, etc. At this point I'm extremely lost, since I don't know if I do this in my Dockerfile, settings.py in my project, or docker-compose.yml (I'm guessing I shouldn't even have this since this is for a multi-container app which I'm trying to avoid). [Aside: Lastly, can one run a django app reliant on celery & rabbitmq in just one container? Like my pg example I only see instances of having them all in separate containers.] As for … -
Failed Building Wheel for mysqlclient with gcc.exe Error
I'm installing in the process of installing django on windows. I use WinPython 3.4.4.4 on Windows 64-bit. My MySQL Version is 5.6.32 according to Workbench. When I did "pip install mysqlclient", I got "gcc.exe: error: /Zl: No such file or directory". Here is following log: C:\WinPython-64bit-3.4.4.4Qt5\scripts>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command C:\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\BRADWY~1\\AppData\\Local\\Temp\\pip-build-ze_7a4re\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\BRADWY~1\AppData\Local\Temp\tmpmazvgwu3pip-wheel- --python-tag cp34: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.4 copying _mysql_exceptions.py -> build\lib.win-amd64-3.4 creating build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.4\MySQLdb creating build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.4\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win-amd64-3.4 creating build\temp.win-amd64-3.4\Release C:\WinPython-64bit-3.4.4.4Qt5\scripts\..\python-3.4.4.amd64\Scripts\gcc.exe -mdll -O -Wall -Dversion_info=(1,3,10,'final',0) -D__version__=1.3.10 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -IC:\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\include -IC:\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\include -c _mysql.c -o build\temp.win-amd64-3.4\Release\_mysql.o /Zl gcc.exe: error: /Zl: No such file or directory error: command 'C:\\WinPython-64bit-3.4.4.4Qt5\\scripts\\..\\python-3.4.4.amd64\\Scripts\\gcc.exe' failed … -
Can't use Jinja elements on Page
I am working on Django and new to Jinja templates. I am able to print variable from the context but can't use other features of Jinja. When I do {{ 1+1 }} on the page . it shows: Could not parse the remainder: '+1' from '1+1' I am trying to generate a random no. as by this answer. but it throws error as: Could not parse some characters: range|(1, 51)| | random -
Django makemigrations fail in heroku
I'm trying to deploy a Django (1.10.6) app to Heroku, runtime Python 3.6.1. The app runs succesfully (except the fact that tables are not created), but when trying run the makemigrations I get the following error: Running python manage.py makemigrations on prochu1991... up, run.2221 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/reportlab/lib/utils.py", line 667, in open_for_read return open_for_read_by_name(name,mode) File "/app/.heroku/python/lib/python3.6/site-packages/reportlab/lib/utils.py", line 611, in open_for_read_by_name return open(name,mode) FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Windows\\Fonts\\Ver dana.ttf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/reportlab/lib/utils.py", line 670, in open_for_read return getBytesIO(datareader(name) if name[:5].lower()=='data:' else urlopen (name).read()) File "/app/.heroku/python/lib/python3.6/urllib/request.py", line 223, in urlop en return opener.open(url, data, timeout) File "/app/.heroku/python/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/app/.heroku/python/lib/python3.6/urllib/request.py", line 549, in _open 'unknown_open', req) File "/app/.heroku/python/lib/python3.6/urllib/request.py", line 504, in _call _chain result = func(*args) File "/app/.heroku/python/lib/python3.6/urllib/request.py", line 1388, in unkn own_open raise URLError('unknown url type: %s' % type) urllib.error.URLError: <urlopen error unknown url type: c> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/reportlab/pdfbase/ttfont s.py", line 137, in TTFOpenFile f = open_for_read(fn,'rb') File "/app/.heroku/python/lib/python3.6/site-packages/reportlab/lib/utils.py", line 672, in open_for_read raise IOError('Cannot open resource "%s"' % name) … -
Django Rest Framework SerializerMethodField TypeError: "'RelatedManager' object does not support indexing"
I have two SerializerMethodFields on a serializer. One of them returns obj.somelist.count() fine. But where I am asking the other method to return obj.somelist[0] I'm getting a TypeError 'RelatedManager' object does not support indexing. Any advice is much appreciated. Here's some code: class TripSerializer(serializers.ModelSerializer): stops = StopSerializer(read_only=True, many=True) stops_count = serializers.SerializerMethodField() car = CarSerializer(read_only=True, many=False) origin = serializers.SerializerMethodField() class Meta: model = Trip fields = ('id', 'name', 'owner', 'car', 'stops_count', 'stops', 'origin', ) def get_stops_count(self, obj): return obj.stops.count() #OK def get_origin(self, obj): return obj.stops[0] #TypeError -
Django manage.py commands that require input get stuck
Since a while any python manage.py command that requires an input (removing null=True without providing default, recollecting static files...) does not accept said input. when I press enter it simply displays the carriage return char ^M in the console. I have no Idea how to debug this, as ctrl+ c simply gives tracebacks like these: ./manage.py makemigrations You are trying to change the nullable field 'package' on company to non-nullable without a default; we cannot do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration) 3) Quit, and let me add a default in models.py Select an option: 1^M^M^M^C^CKeyboardInterrupt 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 "/Users/mac/.virtualenvs/mindance/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/mac/.virtualenvs/mindance/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mac/.virtualenvs/mindance/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File … -
Django raises IntegrityError: UNIQUE constraint failed in unit test
When I try to create the Timesheet object in the test.py or in the shell interface, I get an integrity error. However, I can create the object via the served html interface just fine. Error, models, views, and forms below. Any thoughts or advice would be greatly appreciated. Error: Traceback (most recent call last): File "<console>", line 5, in <module> File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/query.py", line 399, in create obj.save(force_insert=True, using=self.db) File "/Users/Development/et/timesheets/models.py", line 222, in save return super(Timesheet, self).save(*args, **kwargs) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/query.py", line 1045, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/Development/venvs/venv-2017-01/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute … -
How do I get an Django ViewSet to return a 403 error on anonymous post
I'm trying to get my app to return a 403 error when an anonymous user attempts to POST to it. Right now it returns a 201 code, but doesn't save the post to the database. The problem is that my unit test fails because it's checking for a 403 code. Here is my views from post.models import Post from post.serializers import PostSerializer from post.permissions import IsOwnerOrReadOnly, IsOwnerOrAdmin from rest_framework import viewsets, status from rest_framework.response import Response class PostViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Post.objects.all() serializer_class = PostSerializer # The default will be that anyone can read a post, but only owners can change it permission_classes = (IsOwnerOrReadOnly,) def get_permissions(self): # Both owners and admins can destroy a post, so if we're destroying we change permissions if self.action in ('destroy',): self.permission_classes = [IsOwnerOrAdmin, ] return super(self.__class__, self).get_permissions() def perform_create(self, serializer): if self.request.user.is_authenticated: serializer.save(author=self.request.user) else: return Response('Cannot post anonymously', status=status.HTTP_403_FORBIDDEN) You can see I'm checking it the user is authenticated and if not, returns a Response with a 403 code, but for some reason a 201 code is being returned. How do I get it to return a 403 code? -
how to access request in tastypie Resource?
#api.py class MyResource(ModelResource): class Meta: queryset = Model.objects.all() This would get an api with all objects of that Model. I use an app called django -vote to get only the voted objects of a Model. in this way queryset = Model.votes.all(request.user.id) . But how to access request in a Resource class? -
Drango order_by('?')[:n] n using a variable which I take from the database? but not work
def home (request): questions = Article.objects.order_by('?') n = guestionNum.objects.all() n = n[0] answers = Answer.objects.all().order_by('?')[:n] return render_to_response('question/home.html', {'questions': questions, 'answers': answers,'n':n, 'username':auth.get_user(request).username}) ` TypeError: '>=' not supported between instances of 'guestionNum' and 'int' How do I make a slice using a variable n which I take from the database? -
Unable to make migration since loaded in eclipse
i'm trying to makemigrations on my project but since i loaded it in eclips (it modified an environment variable but i don't know wich one) but i now have a permission error. Here are my logs /usr/lib/python3.6/site-packages/django/contrib/admin/migrations/0001_initial.py - Create model LogEntry Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 193, in handle self.write_migration_files(changes) File "/usr/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 232, in write_migration_files with io.open(writer.path, "w", encoding='utf-8') as fh: PermissionError: [Errno 13] Permission denied: '/usr/lib/python3.6/site-packages/django/contrib/admin/migrations/0001_initial.py' EDIT 1: I don't want to use sudo, it worked without it before. EDIT 2 : I don't use eclipse anymore. -
cant add field to form dynamically
i want to add field to my form in django. When i clicked "add button", it adds a new char field. when i clicked remove it removes the charfield. Therefore, i looked a few articles and stackoverflow questions, but i couldnt make it. This my codes after my efforts. views.py from django.shortcuts import render,redirect,HttpResponse,Http404 from .forms import girisFormu,kayitFormu,ProfileForm from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages from uyelik.models import ders_bilgileri from django.contrib.auth.models import User @login_required def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST,extra=request.POST.get("total_input_fields"), instance=request.user.ders_bilgileri) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Bilgileriniz başarıyla güncellendi!')) else: messages.error(request, ('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.ders_bilgileri) return render(request, 'uyelik/detay.html', { 'form': profile_form }) models.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver User._meta.get_field('email').blank = False class ders_bilgileri(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) dersler = models.TextField(max_length=500,blank=True) facebook_adresi=models.URLField(max_length=1000,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: ders_bilgileri.objects.create(user=instance) forms.py from django import forms from django.contrib.auth import authenticate from django.contrib.auth.models import User from uyelik.models import ders_bilgileri class ProfileForm(forms.ModelForm): dersler=forms.CharField(max_length=1000,label="Dersleriniz: ",widget=forms.Textarea) total_input_fields = forms.CharField(widget=forms.HiddenInput()) facebook_adresi=forms.URLField(max_length=100, label="Facebook adresiniz: ") def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) # check if extra_fields exist. If they don't … -
"<Association: >" needs to have a value for field "association" before this many-to-many relationship can be used: django error
I have seen a bit of similar threads here in SO but cant seem to solve it. Here is my model: class Association(models.Model): ''' For members declared as groups ''' member=models.ManyToManyField(User,related_name='association_user') name=models.CharField(max_length=50) def __str__(self): return self.name class Meta: ordering=('name',) The many-to-many relationship ended up creating, i think, a table under the hood with the following definitions: association_id user_id I don't know if it is refering to the that field association nor how to add values to that table from my views. my forms.py class NewAssocationForm(forms.ModelForm): ''' this is used to create a new form ''' class Meta: model=Association fields=['name',] labels=['Assocation Name'),] and my views.py: @login_required def make_new(request): ''' Register a new association or corporate ''' if request.method=='POST': form=NewAssocationForm(request.POST or None) if form.is_valid(): new_association=form.save(commit=False) new_association.member=request.user new_association.save() #add a message then redirect return HttpResponseRedirect('/corporates/done/) else: form=NewAssocationForm(request.POST or None) else: form=NewAssocationForm(request.POST or None) return render(request, "association_new.html", locals()) I don't have a field named association in my model at all. I doubt it is constraint erorr cos i can insert records to the table from the shell without any issues. Here is my traceback. Environment: Request Method: POST Request URL: http://localhost:9000/corporates/new/ Django Version: 1.10 Python Version: 3.4.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Setting up a Django development server that can be accessed by other devices on my network
I want to set up a Django development server that both my computers and smart phones can access whilst on my network via wifi. I've already set up a development server that my computer can access on http://127.0.0.1:8000/. However, my other devices can't. The Django documentation says: "Note that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled)." I've found my "public IP address" and tried to use this by: python manage.py runserver xx.xx.xxx.x (where this is my public ip address) but i get a command error that this is not a valid port number or address:port pair. I then tried the same with :8000 after the IP address, but got an error "Error: That IP address can't be assigned to". Then python manage.py runserver 0.0.0.0:8000. The command line reports the development server has started, but when i try "http://0.0.0.0:8000/" on Chrome, i get a "This site can't be reached error". Is it something to do with my windows firewall settings? Please can you someone help me? Thanks! -
Dynamic checkbox checked
Currently, I'm using a simple form to display a list of games. This list is presented with checkboxes. The user just check a game to add it to his favorite games. So basically, when the user is back to the list, I just want to make the user able to check or uncheck a game from the list. But I don't know how to check a game if the user already selected it Any idea ? Thanks ! forms.py : class GamesRegisterForm(forms.Form): favorite_games_choices = [] for game in Games.objects.all().order_by('title'): favorite_games_choices.append((game.guid, game.title), ) favorite_games = forms.MultipleChoiceField( required=True, initial=True, widget=forms.CheckboxSelectMultiple(), choices=favorite_games_choices, ) class LogonForm(forms.Form): email = forms.EmailField( ) password = forms.CharField( widget=forms.PasswordInput, min_length=8, ) models.py class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.title class FavoriteGames(models.Model): game = models.ForeignKey('Games') user = models.ForeignKey(settings.AUTH_USER_MODEL) -
Django: edit related popup not closing
After upgrading from Django 1.4 to 1.7.11 the related popup window fails to close due to a JavaScript error TypeError: opener.dismissEditRelatedPopup is not a function This function is defined in related-widget-wrapper.js which is successfully loaded when the popup opens. function dismissEditRelatedPopup(win, objId, newRepr) { objId = html_unescape(objId); newRepr = html_unescape(newRepr); newRepr = newRepr.replace(/</g, '&lt;'); newRepr = newRepr.replace(/>/g, '&gt;'); var name = windowname_to_id(win.name).replace(/^edit_/, ''); var elem = document.getElementById(name); if (elem && elem.nodeName == 'SELECT') { var opts = elem.options, l = opts.length; for (var i = 0; i < l; i++) { if (opts[i] && opts[i].value == objId) { opts[i].innerHTML = newRepr; } } } if( $("a#edit_"+elem.id).text().indexOf("General Info") !=-1 || $("a#edit_"+elem.id).text().indexOf("Tool") !=-1){ $("input.edit_"+elem.id).attr('value', objId); $("input.edit_"+elem.id).trigger('change'); } else { $("#"+elem.id).trigger('change', newRepr); } win.close(); }; The django snippet used can be found here: