Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'request' is not defined, in Django forms
How do I get the current logged in user in forms.py? I am trying to pre-populate the email field of the current user. class ContactMe(forms.Form): name = forms.CharField(label = "Name") email_address = forms.CharField(label = "Email Address", intital = request.user.email) subject = forms.CharField(label = "Subject") message = forms.CharField(label = "Message", widget=forms.Textarea(attrs={'cols': 10, 'rows': 3})) additional_comments = forms.CharField(required = False) class Meta: model = Contact_me I tried passing request from views.py as : contact_form = ContactMe(request.POST or None, request) and then receiving the request inside of class ContactMe as : class ContactMe(forms.Form, request): name = forms.CharField(label = "Name") email_address = forms.CharField(label = "Email Address", intital = **request.user.email**) subject = forms.CharField(label = "Subject") message = forms.CharField(label = "Message", widget=forms.Textarea(attrs={'cols': 10, 'rows': 3})) additional_comments = forms.CharField(required = False) class Meta: model = Contact_me It throws the error NameError: name 'request' is not defined. I know request is accessible in html, models.py, views.py. How to get it in forms.py? -
django-cors-headers not working when i18n is on
I have a working environment with: django==1.10 django-rest-framework==3.5.3 djangorestframework-jsonapi==2.1.1 channels (latest) daphne (latest) instead of gunicorn. I'm using nginx as a proxy server above daphne, inside a docker environment. I'm building a separate angular 2 SPA that connects to the above backend and I'm using django-cors-headers==2.0.2 to allow connections from that web app. It works with: USE_I18N = False It works fine when I set Django's USE_I18N = False. When trying to authenticate against the backend, I send a POST request that nginx logs as: POST /api/auth/login/ HTTP/1.1" 200 256 "http://localhost:8080/account/login" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "-" I receive the JWT Token that I am supposed to receive. All works fine. It fails with: __USE_I18N = True However, the same connection fails when USE_I18N = True. The request is equivalent to: curl -H "Content-Type: application/vnd.api+json" -X POST -d '{"data": {"type": "obtainJSONWebTokens", "attributes": {"email":"admin@email.com", "password":"password"}}}' http://localhost/api/auth/login/ The returned error is: XMLHttpRequest cannot load http://localhost/api/auth/login/. Redirect from 'http://localhost/api/auth/login/' to 'http://localhost/en/api/auth/login/' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect. Relevant settings: INSTALLED_APPS += ( 'corsheaders', ) if DEBUG is True: CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', … -
Having problems with slug Django
Hello I hope somebody can help me with my problem. im trying to implement a like Botton into my site and I managed to but up a likes field in admin (when im on admin page I can select a user and click save and the like numbers will increase on the page and you can see the number of likes). now im trying to but this like button into the site itself so the user can click it but before I do this im trying to make the url for that (site.com/my_profile/70/like/) the number stands for the post id. So I found a tutorial where they are working with slug. I really have a problem to implement this into my code. I get errors all over the place.... So here are my Views: from django.utils.text import slugify from .utils import get_read_time, unique_slug_generator def index (request): return render(request,'pics/pics.html') def upload(request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() #handle_uploaded_file(request.FILES['file']) messages.success(request, 'You did it') return redirect('profile') return HttpResponseRedirect(instance.get_absolute_url()) context = { 'form':form, } return render(request, 'my_profile/upload.html', context) class PostLikeRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): slug = self.kwargs.get("slug") print(slug) obj = get_object_or_404(Post, slug=slug ) url_ =obj.get_absolute_url() return url_ so … -
Connect to SQL server using Django(pyodbc)
I tried to connect to exist SQL server, and it actually read data from db. But when I tried to modify the generated inspectdb of models, there show the following error. File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Users\max\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sql_server\pyodbc\base.py", line 539, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: ('42S01', "[42S01] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]��Ʈw���w�g���@�ӦW�� 'AOI' ������C (2714) (SQLExecDirectW)") Google told that the table name already exists: This can happen if the script you are running is creating a table that already exists in the database. It does not usually make sense to generate tables as part of your load test. Instead you should create the tables just once and then populate & query them etc during the test. If however you do want to run a test in which you keep generating new tables before populating them then you need to ensure the table names are unique each time. But I just modify some field name in the models.py. This … -
Django: ValueError (must be a category instance) when saving a ModelMultipleChoiceField with CheckboxSelectMultiple based on a ForeignKey to my Form
I'm getting a ValueError: Cannot assign "[Category: cat1],[Category: cat2] ": "ProfileUser.chosencategories" must be a "Category" instance. When attempting to save my ModelForm. My form is as follows: class ProfileUserForm(forms.ModelForm): class Meta: model = ProfileUser fields = ('field1', 'field2','field3','field4', 'chosencategories') chosencategories = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all(), to_field_name="name") My View is: @login_required def create_user_profile(request): user = request.user if request.method=='POST': profile_user_form=ProfileUserForm(request.POST) if profile_user_form.is_valid(): new_user_profile=profile_user_form.save(commit=False) new_user_profile.user=user new_user_profile.save() return render(request, 'accounts/user_profile_registered.html', {'new_user_profile':new_user_profile}) else: profile_user_form=ProfileUserForm() return render(request, 'accounts/create_user_profile.html', {'profile_user_form':profile_user_form}) My Models are: class ProfileUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) field1 = models.CharField(max_length=155, blank=True) field2 = models.CharField(max_length=155, blank=True) field3 = models.DateField(blank=True) field4 = models.CharField(max_length=255, blank=True) chosencategories=models.ForeignKey(Category, blank=True, null=True, related_name='categorieschosen') def __str__(self): return self.user.username class Category(models.Model): name=models.CharField(max_length=100, choices=CATEGORIES) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name I want to allow users to select multiple instances of the Category object and have these instances saved to their profile within the chosencategories attribute. I have set up the Models and Form Fields to that effect. I have looked at the following questions: Django form not saving with ModelChoiceField - ForeignKey Django: ValueError when saving an instance to a ForeignKey Field How to solve ValueError When save ModelMultipleChoiceField in ModelForm? All of which touch on the topic without providing a clear cut solution. … -
Update the list with Django Channels
I have model "Project" with 'members' ManyToMany field. List of members with there roles in the current project user can see in the page. Is it possible to show new members after adding them without resfresh the page. I am tring to add async to my project with Django Channels. Is it possible? models.py: class Project(models.Model): members = models.ManyToManyField(User, through='Member', help_text=_('Members')) ROLE_CHOICES = ( ('manager', _('Manager')), ('developer', _('Developer')), ('business_analyst', _('Business Analyst')), ('system_analyst', _('System Analyst')), ) class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES) .html {% for member in project.member_set.all %} {{ member.user }} {{ member.role }} {% endfor %} -
What exception type should I raise if my dictionary is missing required keys?
I am testing that data (dictionary), used in Django's render(request, url, data), has some required keys. I will raise an exception if the required keys are missing. What exception type is best suited for this? Is there a better way to think about this? -
Increase the point of inviter after he/she has referred other
How can i increase the point of inviter when he has referred other to join. Point will be increase when refer is accepted. I could make the referral but could not increase the point when refer is accepted by the user to whom the refer was send by inviter. Here is my code class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_("e-mail Address")) invite_code = models.UUIDField(default=uuid.uuid4, unique=True) points = models.PositiveIntegerField(default=5) request_approved = models.BooleanField(default=True, verbose_name=_('request accepted')) def __str__(self): return "Invite: {0}".format(self.email) class Referral(models.Model): referred_by = models.ForeignKey(Invitation, related_name="sharer", null=False, blank=False) referred_to = models.EmailField(unique=True, null=False, blank=False) refer_code = models.UUIDField(default=uuid.uuid4, unique=True) refer_accepted = models.BooleanField(default=False) def referInvitation(request, invite_code): try: # invite_id = request.session['invite_id'] obj = Invitation.objects.get(invite_code=invite_code) except: obj = None form = ReferForm(request.POST or None) if form.is_valid(): referred_to = form.cleaned_data.get('referred_to') print ('referred_to', referred_to) if not obj == None: new_refer = Referral(referred_by=obj, referred_to=referred_to) new_refer.save() subject = "Request to Join Connyct" from_email=None message = "You have been invited by {0}".format(obj.email) to_email=[referred_to] send_mail(subject, message, from_email, to_email, fail_silently=True) context = {"form": form} return render(request, 'refer/refer.html', context) -
Python run from subdirectory
I have the following file hierarchy structure: main.py Main-- A-- a.py b.py c.py B-- a.py b.py c.py C-- a.py b.py c.py From main.py I would like to execute any of the scripts in any of the subfolders. The user will pass on a string A_a.py or B_a.py. The string will be parsed and changed into A/a.py or B/a.py I would like the approach to be dynamic, such that adding any subfolder for e.g. D with a.py, b.py and c.py would directly adapt without forcing any import lines to the main.py script. Is it possible? -
MySQL lite django multitables
I am working on a project from school and one of the questions is List all leagues with a (current) player named "Sophia". I have been able to get all the leagues period, and all the players name Sophia. How ever I cannot seem to figure out how to start in the last table where the first name is reference the first table where the leagues are to get the answer I need. I am hoping someone can see what I am having issues seeing. I have linked the models and views below. Manage.py from django.db import models class League(models.Model): name = models.CharField(max_length=50) sport = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Team(models.Model): location = models.CharField(max_length=50) team_name = models.CharField(max_length=50) league = models.ForeignKey(League, related_name="teams") class Player(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) curr_team = models.ForeignKey(Team, related_name="curr_players") all_teams = models.ManyToManyField(Team, related_name="all_players") views.py from django.shortcuts import render, redirect from .models import League, Team, Player from . import team_maker def index(request): context = { "leagues": League.objects.all(), "teams": Team.objects.all(), "players": Player.objects.all(), "baseball" : League.objects.filter(sport__contains="Baseball"), "women" : League.objects.filter(name__contains="Womens'"), "ice" : League.objects.filter(sport__contains="ice"), "nofootball" : League.objects.exclude(sport__contains="football"), "conferences" : League.objects.filter(name__contains="conference"), "atlantic": League.objects.filter(name__contains="Atlantic"), "teamdallas": Team.objects.filter(location__contains="Dallas"), "raptor": Team.objects.filter(team_name__contains="Raptor"), "cityloc": Team.objects.filter(location__contains="city"), "startT": Team.objects.filter(team_name__startswith="T"), "abc": Team.objects.order_by('location'), "cba": Team.objects.order_by('location').reverse(), "cooper": Player.objects.filter(last_name="Cooper"), "joshua": Player.objects.filter(first_name="Joshua"), … -
Django input_formats removes help_text? I want only to change the way one DateField is displayed
My Problem My problem is that when setting an input_formats on my AbonnentForm(ModelForm) in forms.py, the model's help_text is not displayed in the HTML form. I want only to change the way one DateField is displayed. What am I doing wrong? My Code This is my models.py (shortened) from django.db import models class Abonnent(models.Model): erste_ausgabe = models.DateField(verbose_name="Erste Ausgabe", help_text="Eingabe im Format MM/JJJJ. Zum Beispiel: 01/2018) This is my forms.py (complete) from django.forms import ModelForm, DateField, DateInput from .models import Abonnent class AbonnentForm(ModelForm): # WHEN I ADD THE FOLLOWING LINE, THE HELP_TEXT IS NOT DISPLAYED UNDER THE HTML-FORM erste_ausgabe = DateField(input_formats=['%m %Y'], widget=DateInput(format='%m-%d-%Y')) class Meta: model = Abonnent fields = '__all__' And this is my template (shortened) <div class="col-sm"> <label class="col-form-label" for="{{ form.erste_ausgabe.id_for_label }}">{{ form.erste_ausgabe.label }}</label> <input id="{{ form.erste_ausgabe.id_for_label }}" class="form-control" type="text" name="{{ form.erste_ausgabe.html_name }}" placeholder="" aria-describedby="{{ form.erste_ausgabe.id_for_label }}Help"> {% if form.erste_ausgabe.help_text %}<small id="{{ form.erste_ausgabe.id_for_label }}Help" class="form-text text-muted">{{ form.erste_ausgabe.help_text }}</small>{% endif %} </div> -
call java api from django post_save signal
I am working on a django project in which I am trying to update the database field values in save function and also call a java API in which I am updating some other fields of the same table. The problem I got was that django kept the db lock to itself and didn't let the API update the fields. To solve this problem I have thought of using the post_save signal to call the java API but I am facing some issues. Below is my piece of code: models.py of City app class User(models.Model): city = models.ForeignKey(City) expiry_time = models.FloatField(default=0.0, verbose_name="Expiry Time(in Mins)", validators=[decimal_validation], blank=True) created_by = models.CharField(max_length=30, default='', null=False) created_at = models.DateTimeField(auto_now_add=True, default=timezone.now(), editable=False) def __unicode__(self): return "%s" % (unicode(self.id)) def save(self, *args, **kwargs): data = json.loads(serializers.serialize("json", [self, ]))[0] pk = self.pk super(User, self).save(*args, **kwargs) data["fields"]["id"] = self.id changed = 0 data["fields"]["email"] = data["fields"]["created_by"] if pk is not None: prev_user = User.objects.get(pk=self.pk) if(prev_user.city != self.city): changed = 1 data = dict_to_camel(data["fields"]) //I want to send data variable to the service api. @receiver(post_save, sender=User) def call_service(sender, instance, created, **kwargs): service_api(json.dumps(data), 'application/json', UPDATE_USER) //this data should be provided by the save method. class Meta: db_table = 'user' managed = False … -
Django-oscar multi vendor
I am building a e-commerce website in python using Django-oscar library. what i want to do in it is that there are multiple vendors that can sell there own products and can link there own bank accounts with it. Is it possible in oscar. I am building website like amazon and ebay. but on much smaller scale. where there are multiple vendors/sellers and buyers.. anyone can buy and sell items there.. B2b and B2c is allowed on website. -
Django rest framework : How to serve binary directly in the body
I need to return an Image (binary) directly in the body request, but i get in response a generated file with no extension and an empty array/json inside... I'm using python 3, Django==1.10.5 and djangorestframework==3.5.3, drf-extensions==0.3.1 (for the nested routes) and django-extra-fields==0.9 for the ImageField. (I have try without django-extra-fields, it's the same) I have allready a solution (thx a lot Enix ;p) with the base64 here :Django rest framework : How to download image with this image send directly in the body But my boss doesn't want base64 and just want the binary inside the body response. My models.py class Image(models.Model): class Meta: verbose_name = _('Image') verbose_name_plural = _('Images') creation_date = models.DateTimeField( help_text=_('Creation date'), auto_now_add=True, editable=False ) modified_date = models.DateTimeField( help_text=_('Last modification date'), auto_now=True ) image_file = models.ImageField(upload_to='', null=True) My serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image_file',) My views.py class ImageViewSet(NestedViewSetMixin, viewsets.ModelViewSet): http_method_names = ['get', 'put'] queryset = Image.objects.all() serializer_class = ImageSerializer pagination_class = None def get_queryset(self, *args, **kwargs): image = Image.objects.last() # This is just for the exemple. filename = image.image_file size = filename.size response = FileResponse(open(filename.path, 'rb'), content_type="image/png") response['Content-Length'] = size response['Content-Disposition'] = "attachment; filename=%s" % 'notification-icon.png' return response I have made some … -
Run value through function
I have the following management command in Django which updates a record with data from an external source: class Command(BaseCommand): def handle(self, *args, **options): field_mappings = { 'first_name': 'Voornaam', 'initials': 'Voorletters', 'last_name_prefix': 'Voorvoegsel', 'last_name': 'Achternaam', 'sex': 'Geslacht', 'DOB': ['Geboortedatum', 'convert_DOB'], 'street': 'Straat', 'house_number': 'Huisnummer', 'zipcode': 'Postcode', 'city': 'Woonplaats', 'country': 'Land', 'phone_number': 'Telefoonnummer', 'phone_number_mobile': 'MobielTelefoonnummer', 'email_address': 'Emailadres', 'insurer_name': 'NaamVerzekeraar', 'insurance_policy_number': 'PolisnummerVerzekering', 'gp_name': 'NaamHuisarts', } patients = Patient.objects.all() for patient in patients: result = Query(patient.pharmacy, 'patient_by_bsn', {'BSN': patient.BSN}).run() for x, y in field_mappings.items(): if type(y) == list: pass else: setattr(patient, x, result[y]['0']) patient.save() print('Patient {}-{} updated'.format(patient.pharmacy.vv_id, patient.vv_id)) @staticmethod def convert_DOB(value): return timezone.datetime.utcfromtimestamp(value).date() Most fields can be saved without converting the data first, but some fields like the DOB need converting (in this case from a UNIX timestamp to a Python datetime.date). Where it currently says pass underneath if type(y) == list I want to run the value through the listed function first so that it would save convert_DOB(value) instead of the original value - how can I do this? -
Django Error : 'No module named django.sessions'
I'm getting an error in my Django Project and I would like to find a solution. I developped my project with MySQL Database, but after some discussions, I would like to replace MySQL by NoSQL Database (and Django ORM commands by Django MongoDB commands) like MongoDB for different reasons : Ability to handle billions lines Ability to make Big Data (Hadoop, ...) My Django project settings looks like : import mongoengine from mongoengine import connect AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy' } } MONGO_DATABASE_NAME = 'XXX' MONGO_HOST = '172.30.10.X' MONGO_PORT = 27017 connect(MONGO_DATABASE_NAME, host=MONGO_HOST, port=MONGO_PORT) And, when I run : python manage.py runserver I get : System check identified 1 issue (0 silenced). March 20, 2017 - 10:33:20 Django version 1.10.3, using settings 'Etat_civil.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function wrapper at 0x104994140> Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 142, in inner_run handler = self.get_handler(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/usr/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", … -
Django, mysql ; Error loading MySQLdb module
I just tried to checkout a project, I was working on, from github, on my laptop(windows 10, pycharm). I installed every library, and connectors it needed to run, try to runserver and get this: Unhandled exception in thread started by <function wrapper at 0x046FDEF0> 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:\Python27\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python27\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python27\lib\site-packages\django\db\__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python27\lib\site-packages\django\db\utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Python27\lib\site-packages\django\db\utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 28, in <module> raise ImproperlyConfigured("Error loading MySQLdb … -
Gunicorn doesn't find a module
I have Django app on Ubuntu 16.04, and have virtualenv with all the packages installed. When I run the project using the regular python manage.py runserver 0.0.0.0:8000 everything works fine. But when using gunicorn with the following command, it doesn't work: gunicorn --bind 0.0.0.0:8000 <project_name>.wsgi:application The error is: ImportError: No module named 'bootstrapform' The INSTALLED_APPS in settings.py looks like: INSTALLED_APPS = [ .... "bootstrapform", .... ] I'm not sure what the reason could be for this error because the python manage.py runserver works (and the website is displayed correctly), but gunicorn doesn't work. Both commands (the manage.py and the gunicorn) are run from the virtualenv environment. Opening a python console and doing import bootstrapform works fine. -
Wagtail - more class arguments than parameters? Whats going on?
Hi Stackoverflow Community I have been trying to understand how Django (and Wagtail's Stream-field) work under the hood. Doing that I learned about metaclasses and believe to have a handle on the principle. There is however one piece of code that confuses me (see below). When we follow the StreamField definitions this code seems to pass a list of tuples to a class constructor that doesn't appear to accommodate for a list of this kind. How can this work? Any advice would be highly appreciated. Here the code: models.py This is where we define the StreamField. It takes a list of tuples of format ('title', blockType). Our objective is to follow the StreamField call: class BlogPage(Page): blogElement = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.TextBlock()), ('picture', ImageChooserBlock()), ], default=[]) fields.py>StreamField When we follow the call to StreamField we arrive at the following class constructor. Here the call to StreamBlock(block_types) is where it gets confusing: class StreamField(models.Field): def __init__(self, block_types, **kwargs): if isinstance(block_types, Block): self.stream_block = block_types elif isinstance(block_types, type): self.stream_block = block_types() else: self.stream_block = StreamBlock(block_types) super(StreamField, self).__init__(**kwargs) StreamBlock While the call to the class constructor takes block_types as an argument (contains a list of three tuples defined in models.py) the … -
Django CMS Error 1364, "Field 'file' doesn't have a default value"
Every time I try to add a new File (or Image as Plugin file from Django CMS) I get the error: (1364, "Field 'file' doesn't have a default value") I think it may be an error of MySQL 5.7. Recently I've upgrade my environment from mysql 5.6 to mysql 5.7 Any suggestion? Thank you. Environment Python version: 2.7.10 Django version: 1.9.12 django CMS version: 3.4.2 -
What is Queryset & Difference between filter() and get() in the django models
i'm going through the django official doc can you explain me what's the difference between the filter and get , i guess it is similar to where clause in sql something like this : "select * from table where id='1' " also please clarify the Queryset what its significance . >>> Question.objects.filter(id=1) <QuerySet [<Question: What's new?>]> >>> Question.objects.get(pk=1) <Question: What's new?> -
Django ORM: Override realted_name of Field in Child Class
I get this exception: django.core.exceptions.FieldError: Local field 'ticket' in class 'SpecialPlugin' clashes with field of similar name from base class 'BasePlugin' Here are my models: class BasePlugin(models.Model): ticket = models.OneToOneField('foobar.ticket', primary_key=True, related_name='%(app_label)s_%(class)s') class Meta(IndexImplementation.Meta): abstract = True class SpecialPlugin(BasePlugin): ticket = models.OneToOneField('foobar.ticket', primary_key=True, related_name='special') I only found this note, but in my case the parent class is abstract. I am unsure if it applies here. I want to give the child class SpecialPlugin the related name "special" since the related name (%(app_label)s_%(class)s) of the BasePlugin would break old code. Is there a way to give SpecialPlugin.ticket the related_name "special"? -
Ignore null values in descending order using Django Rest Framework
I am using Django for my website, and hence decided to use Django Rest Framework for building my REST APIs. For a particular model, i want to filter on a text field (using SearchFilter for that), filter on a few categorical fields (FilterBackend with a FilterSet defined) and be able to order data based on some fields (OrderingFilter for this). class StatsAPI(generics.ListAPIView): model = Stats queryset = Stats.objects.all() serializer_class = StatsSerializer filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter) filter_class = StatsFilter pagination_class = StatsPagination ordering_fields = ('__all__') search_fields = ('display_name') The issue i am facing is with my ordering fields as they also contain nulls. Ordering in ascending order works fine. However ordering in descending order (www.example.com/api/stats/?ordering=-appearance), pushes the null values to the top. How do i ignore the null values when using descending order? The number of fields on which ordering can be performed are roughly 20 in number. -
Thumbnail created on image upload is saved twice (duplicate thumbnail)
I have created an AbstractUser -model to extend the default User -model. When a new user is created, an avatar image is uploaded and the AbstractUser -model automatically creates also a thumbnail-image. Model works fine except I get 2 thumbnail images in my folder. The other one is named somename_thumbnail and the other as somename_thumbnail(+some-random-characters). What is causing this? My problem might be similar to this problem where the answer suggests to put an if-clause on self.create_thumbnail(). What should I check on that if-clause before creating the thumbnail? Below is the code for my AbstractUser -model: class SiteUser(AbstractUser): user_avatar = models.ImageField(upload_to="avatar/", blank=True) user_avatar_thumb = models.ImageField(upload_to="avatar_thumb/",null=True, blank=True) def natural_key(self): avatar_path = self.user_avatar avatar_path = str(avatar_path) return (self.username, self.pk, avatar_path) def create_thumbnail(self): # original code for this method came from # http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/ # If there is no image associated with this. # do not create thumbnail if not self.user_avatar: return from PIL import Image from cStringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFile import os # Set our max thumbnail size in a tuple (max width, max height) THUMBNAIL_SIZE = (200,200) if self.user_avatar.name.endswith(".jpg"): PIL_TYPE = 'jpeg' FILE_EXTENSION = 'jpg' DJANGO_TYPE = 'image/jpeg' elif self.user_avatar.name.endswith(".png"): PIL_TYPE = 'png' FILE_EXTENSION = 'png' DJANGO_TYPE = 'image/png' … -
django rest framework: conditionally choosing serializer from same model
My model formula.py TYPE_CHOICES = [ ('new',), ('existing',), ] user = models.ForeignKey("users.User") type = models.CharField( max_length=10, choices=TYPE_CHOICES, ) name = models.CharField(u"처방명", max_length=20) reference = models.CharField( max_length=20, blank=True, null=True, ) base_formula = models.CharField( max_length=40, blank=True, null=True, ) formula_line.py herb_item = models.ForeignKey("herbs") formula = models.ForeignKey("formulas") quantity = models.SmallIntegerField() I want to serializer the model to be in the following form. Output # Use the type field to separate objects. Objects have difference { 'new': { { 'user': UserId1, 'base_formula': string, 'formula_id': int, }, { 'user': UserId2, 'base_formula': string, 'formula_id': int, }, { 'user': UserId3, 'base_formula': string, 'formula_id': int, }, }, 'existing': { { 'name': string, 'reference': string, 'formula_id': int, }, { 'name': string, 'reference': string, 'formula_id': int, }, { 'name': string, 'reference': string, 'formula_id': int, }, } } I have been searching through SOF and reading the doc for some time, but I cannot find a way to do this. I have the faintest idea that I probably should either: override get_serializer_class somehow override __init__ But I really cannot think of a way to implement this. Please note that I thought about dividing the model into NewFormula and ExistingFormula, and use two different serializers accordingly. But this was not possible because I …