Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Task is to export excel to MySQL...!
Requirement: Excel workbook with formulae needs to be exported to MySQL and display graphs. Few columns are dependent on other so every time user performs any CRUD operation simultaneously other dependent columns need to be updated and the graphs as well..! I am using python, django, MySQL and angularJS. Is this possible...? Any ideas..? -
Hello want to encrypt my password using a cer file then encode to base 64 using python 3.4.0. How can I achieve this
want to encrypt my password using a cer file then encode to base 64 using Python 3.4.0. How can I achieve this? -
Receiving no data for PATCH when sending a mulitpart request
I have been working on using viewsets using Django Rest Framework, but when I am running a test for PATCH, I'm getting no data. Here is the test I am running: def create_random_image(self): ''' Create a random image ''' tmp_img = tempfile.NamedTemporaryFile(suffix='.png') size = (600, 600) img = Image.new("RGB", size) draw = ImageDraw.Draw(img) draw.text((300, 300), "HELLO WORLD", fill=(255, 200, 10)) draw.text((300, 250), "HELLO WORLD", fill=(255, 200, 10)) draw.text((200, 220), "HELLO WORLD", fill=(255, 200, 10)) img.save(tmp_img, 'PNG') del draw tmp_img.seek(0) return tmp_img def test_marketing_banner_patch_working(self, mockToken): ''' Test if marketing PATCH api is working ''' post_url = reverse('marketing:banner_create') url = reverse('marketing:banner_update', kwargs={'pk': 1}) self.client.login( username='developers@solaranalytics.com.au', password='dZZGhMLxkHXnauXMk0ID') tmp_img = self.create_random_image() tmp_img2 = self.create_random_image() tmp_img3 = self.create_random_image() post_data = { 'reseller_id': 1, 'name': 'TestRes', 'banner_enabled': True, 'desktop_img': tmp_img, 'mobile_img': tmp_img2, 'tablet_img': tmp_img3 } post_response = self.client.post( post_url, data=post_data, format='multipart') tmp_img = self.create_random_image() patch_data = { 'reseller_id': 1, 'name': 'TestRes2', 'banner_enabled': False, 'desktop_img': tmp_img, } response = self.client.patch( url, data=patch_data, content_type='multipart/form-data; boundary=BoUnDaRyStRiNg', format='multipart') self.assertNotEqual(response.status_code, 404) self.assertEqual(response.status_code, 200) banner = MarketingBanner.objects.filter(reseller_id=1).first() self.assertIsNotNone(banner) self.assertEqual(banner.reseller_id, 1) self.assertEqual(banner.name, 'TestRes2') self.assertFalse(banner.banner_enabled) self.assertIsNotNone(banner.desktop_img) self.assertIsNotNone(banner.mobile_img) self.assertIsNotNone(banner.tablet_img) self.assertIsNone(banner.description) self.assertIsNone(banner.external_link) self.assertIsNone(banner.title) When I print request.data in the method it just shows an empty dictionary. Even when trying the base method from the ModelViewSet, it … -
ReactJS app translation from outer html/JS
I am using Django for backend and Django template in the front-end. I am going to refactor the front-end of a major part of my website (accessible through a link in the header) and rewrite it in ReactJS. What I plan to do is to keep the header and footer as it is (render using django template), and rewrite the view in the middle part using React. The problem is that my buttons for switching languages are in the header. When a user clicks those buttons in the header, I would want the part written in ReactJS to change its language as well. I have done some research and it seems that React props can only be passed between React components and that I cannot pass an outer variable (that specifies the language selected) into the ReactDOM.render() function. Is it possible to achieve i18n for my React app according to my planned structure, or is another solution required? Thank you. -
ImportError: No module named diversely.settings.dev
I've just completed a django tutorial, and after creating a settings folder and reconfiguring my database in my base.py, my website isn't loading, and I'm getting an ImportError. Any thoughts? Here's the traceback: Traceback (most recent call last): File "/Users/m.zayas/Desktop/env1/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/m.zayas/Desktop/env1/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named diversely.settings.dev Here is my base.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_h0tyj2^#5x2jh$9!&p0589-zop-0aiwok)x(sf+u-jjhw9l*o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'diversely.middleware.LoginRequiredMiddleware' ] ROOT_URLCONF = 'diversely.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')], 'APP_DIRS': True, 'OPTIONS': { … -
Django Collectstatic in Amazon Elastic Beanstalk Not Working
I have deployed my Django app in amazon elastic beanstalk. However, the css in the django admin is not working. I understand that it's a collectstatic issue. This is what my settings.py looks like: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' And I have this line in my ebconfig.config file: container_commands: 01_collectstatic: command: "python manage.py collectstatic --noinput" However, this is how it looks like once I deploy it in amazon: I have tried seeing the log files in amazon console. I found a line that reads: EmbeddedPostBuild/postbuild_0_dcape/Command 01_collectstatic] : Starting activity... ..... 0 static files copied to '/opt/python/bundle/33/app/static', 102 unmodified. What do I need to do to make sure it works? -
Django - reload only body page using block not refresh whole page
below code is my base.heml <body class="skin-red"> <!-- Site wrapper --> <div class="wrapper"> <!-- #HEADER --> {% include 'HEADER.html' %} <!-- /#HEADER --> <!-- #SIDEBAR --> {% include 'SIDEBAR.html' %} <!-- /#SIDEBAR --> <!-- #BODY --> {% block content %} {% endblock %} <!-- /#BODY --> <!-- #FOOTER --> {% include 'FOOTER.html' %} <!-- /#FOOTER --> {% block extrajavascript %} {% endblock %} </body> below code is HEADER.html <header class="main-header"> <a href="/rm" class="logo"><b>Resource</b> Monitor <i class="fa fa-bar-chart-o" style="color:#ffd400"></i></a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top" role="navigation"> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> </a> <ul class="nav navbar-nav"> <li><a href="/rm">Home <span class="sr-only">(current)</span></a></li> <li><a href="/rm/pcinfo"> PC information </a></li> <li><a data-toggle="tab" href="#tab_sysuse">??? ???</a></li> <li><a data-toggle="tab" href="#tab_procuse">???? ???</a></li> <li><a data-toggle="tab" href="#tab_prodet">???? ????</a></li> <li><a data-toggle="tab" href="#tab_sdwt">SDWT ????</a></li> <li><a data-toggle="tab" href="#tab_pcevents">??? ?? ??</a></li> <li><a data-toggle="tab" href="#tab_winevents">??? ?? ID? ??</a></li> <li><a data-toggle="tab" href="#tab_agentinfo">Agent ????</a></li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Email ?? ?? <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a data-toggle="tab" href="#tab_emailconfigs">??? ??</a></li> <li><a data-toggle="tab" href="#tab_emailreceiver">??? ??</a></li> </ul> </li> </ul> </nav> </header> when I click header tab menu, I want to reload only {% block content %} {% endblock %} not whole pages.. but now It reloaded the whole page.. There are … -
Prospect matching query does not exist
i am new in django and i am stuck with this form problem. I have no idea what the error means. Prospect matching query does not exist. it says the error occurs here: if form.is_valid(): here's my files: forms.py class ProspectForm(forms.ModelForm): full_name = forms.CharField( label="Full Name", max_length=120, required=False, ) email = forms.EmailField( label="E-mail", max_length=120, required=False, ) contact_number = forms.CharField( label="Contact Number", max_length=14, required=False, ) def clean_email(self): email = self.cleaned_data.get('email') try: Prospect.objects.get(email=email) raise forms.ValidationError('This email is taken') except VendicsUser.DoesNotExist: return email def clean_number(self): number = self.cleaned_data.get('number') validate_integer(number) try: Prospect.objects.get(contact_number=number) raise forms.ValidationError('This number is taken') except VendicsUser.DoesNotExist: if len(number) < 11: return number else: raise forms.ValidationError('Number is too short') def __init__(self, *args): self.helper = FormHelper() self.helper.form_tag = False self.helper.form_class = 'contact_form' self.helper.form_action = '' self.helper.layout = Layout( Field('full_name', css_class='form_fields'), Field('email', css_class='form_fields'), Field('contact_number', css_class='form_fields'), Hidden('sub_domain', ''), FormActions( Submit('submit', 'SUBMIT', css_class='form_button'), ) ) super(ProspectForm, self).__init__(*args) class Meta: model = Prospect exclude = ['user'] views.py def landingpage(request, subdomain=None): form = ProspectForm(request.POST or None) if form.is_valid(): form.save(commit=False) # for future changes form.save() return redirect('' + subdomain + '/') context = { 'subdomain': subdomain, 'form': form, } user = get_object_or_404(WebDetail, domain=subdomain) return render(request, "landingpage/landingpage.html", context) -
Set default value to a ForeignKey Field based on data-table row clicked
I have 2 data-table in my app, onClick on any of the project-content-datatable row will display its child content on a second table (Content Table), Now in my second table I have a button to pop-up a form in modal to create new content in it, In that form how I can set the default value of the parent_project_content = models.ForeignKey(ProjectContent, on_delete=models.CASCADE) based on which row project-content-datatable user click at. Any help is much appreciated, Thank you Here is my code HTML <table id="project-content-datatable" class="display table table-hover table-responsive" style="width: 100%"> <thead> <tr> <th class="small text-muted text-uppercase"><strong>Name</strong></th> <th class="small text-muted text-uppercase"><strong>Description</strong></th> </tr> </thead> <tbody> {% for content in content_list %} {% if content.search_type.name == searchtype.name %} <tr class="text-primary"> <td class="text-left" style="cursor: pointer" onclick='load_workorder({{ content.id }});'> {{ content.id }} </td> <td class="text-left" style="cursor: pointer" onclick='load_workorder({{ content.id }});'> {{ content.name }} </td> </tr> {% endif %} {% endfor content_list %} </tbody> </table> <!-- END Hover Table --> <!-- WORKORDER START--> <h3 class="panel-title text-white">WorkOrders</h3> <div class="btn-group" role="group" aria-label="..."> <button data-toggle="modal" data-target="#create_new_workorder" type="button" class="btn btn-sm btn-success btn-outline"><span class="hidden-md hidden-sm hidden-xs">Create Workorder</span> <i class="fa fa-fw fa-plus"></i> </button> </div> <!--Create Workorder Form Modal --> <div class="modal fade" id="create_new_workorder" tabindex="-1" role="dialog" aria-labelledby="TitleLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div … -
django how add extra arguments in the generic class
Sometime ago I made a simple blog app with comment feature in each article. Everything works fine. Here is my models, urls, view, and template : # model: class Article(models.Model): ...... def get_absolute_url(self): return reverse('blog:article_detail', kwargs={'slug': self.slug}) # urls: url(r'^article/(?P<slug>[-\w]+)/$', views.ArticleDetail.as_view(),name='article_detail'), # views: class BlogCommentCreate(LoginRequiredMixin, CreateView): ...... def get_context_data(self, **kwargs): context = super(BlogCommentCreate, self).get_context_data(**kwargs) context['article'] = get_object_or_404(Article, slug=self.kwargs['slug']) return context def form_valid(self, form): form.instance.user = self.request.user form.instance.article = get_object_or_404(Article, slug=self.kwargs['slug']) return super(BlogCommentCreate, self).form_valid(form) # template <a href="{% url 'blog:blog_comment' article.slug %}">Add a new comment</a></p> But when I modified them to this, since I want a full URL of my article: # models: def get_absolute_url(self): return reverse('blog:article_detail', kwargs={ 'year': self.date_created.strftime('%Y'), 'month': self.date_created.strftime('%m'), 'day': self.date_created.strftime('%d'), 'slug': self.slug}) # urls: url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',views.ArticleDetail.as_view(), name='article_detail'), Error appeared: NoReverseMatch at /blog/article/generating-dummy-post/comment/ Reverse for 'article_detail' with arguments '('generating-dummy-post',)' not found. 1 pattern(s) tried: ['blog/article/(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/(?P[-\\w]+)/$'] How can I add these (year, month, day) extra arguments in the article context into my view and template? -
django - create model with initial data using fixtures then have static variables assigned
I have a model that looks like this... class Status(models.Model): status = models.CharField(verbose_name="The Status", max_length=30) def __str__(self): return self.status class Meta: ordering = ('status',) which load initial data from a fixture... [ { "model": "PotatoEngine.status", "pk": 0, "fields": { "status": "None" } }, { "model": "PotatoEngine.status", "pk": 100, "fields": { "status": "Player Status" } }, { "model": "PotatoEngine.status", "pk": 101, "fields": { "status": "Invited" } }, { "model": "PotatoEngine.status", "pk": 102, "fields": { "status": "Accepted" } ] Now that these primary keys are assigned and "static" to the status. I want to use a variable to access these IDs...ie NONE = 0 INVITED = 101 ACCEPTED = 102 Where/how should I store these assignments to be accessible for the entire app. in the settings file? I would really like to read the fixtures file to create the variables, so, in the event I change them, add/...deletee it will be automatically updated. any recommendations. -
Generate and Pass values to Serializer - Django Rest Framework
I'm trying to pass few values from form and other after generating inside the method. I don't know how to do that. Below is what I tried from .serializers import LoginCredSerializer from rest_framework import viewsets from .models import LoginCred import urllib, requests, re import http.cookiejar from rest_framework.response import Response from django.utils.six import BytesIO from rest_framework.parsers import JSONParser class LoginViewSet(viewsets.ModelViewSet): def feed(self, request): stream = BytesIO(request.read()) data = JSONParser().parse(stream) startAddress = "***********************" LoginAddress = "***********************" start_response = requests.get(startAddress) timestamp = re.findall(r'id="loginstamp" value="(\d+)"',start_response.text, re.M|re.I) if timestamp: post_data = { 'allowinsubframe': 'null', 'mobile': 'false', 'login': 'jsp', 'loginstamp':timestamp[0], 'j_username': data['email'], 'j_password': data['password'] } requesting_ism = requests.post(LoginAddress,post_data) LtpaToken="" mycookie="" JSESSIONID="" for res in requesting_ism.history: if res.url==LoginAddress: LtpaToken=res.headers['Set-Cookie'] else: JSESSIONID=res.headers['Set-Cookie'] mycookie=LtpaToken+";"+JSESSIONID csrftoken = re.findall(r'id="csrftokenholder" value="(\S+)"',requesting_ism.text, re.M|re.I) uisessionid = re.findall(r'id="uisessionid" value="(\S+)"',requesting_ism.text, re.M|re.I) save_data = {"ISM_HOST" : data['ISM_HOST'], "email" : data['email'], "LtpaToken2" : LtpaToken, "JSESSIONID" : JSESSIONID, "UISESSIONID" : uisessionid, "CsrfToken" : csrftoken} //////////////////////////////// LoginCredSerializer(data = save_data) doesn't make any sense to me, I'm just using hit and trial method Trying to push save_data to LoginCredSerializer to save this to the database /////////////////////////////// login_cred = LoginCredSerializer(data = save_data) print(login_cred.is_valid()) if login_cred.is_valid(): login_cred.save() return Response(SomeVariable) def data(self, request): print('I will get you data') pass I'm generating extracting JSESSIONID and … -
Gunicorn can't find staticfiles after dockerization
I am using docker 17.05.0-cs edge on Ubuntu 17.04 Zesty. I have a gunicorn/Django app that I built here. It runs fine before being dockerized, but gunicorn can't see the staticfiles after docker build. Here is the Dockerfile: # Dockerfile # FROM base image to build upon FROM phusion/baseimage # RUN install python and pip RUN apt-get update RUN apt-get install -y python python-pip python-dev # ENV set environment directory tree ENV PROJECT=mysite ENV CONTAINER_HOME=/opt ENV CONTAINER_PROJECT=$CONTAINER_HOME/$PROJECT # move to project WORKDIR WORKDIR $CONTAINER_PROJECT # COPY project to container directory COPY . $CONTAINER_PROJECT # RUN pip and install requirements RUN pip install -r requirements.txt # COPY start.sh into known container location COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD execute start.sh to start the server running. CMD ["/start.sh"] # done! I appended the static file url pattern to urls.py, I am certain this has to do with the container build. Perhaps I need to add an environment directory for the static files? Any help is, of course, appreciated. -
django tables 2 Inheritance Not Working Consistently
I have two parent tables, one of which gets inherited properly and the other doesn't, illogically. I've generally accepted that things which work in one case do not tend to work in another identical case since working with django packages like django tables 2, but I figured I'd put this out there just in case somebody knows why in the world it's not being consistent here. I'm using one view, DetailView, with SingleTableMixin. However I am using two tables on the page. AllocationTable and AllocationPropertyDetailTable are the two relevant ones. AllocationTable does not inherit properly, but AllocationPropertyDetailTable inherits properly. class DetailAllocation(SingleTableMixin, generic.DetailView, BudgetUtils): template_name = 'allocation/allocation_detail.html' context_table_name = 'table' model = Allocation table_class = AllocationTable title = 'Allocation Detail' def get_table_data(self): return [self.object] def get_context_data(self, **kwargs): context = super(DetailAllocation, self).get_context_data(**kwargs) context['property_table'] = AllocationPropertyDetailTable([self.object]) context["dates_table"] = generate_dates_table(self.object.this_pay_date) context['identifier_table'] = generate_identifier_table(self.object.transaction_identifiers) return context Here I list the tables, with their parent classes listed first. class CategoryTable(tables.Table): source_account = tables.LinkColumn('accounts:detail', args=[A('source_account.id')]) minimum = CurrencyColumn() additional_amount = CurrencyColumn() class AllocationTable(CategoryTable): name = tables.LinkColumn('budgetcategories:detail_allocation', args=[A('pk')]) class Meta: model = Allocation exclude = ("created", "modified", "polymorphic_ctype", "category_ptr", "allocation_dates", "transaction_identifiers") sequence = ('name', '...') In the above case, source_account renders as a standard column, not a LinkColumn, … -
name 'urlpatterns' is not defined when doing translation (+= i18n_patterns)
I want to add a language prefix in URL patterns just like the django documentation homepage. Following this example my urls.py looks like this: from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from myapp import views from myapp.views import MyFirstView, MySecondView myapp_patterns = [ url(r'^$', views.CategoryView, name='index'), url(r'^(?P<name>[a-zA-Z0-9_]+)/$', MyFirstView.as_view(), name='detail'), url(r'^(?P<name>[a-zA-Z0-9_]+)/mysecond_view/$', MySecondView, name='mysecond_view') ] urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^categories/', include(myapp_patterns)), url(r'^', views.LandingView), ] This works but now when I add += i18n_patterns urlpatterns += i18n_patterns [ url(r'^admin/', admin.site.urls), url(r'^categories/', include(myapp_patterns)), url(r'^', views.LandingView), ] I get the error: NameError: name 'urlpatterns' is not defined I did add the LocalMiddleware: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] as well as this: LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) I don't understand how urlpatterns all of the sudden is not defined anymore. What am I doing wrong here? -
Get the value in the intermediate model in a Through Relationship
As I loop through a Prize.objects.all() set, I am trying to get the quantity value from PrizeItem, but it seems to reference only the GameItem model, not giving access to the intermediate PrizeItem attributes. How do I get access to the Through model's attributes? class GameItem(models.Model): '...' class Prize(models.Model): '...' item = models.ManyToManyField(GameItem, through='PrizeItem') class PrizeItem(models.Model): #relations game_item = models.ForeignKey(GameItem, on_delete=models.CASCADE) prize = models.ForeignKey(Prize, on_delete=models.CASCADE) #Item details quantity = models.IntegerField(null=True, blank=True, default=1) -
explicitly use database-order for many-to-many model relations in Django
I'm trying to get Django to not order many-to-many relations between Creator and Entry models (one creator can have made many entries, and one entry can have many collaborative creators), instead using whatever ordering the database rows are in. Creator has a relatively straight-forward model and manager: class CreatorQuerySet(models.query.QuerySet): def public(self): return self class Creator(models.Model): name = models.CharField(max_length=140) objects = CreatorQuerySet.as_manager() def __str__(self): return str(self.name) and Entry has slightly longer model but similarly straight-forward manager: class EntryQuerySet(models.query.QuerySet): def public(self): approved = ModerationState.objects.get(name='Approved') return self.filter(moderation_state=approved) class Entry(models.Model): title = models.CharField(max_length=140) content_url = models.URLField() creators = models.ManyToManyField( Creator, related_name='entries', blank=True ) moderation_state = models.ForeignKey( ModerationState, related_name='entries', default=get_default_moderation_state, on_delete=models.PROTECT ) objects = EntryQuerySet.as_manager() def __str__(self): return str(self.title) When retrieving Entries, the entry.creators field seems to order itself based on the name of the creators, which is not what I want it to do: I want it to not order at all. For example, if I have two creators (alice with id 1 and bob with id 2) and two entries, where entry 1 has a creators list [alice,bob] and entry 2 has a creators list [bob,alice] then the many-to-many relation in the database is: id | entry | creator ------+-----------+---------- 1 | 1 … -
How to show custom error in the admin
I'm raising an validationError in the pre_save but Whenever I try to create a new object, instead of getting the red error as the others, I get the yellow page with the error. @receiver(pre_save, sender=Student) def student_pre_save(sender,instance, **kwargs): if instance.classroom.student_set.count() == instance.classroom.QttMax_Stu: raise ValidationError("No places left") -
Referencing extended variables from the user model after authentication successful
So, I have extended the base django user model using a one-to-one field: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user') user_avatar = models.ImageField(storage=site_media_upload_location, null=True, blank=True) Upon authentication the following displays correctly other than the user_avatar variable from the user model: {% if request.user.is_authenticated %} <div class="user"> <div class="user-image"> <img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.userprofile.user_avatar.url }}" alt="User Avatar"> </div> <div class="dropdown user-dropdown"> Hello, <a href="#" aria-expanded="true">{{ request.user.first_name }}<i class="fa fa-caret-down" aria-hidden="true"></i></a> <ul class="sub-menu text-left"> <li><a href="#">My Profile</a></li> <li><a href="#">Settings</a></li> <li><a href="#">Log Out</a></li> </ul> </div> </div> {% else %} Do something else {% endif %} My MEDIA_URL is defined in the settings.py file as MEDIA_URL = "/site_media/" This is purely where every "users" avatar will be stored for development purposes. I've tried a few combinations, none of which seem to work: <img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.userprofile.user_avatar.url }}" alt="User Avatar"> ...and this... <img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.userprofile.user_avatar.url }}" alt="User Avatar"> ..and this... <img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.user_avatar.url }}" alt="User Avatar"> If anyone knows how I can reference the variables of an extended model after authentication success I would be greatly appreciative! -
Django Rest Framework: Unclear error message
I have: class user_password(generics.UpdateAPIView): authentication_classes = ([JSONWebTokenAuthentication]) serializer_class = user_password_serializer def get_queryset(self): return User.objects.get(id=self.request.user.id) But I'm getting this when running it: AssertionError: Expected view user_password to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I know the serializer is okay because when I use a different type of View for the same thing. It works: class user_password(APIView): authentication_classes = ([JSONWebTokenAuthentication]) def put(self, request, format=None): serializer = user_password_serializer(data=request.data) if serializer.is_valid(): if request.user.check_password(serializer.validated_data[ 'old_password']): request.user.set_password(serializer.validated_data[ 'new_password']) request.user.save() return Response({'success': True, 'result': serializer.validated_data}, status=status.HTTP_200_OK) else: return Response({'success': False, 'result': "credential mismatch"}, status=status.HTTP_401_UNAUTHORIZED) return Response({'success': False, 'result': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) I do not wish to change the way an endpoint is constructed. I do have a JWT authenticated call, and I wish /user/password would simply be able to PUT the 'old password' and 'new password' into that very same user. What am I doing wrong in my generics.UpdateAPIView class? what is that .lookup_field it's talking about? -
docker build seems to not see requirements.txt even though it's in same directory D`:
I'm setting up a website, pretty new to this, but I have the backend set up using django and gunicorn, and I am trying to package the whole thing in a docker container. I am using docker 17.05.0-ce edge on ubuntu 17.04 zesty. For some reason even though the directory mysite has the Dockerfile, django app, requirements.txt, start.sh(on github here). The docker build stops at ADD requirements.txt /app/src/requirements.txt, below for reference: # Dockerfile # FROM base image to build upon FROM phusion/baseimage # RUN install python and pip RUN apt-get update RUN apt-get install -y python python-pip python-dev # ADD requirements.txt and RUN pip to install them ADD requirements.txt /app/src/requirements.txt WORKDIR /app/src RUN pip install -r requirements.txt # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD execute start.sh to start the server running. WORKDIR /app/src/mysite CMD ["/start.sh"] # done! I navigate to 'mysite', run docker build - < Dockerfile and it stops on the line where it copies requirements.txt and i get the following error: Sending build context to Docker daemon 2.048kB Step 1/9 : FROM phusion/baseimage ---> 877509368a8d Step 2/9 : RUN apt-get update ---> Using cache ---> adcb4b9e8b08 Step 3/9 : RUN apt-get install … -
Django Cannot resolve keyword 'Word' into field. Choices are:
I have find similar errors on the forum but I don't see any mistakes in my code :/ and model and view are really not complicated. class Word(models.Model): word_text = models.CharField(max_length=50) user_crea = models.CharField(max_length=20) publ_date = models.DateTimeField(auto_now_add=True) modi_date = models.DateTimeField(auto_now=True) class Explanation(models.Model): word_foid = models.ForeignKey(Word, on_delete=models.CASCADE) expl_text = models.CharField(max_length=50) user_crea = models.CharField(max_length=20) publ_date = models.DateTimeField(auto_now_add=True) modi_date = models.DateTimeField(auto_now=True) So in my opinion Foreign Relationship should be ok. I don't have problems when I'm adding new data by admin panel. I used it in a view: def index(request): if request.method == 'POST': form = Search(request.POST) if form.is_valid(): dane = form.cleaned_data tlumaczenie=Explanation.objects.filter(Word__word_text=dane['Searched_word']) print(tlumaczenie) return render(request,'explanation.html', {'dane':dane}) But I'm still getting error: django.core.exceptions.FieldError: Cannot resolve keyword 'Word' into field. Choices are: expl_text, id, modi_date, publ_date, user_crea, word_foid, word_foid_id I don't understand why. It should send query like: select e.* from word w join explanation e on w.word_id = e.word_foid where w.word_text = dane['Searched_word'] and retrieve the data. Any ideas why it's not working properly? -
Display temporary loading page while generating redirect link
py will get input from template then will generate URL link for another website and at the end it will redirect user to that link. But also I want to add temporary loading page while user waiting for result (redirect link). Till now I have managed to write template and views but somewhere I got lost. page1.html <form action="." method="POST" target="_blank"> {% csrf_token %} <input type='hidden' value='XXX' name='name1'> <input type='hidden' value='YYYY' name='name2'> <a href="temporarypageLoading" class="btn btn-default">View</a> views.py def generateurl(request): if request.method == "POST": name1=(request.POST["name1"]).strip() name2=(request.POST["name2"]).strip() #do some calculation return HttpResponseRedirect('https://www.google.com') -
Django cannot use Sum with SQLite and time fields?
I have a model with a time field, and I need to sum the time fields in all instances. This is what I've tried: total_hours = Day.objects.filter(date__year=current_year, date__month=current_month).aggregate(Sum('total_work_hours')) print(total_hours) and I get this error: You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text. Is there a way around this? I'd like to stick with SQLite for now. -
How do i show an attribute of an object, rather than the object itself, in an accessor field in django-tables2?
I have a table of Compounds with a name field, which is linked to another table called Names. When I render a table with django-tables2, it's showing up just fine except for the fact that it doesn't say aspirin in the name column, it says Name object. models.py: class Compound(models.Model): drug_id = models.AutoField(primary_key=True) drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT) # for flagging problematic data flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT) # is a cocktail is_combination = models.BooleanField() class Meta: db_table = 'compounds' tables.py: import django_tables2 as tables from .models import Compound class FimTable(tables.Table): drug_name = tables.Column(accessor='name.name') class Meta: model = Compound attrs = {'class': 'paleblue table table-condensed table-vertical-center'} fields = ('drug_id', 'drug_name') sequence = ('drug_id', 'drug_name') order_by = ('drug_id') views.py: @csrf_protect @login_required # redirects to login page if user.is_active is false def render_fim_table(request): table = FimTable(Compound.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=20) response = render(request, 'fim_table.html', {'table': table}) return response Result: