Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how fix docker when goes to restarting status after docker-compose in django on ubuntu
I use postgresql and docker in my django project. after docker-compose my container goes to restarting status. I tried fix it by stop and remove but didn't work docker-compose.yml: version: '3' services: blog_postgresql: image: postgres:12 container_name: blog_postgresql volumes: - blog_postgresql:/var/lib/postgresql/data restart: always env_file: .env ports: - "5432:5432" networks: - blog_network volumes: blog_postgresql: external: true networks: blog_network: external: true and terminal show this: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e8aa3e604ba3 postgres:12 "docker-entrypoint.s…" 3 days ago Restarting (126) 14 seconds ago blog_postgresql -
Is django-CMS and cookiecutter-django compatible?
I just tried to port my Django-CMS project into Django Cookiecutter (cookiecutter-django) in ordert to get it to run in Docker. It seems Django-CMS is using the default Django user model and Cookie-Cutter is using a custom model (from allauth?). I found this https://github.com/pydanny/cookiecutter-django/pull/248 thread and it suggests changing the order in which the apps are loaded but that doesn't cut the mustard. Are Django-CMS and Cookiecutter at odds with each other? -
ValueError at /checkout/ The view accounts2.views.CheckoutView didn't return an HttpResponse object. It returned None instead
Can anyone please help me fix this error? I'm trying to develop an e-commerce website using Django. Why is this error being thrown? It's in my views.py. But what's the problem actually and what does this error mean? My accounts2.views.py: class CheckoutView(View): def get(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) form = CheckoutForm() context = {"form": form, "cart": cart} return render(self.request, "orders/checkout.html", context) def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) except Order.DoesNotExist: order = Order(cart=cart) order.cart = cart order.user = self.request.user order.order_id = id_generator() order.save() if form.is_valid(): street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') country = form.cleaned_data.get('country') zip = form.cleaned_data.get('zip') # same_shipping_address = form.cleaned_data.get('same_billing_address') # save_info = form.cleaned_data.get('save_info') payment_option = form.cleaned_data.get('payment_option') billing_address = BillingAddress( user = self.request.user, street_address = street_address, apartment_address = apartment_address, country = country, zip = zip ) billing_address.save() order.billing_address = billing_address order.save() return redirect('checkout') messages.warning(self.request, "Failed checkout") return redirect('checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect('/') -
Empty query returns all fields from database. Django
In the search form field, If I don't enter anything, but push on the button to search the query. The query returns every each field from the database. Company.objects.exclude(Q(name__isnull=True)).exclude(Q(name__exact='')) Somehow, doesn't help me. If I use them together or separate. The code in views.py is: class className(listView) model=Company template_name='name_of_the_template.html' def get_queryset(self): query=self.request.Get.get('q') query=query.replace('#',' ') //same for ?\/$%^+*()[] *tried to set exclude code here if query == ' ': object_list = Company.objects.filter(Q(name__icontains='None'))//sending to the empty object return object_list else: // *tried to set exclude code here object_list = Company.objects.filter(Q(name__icontains=query)) return object_list None of exclude code helps. I believe I do simple mistake somewhere... because code suppose to work, but somehow still. I just also tried to get rid off if else statement and use exclude statements for queries such as '', ' ' and null and after that filter for query... And now excluding queries for ' ' also doesn't work... Django doesn't tell me the exclude doesn't work, all works, except, it is like not in the code. -
How to add description to the User Change Page in Django Admin
I'm working on Django and wanted to add a description under the heading at the red mark in the User change page as shown in the pic my admin.py file look like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) fieldsets = ( ('Personal Information', { 'classes': ('wide',), 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','password')}), ('Permissions', {'fields': ('is_superuser','is_staff', 'is_active','date_joined')}), ) So what should I do to get a description at the red mark in the user creation page?? Thanks in advance!! -
How do I go about creating two objects that are tied to each other by a foreign key in one form/view in django?
So, I have a messaging component of an app I am creating. There is a Conversation object, which has a ManyToMany field to user. Then, there is the actual InsantMessage object, which has a sender field to user, textfield and another field called receiver that is a foreign key to my conversation object. Now what I am attempting to do is to create a link underneath another user's profile, and then pass their pk in that link to my view which will check to first see if their already exists a conversation object with request.user and the other user, and if so, will create a message object and then automatically pass in the Convo object pk for the foreign key field conversation in my Message object. Now, I think I have the basic understanding of how to do this, perhaps just using an if statement and a nested form. But, where I'm stuck in is, how do I get the conversation pk to automatically pass? And how would if the conversation object is being created, how can I get request.user/other user to be automatically put in the conversation object? Even if you don't want to write out my code, just … -
django with angular on elastic beanstalk
I have been using Django and I am used to serving HTML pages using its templates. Using the same to host it on elastic beanstalk has been straight forward. Now if I have to use Django only for its admin and rest APIs while using angular as a frontend framework, what are changes to be made within Django to accommodate angular and how to deploy it on elastic beanstalk with ci/cd preferably through bitbucket. -
Add through field of user to serializer
I'm having the following models class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) display_name = models.Charfield() class Team(models.Model): display_name = models.Charfield() users = models.ManyToManyField(User, through='TeamUser') class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.IntegerField(_('role'), choices=[(g.id, g.name) for g in TeamRoles.all()], default=0) color = models.CharField(_('color'), max_length=10) class Meta: unique_together = ('team_id', 'user_id',) I want to add role and color to Serializers (using request.user) How can I make TeamSerializer for that? -
how to make shopping cart using django
I'm making a shopping cart with two class models, one user can order multiple products I used the many-to-many relationships. but I'm facing some issues like if two users has order same product then the last user's selected qty will show in both user's order. and many times it shows all orders in the user's cart by default. please tell the correct way to write these models. So each users cart can't affect others class OrderItem(models.Model): id = models.AutoField(primary_key=True) product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) qty = models.IntegerField(default=1) def __str__(self): return self.product.Productname class Cart(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, default=None, blank=True) -
Django test runner not running with non-standard project structure
I've got a Django project with a slightly non-standard structure (shown below) and the Django test runner isn't working. root_dir ├ src | ├ myapp_dir (apps.py, etc.) | ├ project_files_dir (settings.py, wsgi.py, etc.) | ├ utils_dir, etc. | └ manage.py ├ tests | ├ test_settings.py | └ myapp_tests_dir (tests1.py, tests2.py, etc.) ├ setup.py └ runtests.py apps.py contains: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' settings.py includes INSTALLED_APPS = [..., myapp] test_settings.py includes INSTALLED_APPS = [..., myapp, tests] runtests.py contains: import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) When I to run the tests with python runtests.py I get ModuleNotFoundError: No module named 'myapp' If try to change test_settings.py to include INSTALLED_APPS = [..., src.myapp, tests] I then get django.core.exceptions.ImproperlyConfigured: Cannot import 'myapp'. Check that 'src.myapp.apps.MyAppConfig.name' is correct. It's probably also worth mentioning that runserver runs fine from the working directory root_dir when calling it like this: > python src/manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 22, 2020 - 16:06:19 Django version 3.0.5, … -
Why aren't my image files uploading properly, I keep receiving 404 in console?
I am trying to have React upload an image via React DropZone. However, when I go to my blog manager page, the console promptly logs 404 Failed to load resource: the server responded with a status of 404 (Not Found). I am using Django Rest Framework for the backend, and in the terminal it states "GET /media/Upload%20image HTTP/1.1". The frontend, react, is able to get the image file on the page, but it will not upload. Here is the settings.py in backend DRF: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p%s-9w1l268@!b$p#92dj26q)pv7!&ln^3m(1j5#!k8pkc9@(u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 'allauth', # 'allauth.account', # 'allauth.socialaccount', 'corsheaders', # 'rest_auth', # 'rest_auth.registration', 'rest_framework', # 'rest_framework.authtoken', 'menus', 'phlogfeeder', 'login' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chefsBackEnd.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Why won't my plotly figures render correctly in Django templates?
I have a basic python module that I'm using to output the div necessary to embed the plotly plot directly into my Django template. I just want to display a basic plot in my website for proof of concept to someone I'm developing with. the plot renders but I can only see visual feedback if my cursor goes over a datapoint and shows the coordinates on screen. Otherwise, the lines, points, axes, and all other rendered components are invisible. The code I'm running is below. Plotter.py import plotly.graph_objects as go from plotly.offline import plot import pandas as pd def get_plot_div(): x = [0,1,2,3,4,5] y = [6,5,4,3,4,5] zipped_list = list(zip(x,y)) df = pd.DataFrame(zipped_list,columns = ['x1','x2']) fig = go.Figure() fig.add_trace(go.Scatter( x = df['x1'], y = df['x2'], mode = 'lines')) fig.update_layout(height=600, width=800, title_text="Simple Plot") plot_div = plot(fig, output_type = 'div',auto_open = False) return plot_div Views.py from . import Plotter.py as plotter from django.shortcuts import render def Profile(request): plt_div_returned = plotter.get_plot_div() context = {'fig':plt_div_returned} return render(request,'django_proj/profile.html',context) Then in the profile.html template I have <h1> Test Plot </h1> {% if context.fig %} {{%context.fig | safe%}} {% endif %} This renders the plot in my template, but again I can only see anything if I move … -
i want to send otp after clicking send otp and then verify it by clicking verify in django template how can i do this?
I want to send OTP from Django template, how I can get receiver's phone I below code and send OTP and verify import requests import JSON import random import math URL = 'https://www.sms4india.com/api/v1/sendCampaign' # get request def sendGetRequest(reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage): req_params = { 'apikey':apiKey, 'secret':secretKey, 'usetype':useType, 'phone': phoneNo, 'message':textMessage, 'senderid':senderId } return requests.get(reqUrl, req_params) data ="0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" leng = len(data) otp ="" for i in range(6): otp += data[math.floor(random.random()*leng)] # get response response = sendGetRequest(URL, 'authkey', 'api key', 'stage', 'phoneNO', 'user', 'Your digit OTP is '+str(otp) ) """ Note:- you must provide apikey, secretkey, usetype, mobile, senderid and message values and then requst to api """ # print response if you want print(response.text) this code generate OTP for me but how to get user-entered OTP and compare in Django -
django-autocomplete-light. How to implement a global navigation autocomplete using django-autocomplete-light
I've been making an Yelp clone and i encounted frustration creating autocomplete. I have one searching form with 2 fields. Search field should traversy through 2 models (Business, Service). Searching should looks like on Yelp. But for Business model it should have one look(it must have and be wrapped into tag). For Service model it looks like a plain text. Also search field must be chained to city field(Look up of businesses should happens only in the city from city field, like 'china restaurants' in 'London' ). I have no problems with city autocomplete(for cities i use cities-light and geodjango). How to implement global navigation autocomplete(like on Facebook or Yelp). *forms.py* class SearchForm(forms.Form): search = forms.ChoiceField(widget=autocomplete.ListSelect2(url='searchquery-autocomplete')) city = forms.ChoiceField(widget=autocomplete.ListSelect2(url='city-autocomplete')) For example i use 2 models: Business with name, service fields and related model Service with name field. -
Django form and CBV CreateView not able to assign request.user to user field
I have a form and a CBV CreateView. I need to assign the request.user to the user field (Foreign Key to CustomUser model), which in the form is a hidden field (user). However, I have tried in the form init method by "self.fields['user'] = self.request.user.id" and I get the error: 'NoneType' object has no attribute 'user'. What is the most clean way of achieving this? I have tried many different ways of doing it with no luck. ): This is my form: class PhoneForm(forms.ModelForm): class Meta: model = Phone fields = 'user', 'phone_name', 'country', 'phone_number', 'phone_type', 'primary' widgets = {'user': forms.HiddenInput()} def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(PhoneForm, self).__init__(*args, **kwargs) self.fields['user'].widget.attrs['readonly'] = True self.fields['user'] = self.request.user.id self.fields['primary'].help_text = _('<strong>Check:</strong> If this is your main contact phone number.') def clean(self): cleaned_data = super(PhoneForm, self).clean() user = cleaned_data.get('user') phone_name = cleaned_data.get('phone_name') country = cleaned_data.get('country') phone_number = cleaned_data.get('phone_number') phone_type = cleaned_data.get('phone_type') primary = cleaned_data.get('primary') print('user: ',user) print('phone_name: ',phone_name) print('country: ',country) print('phone_number: ',phone_number) print('phoe_type: ',phone_type) print('primary: ',primary) if "action_add" in self.request.POST: try: phonenum = Phone.objects.filter(user=user, country=country, phone_number=phone_number).first() if phonenum: raise forms.ValidationError(_('This Phone is registered already.')) except Phone.DoesNotExist: pass try: phone = Phone.objects.filter(user=user, primary=True).first() if phone and primary: raise forms.ValidationError(_('There is another "Primary" … -
Mail don't send mail from smtp server(django)
As far as I understand the problem is that the email is perceived as spam. I wrote to mail on the recommendation, but I don't know when they will respond, so I decided to write, maybe someone has already faced a similar problem Error: 2020-04-21T17:11:44.703528+03:00 srv20-s-st postfix/cleanup[31293]: AB6FC3782386: message-id=<20200421141144.AB6FC3782386@smtp-out7.jino.ru> 2020-04-21T17:11:44.749351+03:00 srv20-s-st postfix/bounce[16478]: 60F7137822E8: sender non-delivery notification: AB6FC3782386 2020-04-21T17:11:44.749756+03:00 srv20-s-st postfix/qmgr[29563]: AB6FC3782386: from=<>, size=2939, nrcpt=1 (queue active) 2020-04-21T17:11:45.286651+03:00 srv20-s-st postfix/smtp[3053]: AB6FC3782386: to=<marsel.abdullin.00@mail.ru>, relay=mxs.mail.ru[94.100.180.31]:25, delay=0.53, delays=0.05/0/0.04/0.45, dsn=5.0.0, status=bounced (host mxs.mail.ru[94.100.180.31] said: 550 spam message rejected. Please visit http://help.mail.ru/notspam-support/id?c=P6S_FpNxB6v7cN6t9-D6dIPfAZm8McBDVirhhk5aBttn62fvJQEllSMAAACyigAAEsgALQ~~ or report details to abuse@corp.mail.ru. Error code: 16BFA43FAB077193ADDE70FB74FAE0F79901DF8343C031BC86E12A56DB065A4EEF67EB6795250125. ID: 0000002300008AB22D00C812. (in reply to end of DATA command)) 2020-04-21T17:11:45.291554+03:00 srv20-s-st postfix/qmgr[29563]: AB6FC3782386: removed -
How to co-exist STATICFILES_FINDERS and STATIC_URL
I would use django on apache with this setting. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") in apache setting Alias /static/ /var/www/html/jrtweet/current/static/ However I installed django-compressor, so adding,this setting. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) However after adding this, browser can't access /static/ directory. I need to do some setting for co-exist STATICFILES_FINDERS and STATIC_URL setting?? -
Can anyone tell about how can I fix this error in django , AttributeError: module 'BRMapp.models' has no attribute 'objects'
BRMapp is project name. please see the code in below image : https://i.stack.imgur.com/v0gG0.jpg In cmd , showing error: books = models.objects.all() AttributeError: module 'BRMapp.models' has no attribute 'objects' Myrest of the code is absolutely correct.Please tell how can I correct this AttributeError.. -
Can I programmatically change in django crispy forms the StrictButton part of the helper?
I see this documentation: https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html?highlight=change%20helper%20in%20view#manipulating-a-helper-in-a-view and https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html I'd like to change the button description in the view: form.py class GenericButtonForm(forms.Form): def __init__(self, *args, **kwargs): super(GenericButtonForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' #self.helper.form_action = 'catalog:ave-properties' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap4/layout/inline_field.html' self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), ) views.py @login_required def CheckAveView(request): template_name='catalog/check_AVE.html' if request.method == 'POST': GenericButtonForm_inst = GenericButtonForm() GenericButtonForm_inst.helper.form_action = reverse('catalog:ave-properties') # Can I change the butto descriprion? 'I'd like to change this' ave_props = check_AVE_query_json(sess) else: ave_props = '' GenericButtonForm_inst = GenericButtonForm() context = { 'GenericButtonForm_inst': GenericButtonForm_inst, 'ave_props': ave_props, } return render(request, template_name, context=context) Can I manipulate in the view the button description?: self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), Thanks, Luca -
Trouble in accessing the field value of Foreign Key in Django
class State(models.Model): name = models.CharField(max_length=30) slug = models.SlugField(allow_unicode=True, unique=True, editable=False) def __str__(self): return str(self.name) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) class Location(models.Model): place_name = models.CharField(max_length=256, primary_key=True) latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) state = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.place_name) class Case(models.Model): user = models.ForeignKey(User, related_name = 'Case', on_delete=models.CASCADE, null=True, blank=True) address = models.ForeignKey(Location, null = True, blank=True, on_delete=models.CASCADE, related_name='Case_Place') case_type = models.BooleanField(default=False) # True is Positive or False is Negative. def __str__(self): if self.case_type == True: return str(self.address) + "- Positive" else: return str(self.address) + "- Suspect" def get_absolute_url(self): return reverse('case:all') class Meta: ordering = ['-case_type'] I want to make get state, total(case_type), case_type group by state from Case. And when user clicks any state the following address, total(case_type), case_type group by address from Case is displayed. -
django apache integration missing module
I'm trying to setup my first Django project and I have some issues with the Apache integration. Here my file tree venv-django aci_project/ |_manage.py |_aci_project/ | |_ init.py | |settings.py | | urls.py | |_ asgi.py | |_ wsgi.py | |_aci_api/ |_ init.py |_aci_script |_admin.py |_apps.py |migrations/ | | init.py |_static --> css |_templates --> template html |_tests.py |_urls.py |_views.py Basically, the flow is the following: Browser --> aci_project --> urls.py --> aci_api --> views.py --> call scripts in aci_script If I run the command "python manage.py runserver" it's working fine. Now I'm trying to integrate my Django project with Apache but it's not working. This is my vhost file in Apache: <VirtualHost *:8000> ErrorLog /var/log/httpd/error_log CustomLog /var/log/httpd/access_log combine <Directory /var/opt/aci_project/aci_project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup aciweb01t.stluc.ucl.ac.be WSGIDaemonProcess aciweb01t.stluc.ucl.ac.be group=www-data python-path=/var/opt/aci_project WSGIProcessGroup aciweb01t.stluc.ucl.ac.be WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/opt/aci_project/aci_project/wsgi.py </VirtualHost> here my wsgi.py file in aci_project --> manage.py --> _aci_project import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aci_project.settings') application = get_wsgi_application() And this is the error I have in the apache logs: [Wed Apr 22 16:49:12.468252 2020] [wsgi:error] [pid 7818:tid 140205314995968] [remote 10.195.113.74:28031] mod_wsgi (pid=7818): Failed to exec Python script file '/var/opt/aci_project/aci_project/wsgi.py'. [Wed Apr 22 16:49:12.468453 2020] [wsgi:error] … -
Vue.js and django rest framework for implements a cascading dropdown list
I would need help building a request to my backend API. I currently have a form with a drop down list. The data in this list comes from this.$Http.get('/ quality/api/affaires/') Below this drop-down list, I have another list. This list, I would like it to be empty until the 1st is not selected, then it is implemented with data according to the selection above. Backend side (Django) I have 2 models which are "Affaires" and "AffairesOfs". I used Serialize and I can therefore request each of these models via api/affaires and api/affairesofs In the "AffairesOfs" model I have a foreignekey (idaffaire) on the id of the "Affaires" model. Finally, I would like my second list to be made up of all the “affairesofs” linked to the “Affaires” selected. For now, I have my 2 drop-down lists but I can't find a way to link the second to the first. I tried different methods found on the internet (with the use of v-model, ...) but could not achieve a result. I can't even get the value selected from the first list to display it in the console, or in a . i think I need a change event on the first … -
Unable to used Django-Filter in python 3.6 returns ImportError: cannot import name 'six'
I am new to Django framework and I am encountering an issue when I'm using Django-filter and enter it in INSTALLED_APPS it returns the following error: File "Programs\Python\Python36\lib\site-packages\django_filters\__init__.py", line 7, in <module> from .filterset import FilterSet File "Programs\Python\Python36\lib\site-packages\django_filters\filterset.py", line 10, in <module> from django.utils import six ImportError: cannot import name 'six' I am currently trying to solve the issue but still to no avail . Any help will be greatly appreciated. Thank you -
Form for updating model info is blank
I am trying to provide a form to update user info such as employment, location, birthday, interests. The form I tried to make will not show any of this info however, it just shows a submit button. user_info = models.UserInfo.objects.get(user=request.user) if request.method == 'POST': form = UserChangeForm(data=request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('login:login_view') else: form = UserChangeForm(instance=request.user) context = { 'user_info' : user_info, 'form ' : form } return render(request, 'account.djhtml',context) I'm pretty sure I need to use user_info but Im not to sure how to do that. If anyone can point me in the right direction i'd greatly appreciate it. Thanks <form method="post"action="{% url 'social:account_view' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> The djhtml I tried -
How to import pickled python object into Django view.py file
This file runs perfectly well on its own: import pickle with open('model.obj', 'rb') as f: model = pickle.load(f) print(len(model)) But what I really want to do is to use model, which is a very large stored python dictionary, in my Django views.py file, like so: from django.shortcuts import render from modeler.load_model import model def page(request): return render(request, 'page.html', {'model':model}) However, when I try this, I get the error below: File "C:\Users\mmm\PycharmProjects\MyProject\modeler\load_model.py", line 3, in <module> with open('model.obj', 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'model.obj' I don't understand why, because if I run the first file directly it works fine - the only extra step here is importing it into views.py (I tried including the entire load_model.py code within views.py at first, but got this error, so then tried it in this separate file and it worked on its own, so obviously the issue is that I don't know how to correctly load/import my python model objects or files within Django.