Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'setup_environ'
I am creating models in django environment. Below is the sample code. class Album(models.Model): artist = models.CharField(max_length=255) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=255) logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ': ' + self.artist class Song(models.Model): artist = models.ForeignKey(Album, on_delete=models.CASCADE, null = True) file_type = models.CharField(max_length=255) song_title = models.CharField(max_length=255) def __str__(self): return self.song_title I was getting below error:: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So, I got some article that suggested me to import django module from django.core.management import setup_environ import settings setup_environ(settings) So now, the above error was corrected, but I got new error as below File "<ipython-input-8-3168a50cefba>", line 2, in <module> from django.core.management import setup_environ ImportError: cannot import name 'setup_environ' I know that the django module is present in my IDE, coz, when I hovered my cursor on the warning icon near the django module it said "django imported but not used". But that is not our concern, as I happened to get rid of the warning. Spyder IDE - 3.2.3 Python - 3.6 Django - 1.11.3-py36_0 -
Accessing the profile information of facebook through Django-Allauth
I am trying to display the complete profile of the authenticated user on my webpage using Django-allauth and Django 1.11.5. I am currently using a simple template as following: <html> <body> Welcome back {{ user.first_name }} <img src="{{cover.source}}" height="60" width="60"> <a href="/">Home</a> </body> </html> Here the image tag is not getting the data. Hence, getting a broken image. But I am wondering how I can use the Django Library and access the complete profile information of the visitor who get authenticated using the Django-Allauthlibrary. Here is the settings.py of my application:-- SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos'], 'METHOD': 'js_sdk', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Kindly, help me. There are many misconceptions I am facing in the usage of the Django-Allauth. I specifically wants to access the Profile URL, Profile Picture, Posts, about me, etc. My Facebook Application has access to many scope, hence there is no problem for this, but the implementation of the library is restricting me from the usage. Kindly, help me. -
How do i find a lost element with jQuery
Well I have the problem, I can't log out when i just log in (without reloading the page). And I cant log in when I just logged out (again with page reload it works). Well I think after reloading the nav, he forgets the id of logout or something? <script> logout = $('#logout') loginform = $('#loginform') logout.click(function () { $.ajax({ url: 'accounts/logout/', success: function (json) { console.log(json) }); }, }); }); loginform.on('submit', function (event) { event.preventDefault(); login(); }); function login() { $.ajax({ url: 'accounts/login/', success: function (json) { console.log(json) /* Reloades the navbar */ $('#usergui').load(document.URL + ' #usergui'); } }); } ; </script> My HTML: <div id="usergui"> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a id="logout"> </span> Logout </a></li> {% else%} <li><a> </span> Login </a></li> <li><a> </span> Register </a></li> {% endif %} </ul> </div> After Login my user gets authenticated and reloading the nav make only logout appear. -
Django Initial Value For Foreignkey Field
So I'm trying to pass some initial data to the volume field in CourseForm, but for some reason it won't work. I've tried looking at similar questions at stackoverflow, but no luck. The volume field is a ForeignKey to a table in the database. It doesn't give me errors just doesn't display any information. My model with the respective volume field: class Course(models.Model): volume = models.ForeignKey(CourseVolume) code = models.CharField(max_length=100, default=None) # ... code shortend to simplify My Modelform with its model set to Course class CourseForm(ModelForm): class Meta: model = Course fields = '__all__' My view where I'm trying to set the initial data for the CourseForm. It just doesn't seem to work. user.volume_preference returns an integer from 1-x which is the id for the specific volume. def view_course_create(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): form.save() return redirect('teaching_courses') else: user = MbsUser.get_user_from_ad(request.session['username']) if user.volume_preference is not None: volume = user.volume_preference form = CourseForm(initial={'volume': volume}) else: form = CourseForm() return render(request, 'teaching/course_create.html', {'form': form}) Anyone who knows how this can be solved? I've really looked and I'm at an impasse. Any help is greatly appreciated. -
Locally hosted Django traffic analytics
is there any known way to track locally hosted django web? I want to know who is using web, how many unique users, what is the most visited resource etc. I would use Google Analytics or smth similar, but my project is deployed offline and has to access to internet. So i need to track the specific IP Django is deployed on. I was trying to install Piwik, since it can be installed on the machine, but i didnt succeed to install mysql on my raspberry pi. I am working on raspberry pi 2 wheezy, python 3 -
How to disable queryset cache in Django forms?
I have a Django form that is supposed to filter choices using a queryset: class GenerateStudentAttendanceForm(forms.Form): selected_class = forms.ModelChoiceField(queryset=Class.on_site.filter( is_active=True, academic_year__is_active=True )) date = forms.DateField(initial=now().date()) The problem is that Class.on_site.filter is evaluated when the form is instantiated and is used for subsequent requests even if the site has changed. How can I come around this? -
Django1.8 or less queryset: filter multiple datetimes by hour
I have a model with a datetime field that I want to filter by hour, the problem is that there's multiple datetimes, making the datetime.now() soluction not realible for this case. Also, if we try gt/lt/gte/lte/in to the hour it doesn't work. The scenario is that if the hour is less then 12 then returns "morning", if it is between 12 and 18 returns "afternoon" and if it is greater then 18 returns "night". Model: class MyModel(models.Model): datetime_field = models.DatetimeField() name = models.CharField() Data example: 1. 2012/10/2 22:00 2. 2015/2/15 15:00 3. 2017/3/2 9:00 Expected queryset: Night = queryset.filter(datetime_field__hour__gte=18) Afternoon = queryset.filter(datetime_field__hour__lt=18, datetime_field__hour__gte=12) Morning = queryset.filter(datetime_field__hour__lt=12) Result: 1. Night 2. Afternoon 3. Morning -
django rest framework, Additional checks and saves in ViewSet and return different response depends on condition
I'm making voting. All user can vote 1 time in 24 hours. User making vote with POST request. Every time he vote I want to check the last time he voted: if he voted more than 24 hours ago I want to save his vote. if less than 24 hours I want to return bad request (or something like this). Please help me. Here is my code but it doesn't work. The object save is happening anyway, doesn't matter what I put in if condition... How to do this things right? views.py: class VoteAddViewSet(viewsets.ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteAddSerializer http_method_names = ['post',] def perform_create(self, serializer): return Response(status=status.HTTP_400_BAD_REQUEST) profile = get_object_or_404(Profile, pk=1) allow_vote_date = profile.vote_date + timedelta(days=1) if (allow_vote_date < timezone.now()):{ profile.vote_date = timezone.now() profile.save() serializer.save(user=self.request.user) } else: return Response(status=status.HTTP_400_BAD_REQUEST) serializers.py: class VoteAddSerializer(serializers.ModelSerializer): class Meta: model = Vote exclude =('id','created_date','user',) urls.py: router = routers.DefaultRouter() router.register(r'vote_add', views.VoteAddViewSet, 'vote_add') urlpatterns = [ url(r'^', include(router.urls)),] models.py class Vote (models.Model): user = models.ForeignKey(User, null=True, blank=True, related_name='girls_user_voted_for', on_delete=models.SET_NULL) girl = models.ForeignKey(Girl, null=True, blank=True, related_name='supporters_of_this_girl', on_delete=models.SET_NULL) created_date = models.DateTimeField(default=timezone.now) def __unicode__(self): return u'{}'.format(self.id) -
Use include tag to include the same template that is calling it
I have a use case where different fields of a form are rendered differently based on an include tag and arguments passed to it. To keep it DRY, sometimes I'd like to include the same template and pass it a different argument, like in a simplified example below: main_form.html {% include "./field-snippet.html" with type=list %} field_snippet.html {% include "./field-snippet.html" with type="regular" %} But that gives a TemplateSyntaxError. Alternatively, I could have different html files for different kinds of fields but that seems to be many files with not much code in each. Any ideas on how to best approach this? Is using custom Widgets the best approach here (I haven't played much with them yet) -
Django return blob form azure-storage as downloadable file
I am new to azure-storage and django My dev environment software configuration is as- django 1.10 , python 2.7.6, azure-storage-blob 0.37. I am using django application as webservice api and frontend is built using angular-2 and HTML I am using azure blob storage for storing files with any type. azure blob Container where which I am saving files have private access only.I am able to upload file successfully. The problem is while downloading file- what I am trying to achieve is- 1] When someone clicks on hyperlink on page request will go to django view with blob name. then I can get blob using container name and blob name block_blob_service._get_blob(container,blob_name) 2] I want to return that blob as downloadable file in django response. Can you suggest be solution or better approach where I can achieve this. Thanks in advance. -
I cannot show images which is url type
I cannot show images which is url type. I wrote in product.html <body> {% for product in products.all %} <h4> {{ product.product_title }}</h4> <img src="{% static product.image }} %}"/> <p> {{ product.body }} </p> {% endfor %} </body> in models.py class Product(models.Model): product_title = models.CharField(max_length=250) image = models.TextField() body = models.TextField() in views.py def product(request): products = Product.objects.order_by('product_title') return render(request, 'registration/product.html',{'products':products}) From admin site,I added product_title&image&body. image's urls is <a href="https://xxxxxx" target="_blank" rel="nofollow"> <img border="0" width="120" height="60" alt="" src="https://wwwyyyyyyyyyyyy"></a> <img border="0" width="1" height="1" src="https://wwwzzzzzzzzzz" alt=""> By using Google console,Failed to load resource: the server responded with a status of 404 (Not Found) is in Console. In Elements,img tag is like <img src="/static/wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"> How can I show image?Am I wrong to write the way of img tag & src? -
python manage.py runserver throwing error
C:\training\webserver\webserver>python manage.py runserver 0.0.0.0:8001 Unhandled exception in thread started by <function wrapper at 0x0000000003C872E8> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, 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() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, 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 299, in <module> class AbstractUser(AbstractBaseUser, PermissionsMixin): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 279, in __new__ new_class.add_to_class(field.name, new_field) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 709, in contribute_to_class cls._meta.add_field(self) File "C:\Python27\lib\site-packages\django\db\models\options.py", line 277, in add_field self.local_fields.insert(bisect(self.local_fields, field), field) File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), I am new to python. I gave the following commands. django-admin startproject webserver this created a skeleton project. after this, i gave python manage.py runserver 0.0.0.0:8001 I am getting above error. i am not able to start server. Please guide me. -
Django Wagtail: migrating from MySQL to Postgresql
I'm trying to migrate a Django project from using MySQL to Postgresql. The project contains a Puput blog. Puput is blog implemented with Wagtail. I've followed the following tutorial. When I reach step three python manage.py migrate --database postgres I get the following error: Apply all migrations: account, admin, app, auth, contenttypes, puput, sessions, sites, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying app.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_fix_str... OK Applying account.0003_passwordexpiry_passwordhistory... OK Applying account.0004_auto_20170416_1821... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying app.0002_marketnotification_pricechangenotification... OK Applying app.0003_auto_20170812_0920... OK Applying app.0004_auto_20170813_0949... OK Applying app.0005_auto_20170816_2141... OK Applying app.0006_auto_20170816_2149... OK Applying app.0007_auto_20170816_2230... OK Applying app.0008_auto_20170816_2239... OK Applying app.0009_auto_20170817_2036... OK Applying app.0010_auto_20170817_2045... OK Applying app.0011_auto_20170817_2048... OK Applying app.0012_auto_20170817_2113... OK Applying app.0013_auto_20170817_2114... OK Applying app.0014_auto_20170817_2115... OK Applying app.0015_auto_20170818_2317... OK Applying app.0016_auto_20170818_2334... OK Applying app.0017_auto_20170819_1500... OK Applying app.0018_auto_20170819_1948... OK Applying app.0019_auto_20170819_2032... OK Applying app.0020_auto_20170819_2054... OK Applying app.0021_auto_20170820_1129... OK Applying app.0022_auto_20170820_1218... OK Applying app.0023_auto_20170820_2140... OK Applying app.0024_auto_20170820_2314... OK Applying app.0025_auto_20170821_1931... OK Applying app.0025_auto_20170821_1923... OK Applying app.0026_merge_20170821_1936... OK Applying app.0024_auto_20170821_1949... OK Applying … -
Django url with anchor
I am using Django 1.11 and have troubles using urls with anchor. They work well intrapage, but when a url points to a specific anchor on another page it doesn't work at all. This is my url schema: url(r'^(?P<slug>[-_\w]+)/$', CategoryListView.as_view(), name='category_detail', ), And this is how the url is constructed: <a href="{{cat.get_absolute_url}}#someAnchor">BlaBla</a> Which results in a url that looks like this: mydomain.com/category/#venus As said once I get to the url at mydomain.com/category/ and reload retry (click again from a sidebar, no reload triggered) the page the anchor works, but when I am going from another location it doesn't point to the anchor and I end up on top of the page. Any ideas how to fix this? Thanks for any input. -
what is best secure way database design for holding credit?
I want to create web site with django that managers can payed their employees salary ,in this method mangers should first pay in my site and i increase their balance after their payed and then i payed to their employees i want to know best way database design for holding balance that cant be hacked and how to hold transactions data in django here is the few models i have tanks all class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) employees = models.ManyToManyField(User, blank=True, null=True, related_name='boss') FatherName = models.CharField(max_length=20,default='',blank=True) NationalCode = models.CharField(max_length=20, default='') birth_date = jmodels.jDateField(null=True, blank=True) PhoneNumber = models.CharField(max_length=20,default='') email_confirmed = models.BooleanField(default=False) phone_confirmed = models.BooleanField(default=False) profile_confirmed = models.BooleanField(default=False) DebitCardNumber = models.CharField(max_length=16, default='') balance = models.DecimalField(max_digits=6, decimal_places=2 , default=0) class Transaction(models.Model): FromUser = models.ForeignKey(Profile, related_name='+') ToUser = models.ForeignKey(Profile, related_name='+') TransactionDate = models.DateField() Amount = models.DecimalField(max_digits=6, decimal_places=2) transaction_type = models.BooleanField() -
Django-Allauth does not offer posts extracts from profile
I am trying since weeks to get the users complete profile and posts for my NLP analysis. I have tried many libraries for that purpose and found Django-alluth a bit useful for authentication. But it does not satisfy my requirements including displaying the profile image, posts, about the user, etc. Inshort most part of the complete profiles on my website and then the analysis part using the posts text. I have gone through many libraries among which is Authomatic, django-allauth and many other. But they are useless in my case. I want to know how I can achieve this task in Django. I do not mean to use the JS-SDK of facebook, as it might reveal the program logic on the front. Kindly, suggest me. If anyone have better option for the achieving the task of my experiment. -
Implement Facebook Log In with Django
Hi I would really appreciate if somebody could please paste there code here for there Facebook login created for their Django project, whether it is a separate app or not, with a couple of explanations. Pulling User Name, Email and profile pic. Thank you -
I cannot read matplotlib graph by using shell
I cannot read matplotlib graph by using shell. I wrote in views.py from pylab import figure, axes, pie, title from matplotlib.backends.backend_agg import FigureCanvasAgg import numpy as np import matplotlib.pyplot as plt def graph1(): left = np.array([1, 2, 3, 4, 5]) height = np.array([100, 200, 300, 400, 500]) plt.bar(left, height) graph1() I wrote commands in terminal like python manage.py shell from accounts import views views.graph1() but no graph is shown. I think matplotlib graph can be read by using shell,but do I misunderstand? or am i wrong to write the way of code? How can I do it? -
how to import a variable from some python file to views.py django
How to import a variable from some python file to views.py django. Getting error in urls.py, views.py, xyz.py while doing normal import in django environment in views.py. For example: from xyz import x; # gives error while running project -
Not able to access the gravatar URL using Django-AllAuth
I am trying to access the profile picture with django-allauth plugin, but I am getting error while accessing it. I am using the following code: import allauth.socialaccount.providers.facebook.provider as fb def fb_personality_traits(request): # logger.debug('FB Page Loaded') print fb.FacebookAccount.get_avatar_url(user) return render(request, 'home/facebook_personality_traits.html') I have got the following error: Please let me know what to do to improve it. Here is the reference: get_avatar_url -
Invalid syntax: from django import forms
I wrote the following code in forms.py. I can't understand what is wrong with this. This gives invalid syntex form django import forms class contactForm(forms.Forms): name=forms.CharField(required=False,max_length=100,help_text='100 characters max.') email=forms.EmailField(required=True) comment=forms.CharField(required=True,widget=forms.Textarea) -
Django doesn't see some static files in development
I am having issues with django not serving some static assets during development. It's a really strange issue. This is how the pertinent part of my static directory is right now: site_media └── static ├── css │ ├── public.css │ ├── site-ada8eab0af.css Now that is my staticfiles directory, and things are correctly imported there from my static directory when I run manage.py collectstatic. I have two lines in my template: <link href="{% static 'css/site-ada8eab0af.css' %}" rel='stylesheet' /> <link href="{% static 'css/public.css' %}" rel="stylesheet" /> These produce these two lines in the rendered output: <link href="/site_media/static/css/site-ada8eab0af.css" rel='stylesheet' /> <link href="/site_media/static/css/public.css" rel="stylesheet" /> When I go to the first link, it works fine. When I go to the public.css link though, I get a 404 error that says 'css/public.css' could not be found. The complete link I use is http://localhost:8000/site_media/static/css/public.css What could possibly make it able to serve one of these files, but not the other? -
Django - Allauth - How to add additional API parameters to registration
I'm using Django all-auth through Django rest-auth and I'd like to extend the registratino functionality to match my custom user object. Given the user model below: class Profile(AbstractUser): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True, blank=True) first_name = models.CharField(max_length=40, blank=True) last_name = models.CharField(max_length=40, blank=True) How can I enable allauth to receive those as parameters via an API call to then clean/store them. In other words, what I want to be able to do, is call the /rest-auth/registration/ endpoint with a body like such; { "username": "foo", "email": "bar@mail.com", "password1": "fooBar!@", "password2": "fooBar!@", "first_name": "first", "last_name": "last" } and have first_name and last_name stored as a Profile object. Again, I want to be able to do this via the API and not via a form. Environment details: Django==1.11.3 django-allauth==0.33.0 django-environ==0.4.4 django-rest-auth==0.9.1 django-storages==1.6.5 django-taggit==0.22.1 djangorestframework==3.6.4 ... $ python --version Python 2.7.11 -
Can't convert string from 'UTF-8' to native encoding for pysvn export
I was running pysvn's export of a repo with file names with french letters like "Français" or "Spécifications du produit". When the export runs, the following error is returned Can't convert string from 'UTF-8' to native encoding I found this http://refactor.se/2007/08/13/svn-fix-cant-convert-string-from-utf-8-to-native-encoding/ and Can't convert string from 'UTF-8' to native encoding indicating something about setting the local language but I couldn't find this in pysvn. Is it possible to set this when initializing a pysvn Client? EDIT: Forgot to mention i'm doing this on django 1.7 Thanks -
deploying a django app on osx
I am using OS X El Capitan with server app v 5.1. I created a simple app using Django in \Library\Server\Web\Data\WebApps. The app is called mysite (actually it is an empty app created with django). Can anyone help me with the deployment of this app? I cannot seem to find any documentation or tutorial on how to do this. Is there a way to add it to the server appp^ and which .conf or .wsgi or com.something should I change. Any help is really appreciated. Thank you