Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to import a small sized MySQL Database to Django?
Schematics Image I have created a simple 5 table SQL Database for my family company. It consists of tables: Companies, CompanyDetails, Contacts, Continents, Products. I am focusing on making a frontend interface for displaying the Companies using drop-down menus for Type, Category, Country and/or Continent. Since, I already learned a bit of Python, I decided to use the Django framework to get it done. Now, I realize that importing a legacy DB using inspectDB is a non-trivial exercise in Django. Would it be a better/easier approach to just create a fresh model in Django and import csv s obtained from the database into it as there are only 5 tables in the first place? If yes, how do I do this in Django? -
ModelForm has no model class specified How can I connect model&form?
I got an error,ValueError at /accounts/upload_save/ ModelForm has no model class specified. I wrote in forms.py class UserImageForm(forms.ModelForm): owner = forms.CharField(max_length=20) image = forms.FileField() in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) in views.py @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = UserImageForm() data.owner = forms.cleaned_data['user'] data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) in index.html <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.What is wrong in my codes?How can I connect model&form? -
Cannot remedy :Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found error
Though I have added the password_reset and password_reset_done module to the Identities/urls.py file, each time I click the Create new password link in my navigation bar I get this error : Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found This is the link to my repository. If you have the time I would really appreciate the help. Thank you in advance. -
module 'importlib._bootstrap' has no attribute '_w_long'
I am trying to install django-adim-tools using pip, but this is what happens: C:\Users\hugo.villalobos>pip install django-admin-tools Could not import runpy module Traceback (most recent call last): File "C:\Python34\Lib\runpy.py", line 14, in <module> import importlib.machinery # importlib first so we can test #15386 via -m File "C:\Python34\Lib\importlib\__init__.py", line 34, in <module> _w_long = _bootstrap._w_long AttributeError: module 'importlib._bootstrap' has no attribute '_w_long' I have no idea how to proceed to solve it. Thanks for your help -
Django CBV: filter images to only service images
Rewriting the logic for django-jquery-file-upload and one particular feature needs to edited. It lists all Picture model saved instead would prefer if it lists all Pictures with the same user_service the model code is below as is for the view. I show how on form_valid i use service_id from a cookie. Last I remember from CBV there's another function like render_response class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'accounts/upload-file.html' def form_valid(self, form): self.object = form.save() user_service = self.request.COOKIES.get('service_id', None) if user_service: exists = UserService.objects.filter(id=user_service) if exists: service = exists[0] obj = self.object obj.user_service = service obj.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') model class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) user_service = models.ForeignKey(UserService, related_name="uploads", blank=True, null=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) … -
django - iterate between json response objects
I have a response object that I am receiving from an api call. The response has several objects that are returned in a single call. What I want to do is grab information from each of the objects returned and store them in varialbes to use them within the application. I know to grab info from a json response when it returns a single objects but I am getting confused with multiples objects... I know how to automate the iteration process through something like a forloop... it wont iterate. here is a sample response that I am getting: I want to grab the _id from both items. { 'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)", 'json':{ '_id':'..6e80', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..22d/nodes/..56e80' } }, 'allowed':'CREDIT-AND-DEBIT', 'client':{ 'id':'..26a34', 'name':'Charlie Brown LLC' }, 'extra':{ 'note':None, 'other':{ }, 'supp_id':'' }, 'info':{ 'account_num':'8902', 'address':'PO BOX 85139, RICHMOND, VA, US', 'balance':{ 'amount':'750.00', 'currency':'USD' }, 'bank_long_name':'CAPITAL ONE N.A.', 'bank_name':'CAPITAL ONE N.A.', 'class':'SAVINGS', 'match_info':{ 'email_match':'not_found', 'name_match':'not_found', 'phonenumber_match':'not_found' }, 'name_on_account':' ', 'nickname':'SynapsePay Test Savings Account - 8902', 'routing_num':'6110', 'type':'BUSINESS' }, <class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'>({ 'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)", 'json':{ '_id':'..56e83', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..d622d/nodes/..6e83' } }, 'allowed':'CREDIT-AND-DEBIT', 'client':{ 'id':'599378ec6aef1b0021026a34', 'name':'Charlie Brown LLC' }, 'extra':{ 'note':None, 'other':{ }, 'supp_id':'' }, 'info':{ 'account_num':'8901', 'address':'PO BOX 85139, RICHMOND, VA, US', 'balance':{ 'amount':'800.00', 'currency':'USD' … -
Couldn't find that app while using pg:copy in heroku
I am trying to migrate the data from my source-app "shielded-dusk-74543" to my target-app "safe-journey-99817" following the information in this link: https://devcenter.heroku.com/articles/upgrading-heroku-postgres-databases The link tell me to do the following command. (I already did the commands before this one, taking the standard-0 plan and putting in maintenance mode) heroku pg:copy source-application::OLIVE HEROKU_POSTGRESQL_PINK -a target- application ! WARNING: Destructive Action ! Transferring data from source-application::OLIVE to HEROKU_POSTGRESQL_PINK ! This command will affect the app: target-application ! To proceed, type "target-application" or re-run this command with -- confirm new-application Then I'll run this command from my target application it appears this error: heroku pg:copy source-application::shielded-dusk-74543 HEROKU_POSTGRESQL_MAROON_URL -a target-application ! Couldn't find that app. And sometimes doing the same thing appears this error: heroku pg:copy source-application::shielded-dusk-74543 HEROKU_POSTGRESQL_MAROON_URL -a target-application ! You do not have access to the app source-application. Both applications are in the same account and I am logged in the account. I did a new website and I want to migrate the information I added in the admin panel from the older website to the new one. Struggling with this problem during a week. -
How to display django form in modal window?
I saw this post, but it did not help me In the modal window, the form is not displayed. View: class CreateOrder(FormView): template_name = 'toner/add_order.html' form_class = OrderForm success_url = '/toner/' def form_valid(self, form): form.save() return super(CreateOrder, self).form_valid(form) add_order.html: <div id="order" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div class="container txt-box"> <form action="{% url 'add_order' %}" role="form" method="post"> {% csrf_token %} {{ form.media }} {{ form.address }} {{ form.room }} {{ form.count }} <button class="btn btn-success" type="submit"> Done </button> </form> </div> </div> </div> </div> main_page.html: {% extends 'toner/base.html' %} {% block main_page %} .... <div> <button class="btn btn-primary" data-toggle="modal" data- target="#order"> Order </button> {% include "toner/add_order.html" %} </div> {% endblock %} urls: url(r'add_order/$', CreateOrder.as_view(), name='add_order'), If I go directly to the url (/add_order) it works. I can see the form. But from main_page.html the modal window is empty. Maybe someone has solved for themselves such a task? -
Angular 4 to Django REST image upload
i have a django REST API with a models.ImageField(), i can upload photos just fine from django itself, my problem is when im trying to do it from angular. .html <div class="form-group"> <label for="usr">Upload your new photo(Optional):</label> <input type="file" accept=".jpg,.png,.jpeg" (change)="attachFile($event)"> <br> <img src="{{imageSrc}}" height="250" weight="250" alt="Image preview..." /> </div> component.ts Update(form){ let body = { house: 3, photourl: this.imageSrc } console.log(this.imageSrc) this.http.Post('http://127.0.0.1:8000/api/photos', body).subscribe( res => console.log(res)) console.log(form) } attachFile(event) : void { var reader = new FileReader(); let _self = this; reader.onload = function(e) { _self.imageSrc = reader.result; }; reader.readAsDataURL(event.target.files[0]); } -
synapse login - 'str' has no attribute 'clinet' - django
I am working on a django project and I am trying to send a request to the synapse api to login to bank accounts through users login information. Within the api, the documentation says to pass a user id for the request and with the login information for the bank account. I am trying to send the request, but it is giving me the following error message. AttributeError at /login_synapse/ 'str' object has no attribute 'client' Request Method: POST Request URL: http://127.0.0.1:8000/login_synapse/ Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'client' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/nodes/ach_us_node.py in create_via_bank_login, line 39 Here is what the documentation is showing that I need to pass: Path Params user_id: required string The user ID of the user you wish to add the ACH-US node under Body Params type: required string Type of node you wish to add. In this case its always ACH-US info.bank_id: required string User's online banking username info.bank_pw: required string User's online banking password info.bank_name: required string This is the bank_code (i.e. "capone" for Capital One) available at here This is the code that I have for the request: def authorizeLoginSynapse(request, form): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user … -
Change / Filter dropdown list based based on ownership
This has got to be a common requirement but nothing I've found on SO or in Django docs that works for me. I'm really new to Django. My problem: I need to change the list of Areas that are presented in a form dropdown list according to the company that has Area ownership. In my app: Accounts (i.e Users) are members of Company. A Company manages an Area. Within the Area are a number of Routes. Routes can be added/updated/removed or assigned to different Areas by the Company. So on my forms I want to make sure that only Areas that belong to a Company are displayed in the dropdown list. Essentially a user would select an Area, then CRUD routes associated with the Area. class Company(models.Model): name = models.CharField(... account_number = models.CharField(... ... class Account(models.Model): name = models.OneToOneField(User... company = models.ForeignKey(Company) ... class Area(models.Model): owner = models.ForeignKey(Company) number = modes.PositiveIntegerField(... class Route(models.Model): owner = models.ForeignKey(Company) area = models.ForeignKey(Area) In forms.py class RouteCreateForm(forms.ModelForm): class Meta: model= Route fields= [ 'area', 'route_number', ... ] Adding: self.fields['area'].queryset = Area.objects.filter(owner_id = 2) provides the correct filtering but of course is not dynamic. I've a lot of variations on : def __init__(self, *args, **kwargs): … -
Django Class Based View With ModelChoiceField
I've been working with Django for about 3 months now and feel I'm getting a bit better, working my way up to class based views. On the surface they seem cleaner and easier to understand and in some cases they are. In others, not so much. I am trying to use a simple drop down view via ModelChoiceField and a form. I can get it to work with a function based view as shown below in my views.py file: def book_by_name(request): form = BookByName(request.POST or None) if request.method == 'POST': if form.is_valid(): book_byname = form.cleaned_data['dropdown'] return HttpResponseRedirect(book_byname.get_absolute_url1()) return render(request,'library/book_list.html',{'form':form}) Here is my form in forms.py: class BookByName(forms.Form): dropdown = forms.ModelChoiceField(queryset=Book.objects.none()) def __init__(self, *args, **kwargs): super(BookByName, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].queryset = Book.objects.order_by('publisher') This code works. When I have tried to convert to a Class Based View, that's when the trouble begins. I tried to do something like this in views.py: class BookByNameView(FormView, View): form_class = BookByName initial = { 'Book' : Book } template_name = 'library/book_list.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def get_success_url(self, *args): return reverse_lazy('library:book_detail', args = (self.object.id,)) When using this with the same form, I receive … -
After updating table id via csv file when trying to add new field getting - duplicate key value violates unique constraint
Problem. After successful data migration from csv files to django /Postgres application . When I try to add a new record via the application interface getting - duplicate key value violates unique constraint. Basically the app try to generate id's that already migrated. After each attempt ID increments by one so if I have 160 record I have to get this error 160 times and then when I try 160 times the time 161 record saves ok. Any ideas how to solve it? -
How can I allow user to be "sloppy" when entering a Django phone number?
I'm making a Django form to update users membership to a website. I want to be able to store phone numbers. I found django-phonenumber-field which is great. The only problem is that the form I created for the user to enter their phone number is too specific. If the user doesn't enter their number as "+99999999" then they get an input error. I would like for the user to be able to enter their number a variety of ways: 999-999-9999, 9-999-9999, (999)999-9999, etc. What's the best way to accomplish this? My code: models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Member(models.Model): """defines a member for annual registration""" name = models.CharField(max_length=255) mailing_address = models.CharField(max_length=255) home_phone = PhoneNumberField() other_phone = PhoneNumberField(blank=True) email = models.EmailField() forms.py from django import forms from .models import Member class MembershipForm(forms.ModelForm): """form for renewing membership""" class Meta: model = Member fields = ('name', 'mailing_address', 'home_phone', 'other_phone', 'email', ) Thank you for any help! -
Unable to find vulnerability in my django app backed by postgres
My django application hosted in cloud machine with a postgres setup on the same machine. It broke for no reason, by looking into the database, I observed all the tables were deleted, I am not getting any clue how it was deleted automatically. Even looking into the cpu or memory usage of the time when it was broken, all seems fine. This seems to be a attacked by someone, but I am not able to find out the path of the attacker so that it can be fixed. Below is the postgres log that look suspicious to me: 2017-09-27 15:04:19 IST ERROR: must be superuser to use server-side lo_export() 2017-09-27 15:04:19 IST HINT: Anyone can use the client-side lo_export() provided by libpq. 2017-09-27 15:04:19 IST STATEMENT: select lo_export(3660040808, 'ps3651619459') 2017-09-27 15:04:19 IST ERROR: function fun310002(unknown) does not exist at character 8 2017-09-27 15:04:19 IST HINT: No function matches the given name and argument types. You might need to add explicit type casts. 2017-09-27 15:04:19 IST STATEMENT: select Fun310002('chmod 777 ./ps3651619459') 2017-09-27 15:04:20 IST ERROR: function fun310002(unknown) does not exist at character 8 2017-09-27 15:04:20 IST HINT: No function matches the given name and argument types. You might need to add … -
Dockered Django + Celery (`celeryd` and `celerybeat`), tasks are executed but database (SQLite) is not modified. What is wrong?
I suppose the title says it all. I have Dockered Django application. There I have another containers (docker-compose) for celeryd and celerybeat. There I have tasks that adjust database values per minute. I ran it, I saw in my terminal that the tasks executed as below. celerybeat_1 | [2017-09-30 22:11:00,002: INFO/MainProcess] Scheduler: Sending due task airport_management.tasks.my_task (airport_management.tasks.my_task) This task is supposed to alter the database every minutes. It works with non-dockered version of my Django application. But, in Docker the database is not changed. Here is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./nginx:/etc/nginx/conf.d - ./static:/app/static - ./timezone:/etc/localzone depends_on: - web rabbit: image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5672:5672" - "15672:15672" web: build: context: . dockerfile: Dockerfile command: /app/start_web.sh container_name: django_airport volumes: - ./:/app - ./static:/app/static - ./timezone:/etc/localzone expose: - "8080" links: - rabbit depends_on: - rabbit celerybeat: build: context: . dockerfile: Dockerfile command: /app/start_celerybeat.sh volumes: - ./:/app - ./timezone:/etc/localzone links: - rabbit depends_on: - rabbit celeryd: build: context: . dockerfile: Dockerfile command: /app/start_celeryd.sh volumes: - ./:/app - ./timezone:/etc/localzone links: - rabbit depends_on: - rabbit How can I fix this? -
(1054, "Unknown column 'nan' in 'field list'") Django bulk_create
I am getting the following error when trying to insert data using Django's bulk_create method. It doesn't happen for all data being inserted. (1054, "Unknown column 'nan' in 'field list'") I don't really understand where the 'nan' is coming from, as I explicitly declare all my fields here. I am trying to insert a large amount of objects at a time to the database (around 10,000 or more) My code is as follows, where observation is another object, TemporaryPhotometry is the model being used: # With thanks to https://stackoverflow.com/questions/18383471/django-bulk-create-function-example for the # example on how to use the bulk_create function so we don't thrash the DB phot_objects = [ TemporaryPhotometry( calibrated_magnitude=function_to_make_calibrated_magnitude(), calibrated_error=uncertainty_stars[i], magnitude_rms_error=mage_2[i], x=x_2[i], y=y_2[i], alpha_j2000=ra_2[i], delta_j2000=de_2[i], fwhm_world=fwhm_2[i], flags=flag_2[i], magnitude=mag_2[i], observation=observation, ) for i in range(0, len(num_2)) ] TemporaryPhotometry.objects.bulk_create(phot_objects) I would greatly appreciate any help with solving this issue. Thank you. The full stack trace is the following: File "/var/www/image_processing/analysis/utils/calibration.py" in do_calibration 545. TemporaryPhotometry.objects.bulk_create(phot_objects) File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in bulk_create 443. ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in _batched_insert 1099. self._insert(item, fields=fields, using=self.db) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py" in _insert 1076. return query.get_compiler(using=using).execute_sql(return_id) File "/usr/lib64/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 1099. cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py" in execute 65. … -
How to correct relation "auth_user" does not exist LINE 1: INSERT INTO "auth_user" ("password", "last_login", "is_super
I am using postgresql as my database and using email instead of username to authenticate. However each time I attempt to register a new user I get this : relation "auth_user" does not exist LINE 1: INSERT INTO "auth_user" ("password", "last_login", "is_super... This is my code on Github These is the response when I created the database : These is the response when I ran the migrations : If you have time and interest I would love to solve this issue. Thank you in advance. -
Django not working inside "style" attribute
I'm trying to display a table with varying background colors depending on a score. I have the following: {% for thing in all_things %} <tr> <td width="25%">{{thing.name}}</td> <td width="25%">{{thing.age}}</td> <td width="25%" style="backgound-color: rgb({{thing.redcolor}},{{thing.greencolor}},0)">{{thing.score}}</td> <tr> {% endfor %} The table is showing properly, and when i print the thing.redcolor and thing.greencolor they show the values they're supposed to be (integers between 0 and 255), but the background color on the cells isn't working. Any help is appreciated. -
Django DB object filter first not getting new items
For some reason when I run this code it keeps looping over the same object and is not getting any new items from the database. In other words, the print output is just the same object over and over, when it should be iterating over items in the list. Here is my code: from mldb.models import Article article = Article.objects.filter(is_locked=False, is_downloaded=False).first() while article: article.is_locked = True article.save() print '******************************' date = article.datetime title = article.title url = article.url print('date: %s' % date) print('url: %s' % url) print('title: %s' % title) get_article(url, title, article) article = Article.objects.filter(is_locked=False, is_downloaded=False).first() Where mldb.models is: from django.db import models class Article(models.Model): url = models.CharField(max_length=1028) title = models.CharField(max_length=1028) category = models.CharField(max_length=128) locale = models.CharField(max_length=128) section = models.CharField(max_length=512) tag = models.CharField(max_length=128) author = models.CharField(max_length=256) datetime = models.DateTimeField() description = models.TextField() article = models.TextField() is_locked = models.BooleanField(default=False) is_downloaded = models.BooleanField(default=False) def __str__(self): # __unicode__ on Python 2 return self.name class Meta: app_label = 'mldb' I have also tried this but it also does not loop through objects: articles = Article.objects.filter(is_locked=False, is_downloaded=False) for article in articles: ... Any ideas? -
django is not displaying media directory
I have this configuration settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #Some dependencies 'django.template.context_processors.media' ], }, }, ] STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) In my urls.py from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'client' urlpatterns = [ url(r'^$', views.index, name='index'), #some others urls ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My media is uploaded in my root project, in the directory /media/ but, when I try to see those resources in the browser, are not displayed and return 404 error. What I have wrong in my configuration? -
fix django views counter
i am creating a blog using Django and i want to count views for each post, i am calling this function when user read the blog post: def post_detail(request, post_id): if 'viewed_post_%s' % post_id in request.session: pass else: print "adding" add_view = Post.objects.get(id=post_id) add_view.views += 1 add_view.save() request.session['viewed_post_%s' % post_id] = True return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)}) the problem is when logging out and log in again, the post views increase again so why django delete the sessions when user logout and how to fix this thanks in advance -
GenericForeignKeyField not shown in related model api
I want to use GenericForeignKeyField in Tastypie api to bind related social accounts to my api models. this is my tastypie model resource class SocialAccountResource(ModelResource): content_object = GenericForeignKeyField({ Customer: CustomerResource, CompanyInfo: CompanyInfoResource, Profile: ProfileResource }, 'content_object') class Meta: queryset = SocialAccount.objects.all() allowed_methods = ['get'] resource_name = 'social_accounts' and these are in my models.py class SocialAccount(models.Model): name = models.ForeignKey(SocialNetwork, null=True) social_network_link = models.URLField(null=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() company info model implementation: class CompanyInfo(models.Model): .... social_accounts = GenericRelation(SocialAccount) .... what i want is to show the social account for every type of model in tastypie like an inline. and the results in api is: Social Account Api Presentation screenshot and nothing shown in company info or customer api . what should i do to solve this problem -
Django admin inline form from child to parent
I have the following model: class Address(models.Model): street = models.CharField(max_length=255) ... class Person(models.Model): private_address = models.OneToOneField(Address) invoice_address = models.OneToOneField(Address) Now, in the admin form for a Person I would like to display an inline admin form for each of the addresses. I know that I could accomplish this by inverting the relation, but then the distinction between the private and the invoice address becomes more complicated. Am I missing something obvious here or is this not possible out-of-the-box? -
Python3.6 on CentOS certificate verify failed
My Django application is currently running on Python 3.4. I want to move it to 3.6, but I have an issue with SSL certificates. The same application works perfectly fine on python 3.4. It still works fine with python3.6 within Docker container and on Windows PC. The only problem is with CentOS and RedHat (both 6.5). My OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013. Full error: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)> What can I do to fix that? The problem is only for python 3.6.0 and python 3.6.1. Python 3.4 works fine with that code.