Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extends myapp base.html - not form other app in my django project
I am new in Django. I wrote a django project which includes some apps. I made a base.html in my users app but I will se of the base.html from my articles app. I used {% extends 'base.html' %} in general and I tried: {% extends 'articles:base.html' %} or {% extends 'articles/base.html' %} and in myproject/settings.py TEMPLATES = [ ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], ... ] but they did not work. I would be glad if someone help me. -
Submit button doesn't redirect to new page
I have a form in django created using django-crispy-forms. It's working, loads fine on the page and even the validation is working. But when I hit the submit button, nothing happens. It redirect to the 'success' page. My forms.py file is: class EmployeeTestForm(forms.ModelForm): error_css_class = 'error' last_salary = forms.IntegerField(min_value=0, required=True, help_text='Yearly, in GBP (£)') resume_file = forms.FileField( validators=[FileExtensionValidator(allowed_extensions=['pdf'])], widget=forms.FileInput(attrs={'style': 'border: 1px;', 'class': 'form-control', 'required': False}) ) class Meta: model = EmployeeTestModel fields = '__all__' def __init__(self, *args, **kwargs): super(EmployeeTestForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = True self.helper.form_id = 'form-test' self.helper.form_class = 'uniForm' self.helper.form_method = 'POST' self.helper.form_action = '/forms/done' self.helper.form_show_errors = True self.fields['post_code'].widget.attrs = {'id': 'p_code', 'required': False} self.fields['uk_resident'].widget.attrs = {'onclick': 'showHidePostcode()'} self.fields['uk_resident'].label = 'Are you currently a UK resident?' self.helper.layout = Layout( Field('full_name', css_class='input-xlarge', placeholder='Your full name'), Field('uk_resident'), Field('post_code', placeholder='Valid UK postcode'), PrependedText('last_salary', '£', placeholder="Your last salary"), PrependedAppendedText('resume_file', 'Upload', 'Browse'), FormActions( Submit('save_changes', 'Submit', css_class="btn-primary") ) ) I have also set the redirect url on success in my view. Code is as follows: class EmployeeFormView(View): form_class = EmployeeTestForm template_name = 'app_temps/form.html' success_url = reverse_lazy('/forms/done') def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return … -
"no migration to apply" message where there is some migrations to be applied
I have added a new field called "city" for my custom user model. I will run makemigrations and it create new file in migration folder: migrations.AddField( model_name='customuser', name='city', field=models.CharField(blank=True, max_length=100, null=True, verbose_name='City'), ) by running migrate it does migrate ok in Windows, and new field is going to be added to my table. I do same thing in Linux command line; it creates same changes in new migration file by running makemigrations but when I run migrate it tells me no migration to apply, and doesn't add new field to the table in database. Previously I glossed over this issue and ended up creating new Database cause I am in development stage and it fixed the issue. However it is getting to the point that I need to find out what is going on, or find a workaround to actually force the changes somehow. I have also tried the migrate --fake-initial but stills the issue persists. I was wondering if anyone has seen this issue before and could please advice? Thanks -
unable to import rest_framework
I have Anaconda installed in my system but clearly I have set up a new and clean environment for a django API project. I also have all the necessary requirements installed for the API. But when I try to import rest_framework it gives me an error saying "Unable to import 'rest_framework' " even when I have done the following: #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', ] #serializers.py from rest_framework import serializers #<---- this line is giving me error from .models import Plans class PlansSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" model = Plans fields = ('id', 'name', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') requirements.txt certifi==2018.11.29 Django==2.1.7 django-crispy-forms==1.7.2 django-filter==2.1.0 django-markdown==0.8.4 django-markdown2==0.3.1 django-pagedown==1.0.6 djangorestframework==3.9.2 djangorestframework-simplejwt==4.1.0 Markdown==3.0.1 markdown2==2.3.7 olefile==0.46 Pillow==5.4.1 Pygments==2.3.1 PyJWT==1.7.1 pytz==2018.9 I also always deactivate the conda's base environment and only activate the required environment. -
Why i got "jQuery.Deferred exception"? I got the same code in CodePen an is working. [Django]
Codepen code here, i guess it's an import javascript problem, here are my head in my Project. <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" /> <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">{% endblock head %} Also i make it in another website, and there it's using another llb, i don't know why, but a delete the llb that doesn't change the result in the another code links. I make this part of the project with CodePen with example data for after put into my project, but doesn't work like the CodePen. I am getting this errors. Django code are here, because it's my project language. The result i am getting in my project it's here, need be like the codepen. Also my project it's a dashboard, just letting the situation know if this will generate a problem. -
Django serializer, nested relation and get_or_create
I've been bugging on this issue for some time now. I have two models : Acquisitions and RawDatas. Each RawData have one Acquisition, but many RawDatas can have the same Acquisition. I want to create or get the instance of Acquisition automatically when I create my RawDatas. And I want to be able to have all informations using the serializer. class Acquisitions(models.Model): class Meta: unique_together = (('implant', 'beg_acq', 'duration_acq'),) id = models.AutoField(primary_key=True) implant = models.ForeignKey("Patients", on_delete=models.CASCADE) beg_acq = models.DateTimeField("Beggining date of the acquisition") duration_acq = models.DurationField("Duration of the acquisition") class RawDatas(models.Model): class Meta: unique_together = (('acq', 'data_type'),) id = models.AutoField(primary_key=True) acq = models.ForeignKey("Acquisitions", on_delete=models.CASCADE) data_type = models.CharField(max_length=3) sampling_freq = models.PositiveIntegerField("Sampling frequency") bin_file = models.FileField(db_index=True, upload_to='media') And my serializers are these : class AcquisitionSerializer(serializers.ModelSerializer): class Meta: model = Acquisitions fields = ('id', 'implant', 'beg_acq', 'duration_acq') class RawDatasSerializer(serializers.ModelSerializer): acq = AcquisitionSerializer() class Meta: model = RawDatas fields = ('id', 'data_type', 'sampling_freq', 'bin_file', 'acq') def create(self, validated_data): acq_data = validated_data.pop('acq') acq = Acquisitions.objects.get_or_create(**acq_data) RawDatas.objects.create(acq=acq[0], **validated_data) return rawdatas My problem is that, using this, if my instance of Acquisitions already exists, I get a non_field_errors or another constraint validation error. I would like to know what is the correct way to handle this please … -
Django Rest Framework nested writable fields mixins drf_writable_nested
I'm currently trying to use the drf_writable_nested to perform updates and creates of my current db schema and I've been facing this error: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer trvl.serializers.StatisticsSerializer, or set read_only=True on nested serializer fields. Main model: class Statistics(models.Model): """Instance: {airport_code, carrier_code, month, year, flight, delay_count, delay_time}""" airport = models.ForeignKey(Airport, on_delete=models.CASCADE) carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE) month = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)]) year = models.IntegerField(validators=[MinValueValidator( 1900, message='Invalid year: year < 1900.')]) # statistics linkage flight = models.ForeignKey( FlightStatistics, on_delete=models.DO_NOTHING) delay_count = models.ForeignKey( DelayCountStatistics, on_delete=models.DO_NOTHING) delay_time = models.ForeignKey( DelayTimeStatistics, on_delete=models.DO_NOTHING) # Guaranteeing the "primary key" of the tuple class Meta: unique_together = ('airport', 'carrier', 'month', 'year') def __str__(self): return '%s_%s_%s_%s' % (self.airport, self.carrier, self.month, self.year) Serializer: class StatisticsSerializer(WritableNestedModelSerializer): # Using nest serializer for handling get and post # Using serializers instead of the model fields flight = FlightStatisticsSerializer() delaycount = DelayCountStatisticsSerializer() delaytime = DelayTimeStatisticsSerializer() class Meta: model = models.Statistics fields = ('airport', 'carrier', 'month', 'year', 'flight', 'delaytime', 'delaycount') View: class StatisticsView(viewsets.ModelViewSet, NestedCreateMixin, NestedUpdateMixin): queryset = models.Statistics.objects.all() serializer_class = serializers.StatisticsSerializer def post(self,request,*args, **kwargs): return self.create(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) Payload Example: { "airport": … -
in Django, how to implement CreateView's function with based-function views?
here is based-class views code: # views.py class ObjectCreate(CreateView): model = ObjectModel fields = "__all__" its simple to create an object and save it use this class. I wonder how? what if I want to use based-function views to achieve it? -
Get the context of a rendered page in a modal contact form
I'm redering a html template using a DetailView view. On the page I have a Contact Form that opens in a modal when a button is click. The Contact Form is submitted using ajax: class ContactView(View): success_message = 'Your message has been sent' def post(self, request): if request.is_ajax(): data = { "message": self.success_message } I need to get a part of the information/context that was already used to generate the page. My approach is to get the url: url=request.META.get('HTTP_REFERER') And from url get the slug, interrogate database and other queries. I'm searching for a better variant, maybe not based on HTTP_REFERER, not to start again doing the same 5-6 queries in the database to get the context of the rendered page. -
Django - Proper way to Update model instance?
Kind of a newbie question so please bare with me. On my Django project, I have a form on my my_account_edit.html page and the values of this form where they are displayed are on my my_account.html which I created. I need this form to update the model instance if it exists or create a new one for the logged in user. What's the best way to execute this? Any help is appreciated. Thanks. -
Django class view
I'm still new at django so please bear with me. I'm trying to make a website about books. Now i'm having error like this MultipleObjectsReturned at /premium/1/ get() returned more than one Book -- it returned 2! i don't know where to look about the error. here is my my example code. class PageDetailView(LoginRequiredMixin, generic.View): def get(self, request, *args, **kwargs): book = get_object_or_404(Book) page = get_object_or_404(Page) user_membership = get_object_or_404(Customer, user=request.user) user_membership_type = user_membership.membership.membership_type user_allowed = book.allowedMembership.all() context = {'object': None} if user_allowed.filter(membership_type=user_membership_type).exists(): context = {'object': page} return render(request, "catalog/page_detail.html", context) Traceback: File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\admin\thesis\blackink_website\catalog\views.py" in get 127. book = get_object_or_404(Book) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py" in get_object_or_404 93. return queryset.get(*args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in get 403. (self.model._meta.object_name, num) Exception Type: MultipleObjectsReturned at /premium/1/ Exception Value: get() returned more than one Book -- it returned 2! I will update the post if the information is not enough. thanks in advance. -
Can't use dynamically ionRangeSlider onFinish function
I create filters dynamically, so they aren't in DOM. I can handle the select tags with on() function. $(document).ready(function(){ $(document).on('change',"select[name='similar_market_select']",function(){ console.log($(this).attr("value")) }) }) I also can get data from ionRangeSlider with change method, but it send me every change. I would like to create my ajax call only when the slider change has finished. This works for me, if the ionRangeSlider was already in my html: $(document).ready(function(){ $(".js-range-slider").ionRangeSlider({ type: "double", onFinish: function (data){ console.log("it works!") } }) But I can't transform it, when I dynamically added is. Thanks for any help! -
Adding two separate model fields to calculate for the average
I have two models: class BsoQMS_QA(models.Model): id = models.IntegerField(db_column='ID',primary_key=True) audit = models.CharField(db_column='Audit', max_length=50, blank=True, null=True) status = models.CharField(db_column='Status', max_length=50, blank=True, null=True) challenge_decision = models.CharField(db_column='Challenge_Decision', max_length=50, blank=True, null=True) name = models.CharField(db_column='Name', max_length=50, blank=True, null=True) timeliness = models.DecimalField(db_column='Timeliness', max_digits=3, decimal_places=2, blank=True, null=True) accuracy = models.DecimalField(db_column='Accuracy', max_digits=3, decimal_places=2, blank=True, null=True) start_date = models.DateTimeField(db_column='Start_Date', blank=True, null=True) closed_date = models.DateTimeField(db_column='Closed_Date', blank=True, null=True) lastmod_date = models.DateTimeField(db_column='LastMod_Date', blank=True, null=True) class Meta: managed = False db_table = 'BSO_QMSQA' This is the other: class QAErrorTracker(models.Model): start_date = models.DateTimeField(null=False,blank=False) name = models.CharField(max_length=50,null=False,blank=False) process = models.CharField(max_length=50,null=False,blank=False) author = models.ForeignKey(User,default=None, on_delete=models.CASCADE) body = models.TextField() accuracy = models.DecimalField(default=1, null=False,max_digits=3, decimal_places=2) def __str__(self): return self.name The first model consists of all quality audits with an accuracy column that has data of either 1 or 0 (1=with error 0= no error) which is fairly easy to calculate and get their accuracy score per month. (ERRORS / # of AUDITS). However, I need to also consider adding the errors logged on the 2nd model (which normally are email escalations logged in the tracker) to accurately get their accuracy score for the month. I've added an accuracy column field which has a default value of 1. I've tried using Django ORM to combined that two queryset: from … -
Django 1.7 fails with debug set to false
I am running a perfectly fine django 1.7 install on an ubuntu 14.04. Now I am trying to install the same thing on an ubuntu 16.04. Same settings, but now it is failing if I set Debug to false. With Debug=True it works just fine. I get this error when trying to run a migrate: File "manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/apps/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/apps/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/apps/env/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/apps/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/apps/env/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/apps/env/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 40, in <module> class Permission(models.Model): File "/apps/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, **kwargs)) File "/apps/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 297, in add_to_class value.contribute_to_class(cls, name) File "/apps/env/local/lib/python2.7/site-packages/django/db/models/options.py", line 166, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/apps/env/local/lib/python2.7/site-packages/django/db/__init__.py", line 40, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/apps/env/local/lib/python2.7/site-packages/django/db/utils.py", line 242, in __getitem__ backend = load_backend(db['ENGINE']) File "/apps/env/local/lib/python2.7/site-packages/django/db/utils.py", line 108, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/apps/env/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 23, in <module> import psycopg2 as Database File "/apps/env/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 144, in <module> """) File "/usr/lib/python2.7/logging/__init__.py", line 1728, in _showwarning logger.warning("%s", … -
downloading file from django not working correct
I am using this code in my views.py def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as f: response = HttpResponse(f.read()) response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 file type can be any and urls.py re_path(r'^download/(?P<path>.*)$', views.download, name='download'), finally my template look like this <div class="container"> <div class="row"> <div class="col-md-8"> <h2>{{ article.title }}</h2> <p style="word-break: break-word;">{{ article.about_article }}</p> <a href="/download">Download</a> </div> </div> when I click Download on the browser it says permisson denied. any suggestion please? when am I making mistake -
django oauth toolkit grant client credentials - accounts/login/
I am trying to use oauth for authentication and authorization in a project. I want to use the client credentials grant type as this project is about a middleware/api that will be consumed by a client application. I have created one corresponding client_id and client_secret. The token generation is working, however as soon as I am trying to do a request with the generated token against the api endpoint i am being forwarded to the accounts/login page by django: <td>http://127.0.0.1:8000/accounts/login/?next=/api/mp/</td> my settings are: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend',) And this the top of my only function in my views: @csrf_exempt @require_http_methods(['POST', 'GET']) @login_required() def getUserContext(request): I am not really understanding where this additional authentication is coming from or resp. how i can tell django to only use oauth for the view. -
Crontab not running script automatically
I created a custom python command called expire_lesson.py. In my terminal when I run python3 manage.py expire_lesson, the command successfully executes. I have added a cron job * * * * * cd /Users/james/Desktop/elearning && python3 manage.py expire_lesson to run the script every minute. The issue is the cron job is not working. I believe it has something to do with the location of my cron job, but am unsure how to find the exact location, or if there is another issue. I would greatly appreciate any help in adding a cron job that runs expire_lesson successfully. class Command(BaseCommand): help = 'Expires old lesson objects' def handle(self, *args, **options): Lesson.objects.filter(lesson_end__lt=timezone.now()).delete() -
How do i start working with AWS for a web application development project?
I just took on a "Recommendation search engine" entitled project, supposedly to be done with Amazone web services, i have access to an amazone account and all. the thing is, i don't know where to begin, this is my first project ever, web development or not. the project mainly, "recommending" a service provider based on the feedback of its previous users. what needs to be done: List item a front end, authentication/signin signup with aws cognito, forms a search engine (no idea how to do it) the recommendations acquired to be analyzed with aws NLP and text analysis, to extract service providers' ratings. i know python, so i'm gonna use django, based on some research i have done.. can anyone help set the draft of web development, considering i'm a total beginner and this project actually has a client and a deadline of 2 months? -
django view problem - Cannot assign "<SimpleLazyObject: <User: admin>>":
I have a problem with order view of my Django application. The whole error: Value Error: Cannot assign "SimpleLazyObject: User: wad2": "OrderItem.order" must be a "Order" instance. This is the order view: @login_required def my_order(request): user = request.user context = {} cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST or None, instance=user) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() context['order'] = order else: form = OrderCreateForm() context['form']=form return render(request, 'iFood/my-order.html', context) The form: class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ('created’,) The models for OrderItem and Order: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='orders') created = models.DateField(default=datetime.date.today()) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity The reason I'm using the form is just to confirm the user wants to create the order. I know there's something wrong with the way I create the orderItem and reference order there but I don't know how to resolve it. -
djqscsv make only one part of my union query
I wish that app to create csv report from to diffrient models. There is models.py: class Renters(models.Model): org_prav_form = models.ForeignKey(Pravform, models.DO_NOTHING, blank=True, null=True) inn = models.CharField('inn',max_length=100, blank=True, null=True) name = models.CharField('orgname',max_length=150, blank=True, null=True) snameplp = models.CharField(max_length=100, blank=True, null=True) fnameplp = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True verbose_name = 'rent' verbose_name_plural = 'rents' class RentAddres(models.Model): renters_id = models.ForeignKey(Renters, models.DO_NOTHING, verbose_name='renter') subject = models.ForeignKey(SubjectRf, models.DO_NOTHING, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) street = models.CharField(max_length=50, blank=True, null=True) house = models.CharField(max_length=4, blank=True, null=True) housing = models.CharField(max_length=3, blank=True, null=True) so I start report app, and create views with queries: return response import django_excel as excel from django.db import models from django.http import HttpResponse from renter.models import * from classification_list.models import* from cutarea.models import ForestryKeys import djqscsv def report(request): atable = Renters.objects.all().values('name','snameplp','fnameplp','inn').union(RentAddres.objects.all().values('subject','city', 'street','house','housing','building', 'office', 'telephon')) return djqscsv.render_to_csv_response(atable) I set urls for report app : urlpatterns = [ url(r'^$', views.report, name='index'), ] and for project: url(r'^report/', include('report.urls')), So, what I expect whe go to localhost/report/ ? I expect dataframe with columns from both models (Renters, RentAddres). But result is only Renters data... What is wrong? How to make union and exportation for them? -
DJANGO DATEFIELD TO STRING
Finding references and also finding datasets for basic training and validation of the model DATEFIELD MODEL VALUE TO STRING MODELS.PY class Product(models.Model): category = models.CharField(max_length=100) product_name = models.CharField(max_length=100) quantity = models.IntegerField() date = models.DateField() def __str__(self): return str(self.date).format() VIEWS.PY def inventory_forecast(request): # trying simple arima model hopefully it will run templates = 'Product/forecast.html' # passing data from one view to another query_cat = request.session.get('c') query_pro = request.session.get('p') query_num = request.GET.get('forecast_num') filtering values in the model using the category values and product name to get the values_list in terms of value and quantity columns query = Product.objects.filter(Q(category__iexact=query_cat) & Q(product_name__iexact=query_pro)) \ .all()\ .values_list('date', 'quantity') listing the np.array to shape the query query_array = np.array(query) # 80% of the data points will be used as train query_slice_train = mt.floor((query_array.shape[0])*0.8) # 20% of the data points will be use as test query_slice_test = mt.floor(query_array.shape[0]-query_slice_train) # query[start:] or from # items start through the rest of the array # query[:stop] or to # items from the beginning through stop-1 # training 80% of the datasets train = query_array[:query_slice_train] # testing 20% of the datasets test = query_array[query_slice_train:query_array.shape[0]] print(query_array.shape) print(query_array.shape[0]) print(query_array.shape[1]) print(query_array.ndim) print(query_slice_train) print(query_slice_test) print(train.shape) print(test.shape) print(test.shape[0]) print(train) print(test) context = { 'query_cat': query_cat, 'query_pro': query_pro, … -
How to get value at the signal?
I'm beginner at Django. I have a signal, which is create model RelationShip during updating model RelationRequest. But I'am get type_of_relation = None', altought a modelRelationRequest` has a value. How I can get this value? signals.py @receiver(post_save, sender=RelationRequest) def relation_save(instance, created, update_fields, **kwargs): not_approving_list = ['familliar', 'mate', 'friend', 'colleague'] if not created: user = instance try: request_relation = RelationRequest.objects.filter(creator=user.creator).filter(status=True).first() print(request_relation.type_of_relation) #accounts.RelationType.None relation_ships = RelationShip.objects.filter(creator=user.creator) for i in relation_ships: if unicode(request_relation.creator) == i.creator and unicode(request_relation.relation) == i.relation and request_relation.type_of_relation == i.type_of_relation: break else: RelationShip.objects.create( creator = user.creator, relation = request_relation.relation, type_of_relation = request_relation.type_of_relation, ) except: pass views.py @method_decorator(login_required, name='dispatch') class ProfileView(DetailView): model = User queryset = User.objects.filter(is_active=True) def post(self, request, *args, **kwargs): self.object = self.get_object() relation_form = RelationRequestForm(request.POST or None) if relation_form.is_valid(): for rt in relation_form.cleaned_data['type_of_relation']: relation_user_id = int(filter(lambda x: x.isdigit(), request.path)) rq = RelationRequest.objects.create( creator = request.user, relation = User.objects.get(id = relation_user_id), ) rq.type_of_relation.add(rt) not_approving_list = ['familliar', 'mate', 'friend', 'colleague'] request_relation = RelationRequest.objects.filter(creator=request.user).first() relation_ships = RelationShip.objects.filter(creator=request.user) if rt.title.lower() in not_approving_list: for i in relation_ships: if unicode(request_relation.creator) == i.creator and unicode(request_relation.relation) == i.relation and rt.title.lower() == i.type_of_relation: print('if') break else: print('else') RelationShip.objects.create( creator = request.user, relation = request_relation.relation, type_of_relation = rt.title.lower(), ) request_relation.status = True request_relation.save(update_fields=['status']) context = self.get_context_data(relation_form = relation_form) … -
django error string index out of range when resetting password
Hello I have my django app deployed to production environment and whenever I try to reset password using the custom password reset for django I get error IndexError at /accounts/password_reset/ string index out of range Request Method: POST Request URL: https://www.simplyadventure.co.ke/accounts/password_reset/ Django Version: 2.0.6 Exception Type: IndexError Exception Value: string index out of range -
Disconnect with linkedin authentication in Django displays blank screen
I want a user to be able to disconnect from linkedin in my application, but it displays a blank screen. <div class="my-2 my-lg-0 mx-5"> <strong class='text-light mr-2'> Hi {{ user.username }} </strong> <a href="{% url 'social:disconnect' 'linkedin-oauth2' %}" class="btn btn-primary my-2 my-sm-0" type="submit">Logout</a> </div> This is the url for the django_social_auth path(r'', include('social_django.urls', namespace='social')), I want the user to be disconnected from his linkedin account if he clicks the logout button. -
Django & Celery, tasks not activating if using venv
I've started using Celery in my Django project, Redis is a broker. Everything is fine when I install Celery globally. But when I install Celery to a virtual environment, all tasks are sort of stuck. Flower shows that all tasks are "Processed" and none are Active. Worker's output with debug option is like this: [2019-03-18 13:45:13,247: INFO/MainProcess] Received task: (data) [2019-03-18 13:45:13,247: DEBUG/MainProcess] TaskPool: Apply <(data...)> ..etc There is no "Task accepted: (data)" message What can be the reason? I use: Django==2.1.7 celery==4.3.0rc2 flower==0.9.2 redis==3.2.0 Python v3.7.2, Windows 10