Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking duplicate email when editing user profile in Django
I am trying to check the duplicate email while I am logged in as a user and editing my own profile. But when the email entered is the email of current logged in user and I do not want to update my current email then also I am getting a duplicate email error message. accounts/forms.py class UserProfileForm(forms.ModelForm): class Meta: model = models.Profile fields = ("organisation", "phone_number") first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)")) organisation = forms.CharField(max_length=30) email = forms.EmailField() def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.initial['first_name'] = self.instance.user.first_name self.initial['last_name'] = self.instance.user.last_name self.initial['email'] = self.instance.user.email helper = FormHelper() helper.layout = Layout( Div( Field("first_name", wrapper_class="col-sm-6"), Field("last_name", wrapper_class="col-sm-6"), css_class = "row" ), Div( Field("organisation", wrapper_class="col-sm-6"), Field("email", wrapper_class="col-sm-6"), css_class = "row" ), Div( Field("phone_number", wrapper_class="col-sm-6"), css_class = "row" ), ) def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError(u'Please use a different email address.') return email def save(self, commit=True, *args, **kwargs): self.instance.user.first_name = self.cleaned_data['first_name'] self.instance.user.last_name = self.cleaned_data['last_name'] self.instance.user.email = self.cleaned_data['email'] self.instance.user.save() return super(UserProfileForm, self).save(commit, *args, **kwargs) How can I check if the entered email is a new email and if it is new email then check duplicate function else ignore email field … -
Deploying Django projects with conda
Environment management in Python projects is critical and is commonly done with venv or virtualenv. However, I am interested in deploying a Django project with conda. The basic setup looks like the one here. Django is served using gunicorn which is controlled with supervisor. That conda does not use folders as environments basically means that there is no isolated directory where the Django project could live (hope I got this right). This post has a nice description of how to deploy a Python project with conda in general. For using this with supervisor I was thinking if activating a specific conda environment with installed dependencies in supervisor would suffice to create the needed results. I assume this supervisor config might look something like this: [program:djangoapp] command = .activate django-env; python gunicorn djangoapp.wsgi:application -b 127.0.0.1:8000 directory = /path/to/djangoapp ... The supervisor docs say that supervisor will search the supervisord’s environment $PATH for the executable, if it's provided without an absolute path. Does this mean that the absolute path of the conda environment needs to be used here? Long story short: Is anyone using conda for this and is it even usable the way I like to do it and if yes: … -
Getting error while including javascript files using Django and Python
I am getting some error while including javascript files in templates using Django. I am explaining my error below. Error: TemplateSyntaxError at / Invalid block tag on line 6: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 6: 'static'. Did you forget to register or load this tag? Exception Location: C:\Python34\lib\site-packages\django\template\base.py in invalid_block_tag, line 571 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 I am explaining my code below. settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] PROJECT_DIR = os.path.dirname(__file__) """ Internationalization """ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True """ Static files (CSS, JavaScript, Images) """ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') urls.py: """Neuclear plant URL Configuration""" from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('plant.urls')), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html: <html lang="en"> <head> <meta charset="utf-8"> { % load static %} <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> </head> In the above template file i am getting the error. Here I need to include the js file in … -
Key (email)=() already exists error: python-social-auth
My app uses both email registration and Facebook or Google+ registration using python-social-auth (0.2.11). When some new users register using Facebook, they are taken to an error page. After that, I see the following error: Internal Server Error: /complete/facebook/ Traceback (most recent call last): File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/newrelic/hooks/framework_django.py", line 527, in wrapper return wrapped(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 51, in wrapper return func(request, backend, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/apps/django_app/views.py", line 28, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/actions.py", line 43, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 41, in complete return self.auth_complete(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper return func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/facebook.py", line 87, in auth_complete return self.do_auth(access_token, response, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/facebook.py", line 119, in do_auth return self.strategy.authenticate(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/strategies/django_strategy.py", line 96, in authenticate return authenticate(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate user = backend.authenticate(**credentials) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 82, in authenticate return self.pipeline(pipeline, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 85, in pipeline out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 112, in run_pipeline result … -
How can I display a view based on a database value
I want to use one view (URL) for 2 conditions. In my application, "owners" create daily plans for routes they manage, and update the plans/results throughout the day. class DailyRoute(models.Model): owner = models.ForeignKey(Owner) route = models.ForeignKey(Route) driver = models.ForeignKey(Driver) stops = models.PositiveSmallIntegerField(default=0, ... on_duty_hours = models.TimeField(default=datetime.time... date = models.Datefield(... finalized = models.Boolean(... Essentially, there are 3 database conditions, 2 of which I'm trying to use for a view: No database row for the date/route. This means that the owner hasn't created a plan for the day. (e.g. if DailyRoute.objects.filter(stage = 0).count() == 0:...) A database row for the date/route with finalized = False. This means that a plan has been created for the day for the date/route pair and can be edited. (e.g. DailyRoute.objects.filter(stage = 0).count() >0 ) A database row for the date/route with finalized = True. This means that a plan/updates for the day are complete and no further edits are allowed. (e.g. if DailyRoute.objects.filter(stage = 1).count() > 0:...) As a daily activity, I want the user to go to a URL (e.g. /account/daily) and be presented with one of these views: a) If no owner routes (point 1 above), provide an "Add" button to add a row … -
Unable to Render Bundle (404) - React with Jango
I've been stuck for a while in this part to render a simple, basic HTML page with a react container. What happens is that the system is unable to find the bundle, popping out the following error in the browser - element inspection: main-e81ebca393352343ecd4.js Failed to load resource: the server responded with a status of 404 (NOT FOUND) While popping the following error in the "python manage.py runserver" terminal window: [29/Aug/2017 16:40:57] "GET / HTTP/1.1" 200 269 [29/Aug/2017 16:40:57] "GET /static/bundles/main-e81ebca393352343ecd4.js HTTP/1.1" 404 1721 Now I've been through multiple times my settings.py file and my webpackconfig.js file, however, I havent been able to find where is my mistake so far. webpack.config.js: //require our dependencies var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { //the base directory (absolute path) for resolving the entry option context: __dirname, //the entry point we created earlier. Note that './' means //your current directory. You don't have to specify the extension now, //because you will specify extensions later in the `resolve` section entry: './assets/js/index', output: { //where you want your compiled bundle to be stored path: path.resolve('./assets/bundles/'), //naming convention webpack should use for your files filename: '[name]-[hash].js', }, plugins: [ … -
Can this be done with Scrapy or something else?
Compared to 99% of you on this site, I am a newbie when it comes to programming & other technical issues. Luckily I have a son with a CS degree who is pretty talented. Unfortunately, he is extremely busy so when I ask him to do something for me I have to have my ducks in a row to make him efficient. Scrapy looks like a tool that he could use to do something for me. I just wanted this communities’ thoughts on whether I’m sending him in the right direction. I promise that there will be no newbie level follow-up questions from me once I have determined that this is the right tool for him to use for what I want to accomplish. I’m looking for a tool that can constantly and quickly scan part of a website for newly added pages. Ideally, I need it to find the new page within 1-2 seconds after it is added. Before normally using this website I am required to logon to gain access (so it needs to be able to handle that). I only want this tool to scan the part of the website where the web address starts with an … -
how to catch the unauthenticated response 401 from django rest api in react native
Here in views.py class StockList(APIView): #authentication_classes = (TokenAuthentication,) permission_classes = [IsAuthenticated] def get(self,request): stocks = Stock.objects.all() serializer = StockSerializer(stocks,many=True) return Response({'user': serializer.data,'post': serializer.data}) def post(self): pass Here if token is not valid then it doesnt send any data.. so in react native I have to patch that error and show their invalid credentials. So here is my react.js file componentDidMount() { return fetch('http://10.42.0.1:8000/stocks/', { method: "GET", headers: { 'Authorization': `JWT ${"eyJhbGciOiIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwNDAxNTg4M30.o_NjgPNsxnLU6erGj5Tonap3FQFxN3Hh_SsU6IvLO9k"}` } }) .then((response) => response.json()) .then((responseData) => { console.log(responseData.detail); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ isLoading: false, sa: ds.cloneWithRows(responseData.post), }, function() { }); }) .catch((error) => { console.error(error); }); } here if json data is not provided then show some error.. how could I accopmlished that. thank you. -
How can I display error messages in django
As I can put an error message to the user when it completes the fields of my form, I am using views based on classes CreateView .. and I only found success_message class RegistroUsuario(CreateView): model = User template_name = "usuario/registrar.html" form_class = RegistroForm success_url = reverse_lazy('denuncias:index') permission_denied_message = "You must login to contact the administrator" I also tried to add this function but it no longer creates the regitros when I use it def form_invalid(self, form): response = super(RegistroUsuario, self).form_invalid(form) messages.error( self.request, 'Error de validacion: Email o contraseñas incorrectas, recuerde las contraseñas deben tener un minimo de 8 caracteres con letras y numeros') return response -
Error 'str' object has no attribute 'resolve_expression when using CASE WHEN statement in Django
Perhaps there is a better way to doing it, but I am trying to count the number of members by age group. It is the first time I am trying to use CASE/WHEN and I am running into the above error. This is the case statement I am using: Case( When(2017 - birthdate__year__range=(0,10), then=Value('0,10')), When(2017 - birthdate__year__range=(11,20), then=Value('11,20')), When(2017 - birthdate__year__range=(21,30), then=Value('21,30')), When(2017 - birthdate__year__range=(31,40), then=Value('31,40')), When(2017 - birthdate__year__range=(41,50), then=Value('41,50')), When(2017 - birthdate__year__range=(51,60), then=Value('51,60')), When(2017 - birthdate__year__range=(61,70), then=Value('61,70')), When(2017 - birthdate__year__range=(71,80), then=Value('71,80')), When(2017 - birthdate__year__range=(81,90), then=Value('81,90')), When(2017 - birthdate__year__range=(91,100), then=Value('91,100')), When(2017 - birthdate__year__gt=100, then=Value('100+')), output_field=CharField(), ) My query is: members=MK.objects.filter(**filters).annotate(age_groups= Case( When(2017 - birthdate__year__range=(0,10), then=Value('0,10')), When(2017 - birthdate__year__range=(11,20), then=Value('11,20')), When(2017 - birthdate__year__range=(21,30), then=Value('21,30')), When(2017 - birthdate__year__range=(31,40), then=Value('31,40')), When(2017 - birthdate__year__range=(41,50), then=Value('41,50')), When(2017 - birthdate__year__range=(51,60), then=Value('51,60')), When(2017 - birthdate__year__range=(61,70), then=Value('61,70')), When(2017 - birthdate__year__range=(71,80), then=Value('71,80')), When(2017 - birthdate__year__range=(81,90), then=Value('81,90')), When(2017 - birthdate__year__range=(91,100), then=Value('91,100')), When(2017 - birthdate__year__gt=100, then=Value('100+')), output_field=CharField(), )).values('age_groups',).annotate(total=Count('age_groups')) I read to use models.CharField() for output field but still it didn't make a difference. Is my approach at right? -
Django ModelForm error message not showing in template
I have created some custom error message following the documentation (as best as I can find) but I'm not getting any errors, let alone my custom errors. Here's my code: forms.py class UploadFileForm(forms.ModelForm): class Meta: model = Job fields = ['jobID','original_file'] labels = { 'jobID': _('Job ID'), 'original_file': _('File'), } error_messages = { 'jobID': { 'max_length': _("Job ID is limited to 50 characters."), 'required': _("Please provide a Job ID."), 'invalid': _("Job ID must be a combination of letters, numbers, - and _.") }, 'original_file': { 'required': _("Please provide a file."), 'validators': _("Please ensure you are selecting a zipped (.zip) GDB."), }, } help_texts = { 'original_file': _('Please provide a zipped (.zip) GDB.'), } upload.html <form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data" name="uploadForm"> {% csrf_token %} {% for field in form %} <div> <strong>{{ field.error }}</strong> {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class ="help-text">{{ field.help_text }}</p> {% endif %} </div> {% endfor %} <br /> <button type="button" id="uploadButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off" style="margin: auto 20%; ">Upload</button> </form> I've included everything I think is relevant, let me know if you need anything more. -
django error " NoReverseMatch at /polls/"
l am following a tutorial and l have been getting these errors!why? i need your help. on the error page it says "NoReverseMatch at /polls/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/$(?P[0-9]+)/$']" please help, l am struggling through this tutorial. the tutorials link"https://docs.djangoproject.com/en/1.11/intro/tutorial04/" my index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <a href="{% url 'polls:detail' question.id %}">{{question.question_text}}</a></li> {% endfor %} </ul> {% else %} <p> No polls are available </p> {% endif %} urls.py in polls app from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] my views.py in polls app from django.template import loader from django.http import HttpResponse from .models import Question from django.shortcuts import get_object_or_404, render from django.urls import reverse # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404 (Question,pk=question_id) return render(request, 'polls/detail.html' , {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls:results', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, … -
Setting up a virtual environment for python3 using virtualenv on Ubuntu
I want to learn Django so for that, as per the instructions on the website, you need to create a virtual environment. I've heard enough horror stories about people corrupting their OS cause they didn't set up the virtual environments properly so it's safe to say I'm sufficiently paranoid. I've created a separate folder/directory VirtualE at located at Academics/CS/VirtualENV and I want to create all my virtual environments there. As per the website, the following command should be used - virtualenv --python=`which python3` ~/.virtualenvs/djangodev I'm not sure what exactly I should write in place of the single quotes (the which python3 part). I wrote the following - virtualenv --python=3.5.2 ~/Academics/CS/VirtualENV/DjangoDev It says The path 3.5.2 (from --python=3.5.2) does not exist Where exactly am I going wrong? -
elasticsearch (Python/Django) bulk indexing throws No Index error
I am using elasticsearch's python client and elasticsearch-dsl as well. I have created an index IndexName and I validated the existence of the index. I have a doc_type DocumentModelIndex associated with this IndexName. def bulk_indexing(): from app.models import DocumentModel DocumentModelIndex.init(index=settings.ES_INDEX) es = Elasticsearch() bulk(client=es,actions=(b.indexing() for b in DocumentModel.objects.all().iterator())) When I run the above code I get the following error: ValidationException: No index. I tried Putting a document into that index using: curl -XPOST "http://localhost:9200/index_name/document_model_index/" -d "{\"source\":\"google\"}" and this worked. I am new to elasticsearch and am not able to figure this out. Any help would be much appreciated! -
geodjango query format coordinates- convert lat lon , open street map
I have a polygon in my model citys but in my map for example bogota has the coordinate -8243997.66798 , 517864.86656 -> open street maps; but i need make query with coordinates like (4.697857, -74.144554) -> google maps. pnt = 'POINT(%d %d)'%(lon, lat) zonas = ciudad.zona_set.filter(polygon__contains=pnt) zonas is empty :/ , how i can convert lat and lon to standar coordinates in open street map , or how know the srid code for one input (lat,lon) pnt = GEOSGeometry('POINT(-96.876369 29.905320)', srid=srid_from_lat_lon) thanks -
limiting the number of displayed instances of a model in Django Admin
I have a model which over timer will have several thousand to tens of thousands of instances. Each of those is unique. In the Django Admin interface I can see all the instances and access them ect. Is there a way for me to limit the number of instances I can see to lets say 20 or 50 sorted in whichever order and I can look through them like pages? I ask because loading all several thousand instances will likely clog up my server. So how do I limit it? My model is as follows if that helps: #Student Type class StudentType(models.Model): name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Name') def __unicode__(self): return self.name #Old -- Deprecated:Student Images Folder def student_directory_path(instance, filename): return 'students/%s' % filename #Student Images Folder def st_profile(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'students/%s' % filename #Student Profile class ProfileStudent(models.Model): user = models.OneToOneField(app_settings.USER_MODEL,) created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') email = models.EmailField(max_length=254, blank=True, null=True) name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Name') last_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Last Name') phone_number = … -
Pass arguments to serializer DRF
Well I'm struggling at sending arguments to the serializer class, my code looks like: models.py class Transaction(models.Model): owner = models.ForeignKey(User, on_delete=models.SET("DELETED"), related_name='transactions') date = models.DateField(auto_now_add=True) concept = models.CharField(max_length=100) value = models.DecimalField(max_digits=10, decimal_places=2) total = models.DecimalField(max_digits=10, decimal_places=2) serializers.py class TransactionSerializer(serializers.ModelSerializer): total = serializers.ReadOnlyField(source='new_total') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Transaction fields = '__all__' views.py class TransactionHandler(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer def perform_create(self, serializer): last_transaction = Transaction.objects.latest('id') new_total = last_transaction.total + Decimal(self.request.data['value']) serializer.save(owner=self.request.user, new_total=new_total) When in the serializer.save() method there is only the owner argument all works fine but when I add the second argument all gets messy -
invalid literal for int() with base 10: 'choosen_room_1_id'
I was trying to access part of the model self attributes, however after migrations this error showed up. The model works perfectly fine before I ran makemigrations and migrate. After reading through the value error page, I notice that the value error was cause by the model trying to access it's own foreign key(choosen_room_1) under a property function. models.py def getTotalPricing(self): total_price = 0 amount = dict() if self.choosen_room_1 is not None: The choosen_room_1 attribute was defined as below: models.py choosen_room_1 = models.ForeignKey(ChoosenRoom, default=None, related_name="room_type_1", null=True) Some things I have tried so far are: remove old migrations file check if id field exist in the table using sqlite terminal, and it does exist force choosen_room_1 to_field as 'id' or 'choosenroom_id', same error still exist Using django admin interface I am sure the choosenroom wasn't null and was able to reassign it with a new foreign key item. Accessing choosen_room_1 using manage.py shell will give me the same error. After reading through some of the stackoverflow issues, my guess was somehow foreignkey was expecting the unique id key with integer type, however something went wrong during query process? As mention here btw, I was running this project under python2.7 with django … -
Slow Image Loading with Lightbox Plugin and Amazon S3
I am hosting a Django app which displays images inside a gallery-view called lightbox (https://github.com/ashleydw/lightbox). Every Image is loaded via a presigned url from Amazon S3. The problem is that the image only starts loading as soon as it is viewed in the gallery, not any sooner. For some users this then takes a couple seconds to load. I am not to sure whether S3 is the bottleneck, but is there any method to force preloading of images that are currently "invisible"? Even preloading the next picture in the gallery would suffice I think. I am aware that Cloudfront enhances loading times from S3 as well, but is currently not an option. -
why is requirement.txt build failing in elastic beanstalk?
I am in the process of migrating a Django app from Heroku to Elastic Beanstalk. It is working fine in Heroku as is. I am getting the error Your requirements.txt is invalid. Snapshot your logs for details. When I dive into the eb-activity.log I see the failure seems to be related to atlas and scipy. I don't under why requirements.txt is invalid on aws but valid on heroku. Insight into what is causing this error and how to remedy would be greatly appreciated. My eb-activity.log /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. self.calc_info() /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable. self.calc_info() /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable. self.calc_info() Running from scipy source directory. Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-ix0qk_kf/scipy/setup.py", line 416, in <module> setup_package() File "/tmp/pip-build-ix0qk_kf/scipy/setup.py", … -
How to used foreignkey data in extra field with inline in django
When we save foreign key object from django admin. As following screenshot click here to see the screenshot Newly created object will get saved but not been able to display at same time in dropdown list. We have measurement model which has material and product foreign key as showed in following snippet. So I want when object is created it should display the newly created option in foreign key dropdown. Please suggest how do I do that. Here is my code snippet models.py class MaterialName(models.Model): material_name = models.CharField(max_length=150, default=None, null=True, unique=True) class Product(models.Model): product_name = models.CharField(max_length=100) class Measurement(models.Model): product = models.ForeignKey(Product,default=None, null=True, related_name='Measurement') material_name = models.ForeignKey(MaterialName,default=None, blank=Blank, related_name='materialname') admin.py class MaterialTypeAdmin(admin.ModelAdmin): model = MaterialType list_display = ('material_type',) class ProductAdmin(admin.ModelAdmin): model = Product inlines = [MaterialTypeAdminInline,] -
Loaddata return error "Key (user_id)=(2) already exists."
i have data in Sqllite3, but i want to use PostgreSQL so i did dumpdata then loaddata it says this error: psycopg2.IntegrityError: duplicate key value violates unique constraint "uyelik_ders_bilgileri_uye_id_23796fd8_uniq" DETAIL: Key (user_id)=(2) already exists. i think it is about my models.py, because i created extended user profile with these codes: class ders_bilgileri(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) dersler = models.TextField(max_length=500,blank=True,default="bos") facebook_adresi=models.URLField(max_length=1000,blank=True) facebook_mesaj_gonderilsin=models.BooleanField(default=True) twitter_mention_atilsin=models.BooleanField(default=True) twitter_adresi = models.CharField(max_length=1000,blank=True) facebook_idsi=models.CharField(max_length=100,blank=True,default="yok") pushed_id=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: ders_bilgileri.objects.create(user=instance) I tried then get_or_create but nothing changes, what is the problem you think? -
Can I login in with Facebook as an unregistered user? (Django, all-auth)
I'm building my Django RESTful Framework to retrieve and post data for Mobile. I'm using djang-rest-auth (which is just all-auth with RESTful functionality; more info: http://django-rest-auth.readthedocs.io/en/latest/). Question: Social Auth in all-auth is not clear to me. Can you finish this use case? Use Case: Unregistered User User Login with Facebook on Mobile Mobile gets facebook token from Facebook SDK Mobile sends token to our DRF Backend server URL which is '/rest-auth/facebook' And what happens? Can you complete this Use Case? <- This is my question My guesses: all-auth automatically create new user for facebook user token and return new token? Then, it saves created user to settings.AUTH_USER_MODEL? Or...? I found 'social account' in Django admin. Are we saving User in this account..? -
how to setup django database accessed from 3 apps
I have 3 apps in a project. What I want to do are 2 things. (1) I want to setup each apps to access same database(Read & Write). I have no idea that I have to have same models.py each of my apps. If so, how can I migrate database. I tried it, but one app which was used to do migrate command success database access. But other 2 apps couldn't access database. And I tried to make simbolic link of models.py and migrations directory to each apps directories. But it didn't work too. (2) I want to use django authentication system to each of my apps. App1 (For Enduser) - (email, password) App2 (For Service provider) - (ID, password) App3 (For System Administrator) - (ID (different from App2), password) I can use django user authentication system from 1 app. But I want to make authentication system to 3 apps from different urls. App1 is a webview based app that use django via rest framework. App2 and App3 are web application (different url and port). Can I make it on using django? Would you give me some advice please? -
Django - creaing a custom model admin form field, passing the model instance to set a read only attribute
I know you can set readonly_fields in a model's admin.py but I am trying to make a field read only dependent upon it's (saved) value in the database. I can create a custom field Class, but am unable to pass the value of the model instance so I can achieve the above. Eg class MytypeField(models.CharField): def __init__(self,*args,**kwargs): PAGE_LAYOUT_CHOICES = ( ('column1','One Column'), ('column2','Two Columns') ) kwargs['max_length'] = 7 kwargs['choices'] = PAGE_LAYOUT_CHOICES kwargs['default'] = 'column1' super(MytypeField,self).__init__(*args,**kwargs) And in the model layout = MytypeField() Is there a way to do this in admin.py rather than in the model itself? I can't pass the model instance to this custom class, and I'm sure that's not the way to do it anyway! Many thanks!