Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting RelatedObjectDoesNotExist at /admin/login/. How do I successfully create user profiles in Django via a one to one relationship?
I'm trying to extend the built-in user and add some more information to it. I have two apps in my django project- general and user_details. Inside my user_details app, in the models.py file, I have the following... from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from general.models import Ward class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstname = models.CharField(max_length=20) middlename = models.CharField(max_length=20) lastname = models.CharField(max_length=20) loc_id = models.CharField(max_length=8, unique=True) ward = models.ForeignKey(Ward, related_name="wards", on_delete=models.CASCADE) phone = models.CharField(max_length=10, unique=True) address = models.CharField(max_length=255) postal_code = models.CharField(max_length=15) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "User details" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() I have successfully done this before but today for some reason I keep getting the RelatedObjectDoesNotExist at /admin/login/, no such column: user_details_profile.id. Can anyone tell me what I am doing wrong please and how I can get it to work. Help. -
Relations setup for ecommerce products using django?
from django.db import models class books_category(models.Model): name =models.CharField(max_length=200,unique=True) description =models.TextField() #slug =models.SlugField(max_length=200,unique=True,help_text='unique value for product page url') is_active =models.BooleanField(default=True) #meta_keywards =models.CharField("meta_keyward",max_length=255,help_text='Comma-delimited of SEO keywards for meta tag') #meta_description =models.CharField("meta_description",max_length=255,help_text='content for meta tag') created_at =models.DateTimeField(auto_now_add=True) updated_at =models.DateTimeField(auto_now=True) def __str__(self): return self.name class books(models.Model): name =models.CharField(max_length=200,unique=True) description =models.TextField() #slug =models.SlugField(max_length=200,unique=True) author =models.CharField(max_length=200) publisher =models.CharField(max_length=200) is_active =models.BooleanField(default=True) is_bestseller =models.BooleanField(default=False) is_featured =models.BooleanField(default=False) is_deal_of_the_day =models.BooleanField(default=False) is_new_arrival =models.BooleanField(default=False) quantity =models.IntegerField() image =models.ImageField(upload_to='product/',blank=True) #meta_keywards =models.CharField("meta_keyward",max_length=255,help_text='Comma-delimited of SEO keywards for meta tag') #meta_description =models.CharField("meta_description",max_length=255,help_text='content for meta tag') created_at =models.DateTimeField(auto_now_add=True) updated_at =models.DateTimeField(auto_now=True) old_price =models.DecimalField(decimal_places=2,max_digits=10,null=True) price =models.DecimalField(decimal_places=2,max_digits=10,blank=True,default=0.00) #categories =models.OneToManyField(category_name) def __str__(self): return self.name class cricket_bat(models.Model): name =models.CharField(max_length=200,unique=True) description =models.TextField() size =models.CharField(max_length=100) willow_type =models.CharField(max_length=100) width =models.IntegerField() height =models.IntegerField() brand_name =models.CharField(max_length=100) cover_included =models.BooleanField(default=True) toe_guard =models.BooleanField(default=True) ideal_for =models.CharField(max_length=100) #men,boys,women,girls suitable_for =models.CharField(max_length=100) #ball type curve =models.BooleanField(default=True) anti_scuff_sheet =models.BooleanField(default=False) handle_type =models.CharField(max_length=100) handle_grip_type =models.CharField(max_length=100) handle_material =models.CharField(max_length=100) age_group =models.PositiveIntegerField() created_at =models.DateTimeField(auto_now_add=True) updated_at =models.DateTimeField(auto_now=True) old_price =models.DecimalField(decimal_places=2,max_digits=10,null=True) price =models.DecimalField(decimal_places=2,max_digits=10,blank=True,default=0.00) def __str__(self): return self.name This how my code looks like. Bascially I want it to be more efficient by creating a class in which I can store all the fields and then call the specific fields for specific products but I am not sure whether it is possible in django or not. Any help would be fruitful thank you. -
Django 3.7, IntegrityError, NOT NULL constraint failed: papers_paper.seminary_id
I'm new to django and I'm teaching myself mostly with help of tutorials and 'trial and error'. I have searched stackoverflow, but none of the previous questions seem to fit to my problem. For example, they refer to blank CharFields, which I don't think is my problem here. I thought, that I linked the two classes Seminary and Paper via the ForeignKey. Right now I can add Seminary to the database via the appropiate form and display it the way I want it. But with a second form considering the class Paper, django gives me the error: Request Method: POST Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: papers_paper.seminary_id papers is my app, btw Here is models.py, without meta: class Seminary(models.Model): slug = models.SlugField(unique=True) seminary_type = models.CharField(max_length=25, choices=choices.SEMINARY_TYPE_CHOICES) seminary_title = models.CharField(max_length=200) seminary_year = models.IntegerField(choices=choices.YEAR_CHOICES, default=datetime.now().year) summer_winter = models.CharField(max_length=6, choices=choices.SEASON_CHOICES, default="S") def get_absolute_url(self): return reverse('papers:paper-detail', kwargs={'slug': self.slug}) def __str__(self): return self.seminary_title def create_slug(instance, new_slug=None): slug = slugify(instance.seminary_title) if new_slug is not None: slug = new_slug qs = Seminary.objects.filter(slug=slug) exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().pk) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Seminary) class Paper(models.Model): seminary … -
how to fix heroku "Application error" where console error "code=H14 desc="No web processes running"
I'm trying to deploy django project on Heroku. My setting are: DEBUG = False ALLOWED_HOSTS = ['*'] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware',] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'startshop/static/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' import dj_database_url DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) Procfile is - "web: gunicorn startshop.wsgi --log-file -" Runtime is - "python-3.6.6" WSGI is - import os from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "startshop.settings") application = get_wsgi_application() application = WhiteNoise(application) When I typing "heroku ps:scale web=1", I get error "Couldn't find that process type." -
How to refactor it to CBV django?
I'm beginner in CBV and find help to refactor my FBV. Maybe you can show me some examples or advices for it. I also have a problem with DRY principle as you can see. My FBV: def formen(request): html = 'man_index.html' ip, is_routable = get_client_ip(request) if request.user.is_authenticated and request.user.sex == 'M': queryset = Post.objects.filter(sex=request.user.sex, is_published=True) query = request.GET.get('q') if query: queryset = queryset.filter(title__icontains=query) paginator = Paginator(queryset, 6) page = request.GET.get('page') try: elements = paginator.page(page) except PageNotAnInteger: elements = paginator.page(1) except EmptyPage: elements = paginator.page(paginator.num_pages) elements = paginator.get_page(page) context = { 'all_posts': elements, 'page_range' : paginator.page_range, } elif request.user.is_authenticated and request.user.sex == 'W': return redirect('/forwomen') else: queryset = Post.objects.filter(sex='M', is_published=True) query = request.GET.get('q') if query: queryset = queryset.filter(title__icontains=query) paginator = Paginator(queryset, 3) page = request.GET.get('page') try: elements = paginator.page(page) except PageNotAnInteger: elements = paginator.page(1) except EmptyPage: elements = paginator.page(paginator.num_pages) elements = paginator.get_page(page) context = { 'all_posts': elements, 'page_range' : paginator.page_range, } return render(request, html, context) What methods should I use to refactor it to CVB? -
Problems to get related fields serialized (manytomany etc) ... looking for good practices
I've got some problems to understand the right way serializing data with django-rest-framework e.g. using data from related models. Let me explain a little bit my situation: I have an Organization model with a manytomany relation to a Subtopic model classifying each organiaztion. Further each subtopic belongs to a general topic. In addition there is an OrgaDataSet model to save crawled data for each organization in a PostgreSQL JSONField. The field "type" in the OrgaDataSet Model should give me a kind of flexibility to classify crawled data in further stages. # models.py class Topic(models.Model): name = models.CharField(max_length=200, unique=True) class Subtopic(models.Model): name = models.CharField(max_length=100, unique=True) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) class Organization(models.Model): name = models.CharField(max_length=300, unique=True) description = models.TextField(blank=True, null=True) subtopics = models.ManyToManyField(Subtopic) class OrgaDataSet(models.Model): data_set_types = ( ('ADDRESS', 'address'), ('PERSON', 'person'), ('DIVISION', 'division'), ) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) type = models.CharField(max_length=20, choices=data_set_types) crawled_data = JSONField(verbose_name='Data set') But lets come up with my questions / problems: 1. How can I serialize the related data with minimized database requests and get an customized serialized field like: "topics_list": [ { "topic_name": "Medical science", "subtopics": [ "Dental products", "Hygiene" ] }, { "topic_name": "Biotechnology", "subtopics": [ "Microbiology" ] } ], I tried different approaches: amongst … -
Paho publish.single ssl certificate hostname verification fails because it's gettign the wrong network interface's IP
I'm having trouble with the ssl handshake when using the paho python library. I call publish.single providing the hostname argument of my broker: auth = {'username':'foo', 'password': 'bar'} tls = {} publish.single( "mytopic", payload="mypayload", hostname=mqtt.example.com, port=8883, auth=auth, tls=tls, ) Here's the source for the client setting the TLS data. None of the params are compulsory, and it should just verify the certificate is signed by the default system certificate authority. The trouble is when I call publish.single, line 694 of ssl.py seems to be getting passed the the private network interface IP (10.X.X.X) for self.server_hostname. Here's a partial trace: File “/srv/exampleproject/exampleapp/views.py” in dispatch return super(DevicePostMessage, self).dispatch(request, *args, **kwargs) File “/srv/lib/python3.6/site-packages/django/views/generic/base.py” in dispatch return handler(request, *args, **kwargs) File “/srv/lib/python3.6/site-packages/django/utils/decorators.py” in _wrapper return bound_method(*args, **kwargs) File “/srv/lib/python3.6/site-packages/django/views/decorators/csrf.py” in wrapped_view return view_func(*args, **kwargs) File “/srv/exampleproject/exampleapp/views.py” in post tls=tls, File “/srv/lib/python3.6/site-packages/paho/mqtt/publish.py” in single protocol, transport) File “/srv/lib/python3.6/site-packages/paho/mqtt/publish.py” in multiple client.connect(hostname, port, keepalive) File “/srv/lib/python3.6/site-packages/paho/mqtt/client.py” in connect return self.reconnect() File “/srv/lib/python3.6/site-packages/paho/mqtt/client.py” in reconnect sock.do_handshake() File “/usr/lib/python3.6/ssl.py” in do_handshake self._sslobj.do_handshake() File “/usr/lib/python3.6/ssl.py” in do_handshake match_hostname(self.getpeercert(), self.server_hostname) File “/usr/lib/python3.6/ssl.py” in match_hostname % (hostname, dnsnames[0])) Exception Type: CertificateError at /device/postmessage Exception Value: hostname ‘10.XX.XX.XX’ doesn't match ‘mqtt.example.com’ I'm definitely connecting over the internet and not using the private … -
Django re-style form
i currently try to "style" my form. in General i get the concept behind it but not at that point: This is who its intendet to be (and not working): class RegistrationForm(UserCreationForm): username = forms.CharField(required=True, label='Username', widget=forms.TextInput(attrs={'class': 'class-one-input-fields'})) password1 = forms.CharField(required=True, label='Password', widget=forms.PasswordInput(attrs={'class': 'class-one-input-fields'})) password2 = forms.CharField(required=True, label='Password confirmation', widget=forms.PasswordInput(attrs={'class': 'class-one-input-fields'})) pubpgp = forms.CharField(required=True, label='Public PGP Key', widget=forms.Textarea(attrs={'class': 'class-two-input-fields'})) captcha = CaptchaField() def save(self, commit=True): username = super(RegistrationForm, self).save(commit=False) username.pubpgp = self.cleaned_data['pubpgp'] if commit: username.save() return username The error i get is: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' in my settings.py i set: AUTH_USER_MODEL = 'accounts.User' This is the current working state: class RegistrationForm(UserCreationForm): user = forms.CharField(required=True) class Meta: model = User fields = ( 'user', 'password1', 'password2', 'pubpgp' ) captcha = CaptchaField() def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.pubpgp = self.cleaned_data['pubpgp'] if commit: user.save() return user -
Images size in mb could not be uploaded to my django website hosted on aws
My django website is hosted on aws and I am using postgresql database from aws RDS.For media files I am using local directory of application. mywebsite-- |--home-- |--mywebsite-- |--media-- |<location for media files> and I have my website asking for uploading an image <input type="file" accept="image/*" name="image"></input> <input type="submit" value="submit" name="imagesubmit"></input> I have tried model with defining ImageField as well as FileField. but still the images which are less than 1 mb are able to be uploaded to the server but images with size more than 1 mb could not be. although when I tried FileField in model with uploading the pdf file instead of image it is working fine for pdf files with size more than 1 mb. I check my uploaded image or file by this <a href="{{user.userprofile.file.url}}" target="_blank">click here to see uploaded file</a> here user.userprofile (one to one relationship) and file is model field (test1 with ImageField and test2 with FileField) defined inside the userprofile model. I have searched many places but I could not get the answer why this problem is happening with me.I want to make user able to upload any size of image file. -
How to call Django function using AJAX properly?
I would like to call function on button click without page refresh in Django so I am using AJAX but it does not work. I haven't know about AJAX before and I am new in it but this is what I managed after 3 days of testing: Views.py are working but AJAX function does not. It prints Ups, NOT AJAX views.py: bot = Instagram() def instabot(request): template = 'instabot.html' return render(request, template) def runinstabot(request): print('Welcome here') if request.method == 'POST': runinstabot.login = request.POST.get('login') runinstabot.password = request.POST.get('password') if request.is_ajax(): bot.login(runinstabot.login, runinstabot.password) bot.search() else: print('Ups, NOT AJAX') print(request.POST) return HttpResponse('') instabot.html: {% load static %} <!DOCTYPE html> <html> <head> <title>test bot</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> TEST: <form id='runbot' action='/runinstabot/' method="post" > {% csrf_token %} <input type='text' id='login' /> <input type='text' id='password' /> <input type="submit" value="Submit"> </form> </body> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"> $('runbot').on('submit', function(event){ event.preventDefault(); $.ajax({ type:"POST", url: "{ url 'runinstabot' }", data: { login:$('#login').val(), password:$('#password').val(), csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() }, }); }); </script> </html> urls.py: url(r'^instabot/', instabot, name='instabot'), url(r'^runinstabot/', runinstabot, name='runinstabot'), Instagram() is a python code that use Selenium to automate some stuff I would appriciate all advises -
Django - how to make custom field in inline hidden?
Django 2.1. I have this code: class AnswerInline(admin.StackedInline): model = Answer form = AnswerForm fields = ("question_answer_type", "answer_plain") readonly_fields = ("question_answer_type",) def question_answer_type(self, row): return row.question.answer_type This works and I have new field "question_answer_type" in inline instances. Now I want to make this field hidden. (I want use its content in JavaScript.) I know there is forms.widgets.HiddenInput which I should probably use. But how to use it? -
Allow large file upload from browser while navigating to other page
I'm building a website with Django 1.11 with a fairly simple javascript/html/css part (no framework like Vuejs). I have page reload on each navigation which is fine for my use case. For convenience, I serve my website from App Engine Standard and it's going well so far. Now, I need my user to be able to upload files (up to 300MB size). Due to App Engine's limitation on request size (32MB), I'm using signed urls so I can send these files directly from my client's Javascript to Cloud Storage. Due to the size of the files, the upload may take some time, but I can't seem to navigate to another page since it may cancel the upload. I understand that for a case like this a client app like single-page app in Vuejs for example would be appropriate but is there a way to achieve this with my current setup without rewriting my whole website (with possibly Vuejs and Django REST API)? Any suggestions would be much appreciated. -
What does it mean when written id=-1 in django request?
I'm reading someone's code, and there is written get_object_or_404(Order, id=-1) Could someone explain the purpose of id=-1? -
How to render my Sudoku generator results to html table using Django?
I am pretty new to Django and currently making a Sudoku web app. I wrote a python program to generate the Sudoku games, here is an example of the result/matrix looks like when i run the code (Sudoku Generator.py). [[3, 8, 2, 7, 5, 6, 1, 4, 9],[1, 4, 5, 2, 3, 9, 6, 7, 8],[6, 7, 9, 1, 4, 8, 2, 3, 5],[2, 1, 3, 4, 6, 5, 8, 9, 7],[4, 5, 6, 8, 9, 7, 3, 1, 2],[7, 9, 8, 3, 1, 2, 4, 5, 6],[5, 2, 1, 6, 7, 3, 9, 8, 4],[8, 3, 7, 9, 2, 4, 5, 6, 1],[9, 6, 4, 5, 8, 1, 7, 2, 3]] My question is, how can I render all these generated numbers to my html file? here is the html codes i've created under the templates: {% extends 'base.html' %} {% block sudoku %} <style> table { border-collapse: collapse; font-family: Calibri, sans-serif; } colgroup, tbody { border: solid medium; } td { border: solid thin; height: 1.4em; width: 1.4em; text-align: center; padding: 0; } </style> <table> <caption>Sudoku of the day</caption> <colgroup><col><col><col> <colgroup><col><col><col> <colgroup><col><col><col> <tbody> <tr> <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr> <td> <td> <td> <td> … -
Object_list does not show correct data in template
I've a strange problem in Django template. It is a template for show a list of the articles and for everyone of they I show a list of keyword that I've called key concepts. The stranger thing is that instead of a list of key concepts it is shown a list of articles that use that key concept. Below the E/R diagram and model and template of my project: Models.py class KeyConceptModel(models.Model): concept_text = models.CharField(max_length=50) def __str__(self): return self.concept_text def get_absolute_url(self): return reverse("keyconceptManuscriptusView", kwargs={"pk": self.pk}) class Meta: verbose_name = "Concetto chiave" verbose_name_plural = "Concetti chiave" class PostModel(models.Model): post_title = models.CharField(max_length=70) post_short_description = models.TextField(max_length=200) post_contents = models.TextField() post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE) post_keyconcept = models.ManyToManyField(KeyConceptModel) slug = models.SlugField(verbose_name="Slug", unique="True") post_highlighted = models.BooleanField(default=False) def __str__(self): return self.post_title def get_absolute_url(self): return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Articolo" verbose_name_plural = "Articoli" Template {% for posts in object_list %} <div id="news" class="container"> <div class="row"> <img class="img-fluid" src="{% static 'manuscriptus/img/demo_img.png' %}" alt="Header image"> </div> <div class="row"> <div class="col-3"> <div class="row"> <small class="text-muted">Pubblicato il <strong>{{ posts.post_publishing_date|date }}</strong></small> </div> <div class="row"> {% for keyword in object_list.all %} <p>{{ keyword }}</p> {% endfor %} </div> </div> <div class="col-9"> <div class="row"> <p class="h3"><a href="{{ posts.get_absolute_url … -
JsGrid loading nested object into table
I am developing a web project in Django and using jsGrid. I encountered a problem and couldn't find a solution. I have a nested JSON data which is created by combinating multiple DB table records. Here is my JSON : { "count":3, "results":[ { "personnel":{ "name":"david", "age":34 }, "company":"IBM" }, { "personnel":{ "name":"john", "age":28 }, "company":"Google" }, { "personnel":{ "name":"Yuri", "age":42 }, "company":"Microsoft" } ] } Here is my js script: function () { $("#personnelsgrid").jsGrid({ height: "500px", width: "100%", filtering: !0, editing: !0, sorting: !0, paging: !0, autoload: !0, pageSize: 15, pageButtonCount: 5, deleteConfirm: "Do you really want to delete the client?", controller: { loadData: function (filter) { return $.ajax({ type: "GET", url: "/get_personnels", dataType: "json", data: filter }); } }, fields: [ {name: "personnel.name", type: "text", width: 50}, {name: "personnel.age", type: "number", width: 50, filtering: false}, {name: "company", type: "text", width: 200}, ] As it is seen, I have a nested objects in my data. Although the JSON comes from the server, it is not loaded in jsGrid table. What should I do? -
How can I delete package after I make reusable app
I make a app named polls copy from (https://docs.djangoproject.com/en/2.1/intro/reusable-apps/). When i run python manage.py startapp polls the second, raise error "CommandError: 'polls' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name." How can i delete the package. I do not want name an anther app thanks for your help. -
GUnicorn and Django for 500 concurrent requests with limited resources
I was tasked with creating a Django-Gunicorn demo app. In this task, I need to be able to handle 500 concurrent login requests in 1 second. I have to deploy the app in a VM with 2GB RAM and 2 core CPUs (using Vagrant and VirtualBox, Ubuntu 16.04). I already tried the following for deployment. gunicorn --workers 5 --bind "0.0.0.0:8000" --worker-class "gevent" --keep-alive 5 project.wsgi Using JMeter test from the host machine, the test always takes around 7-10 seconds. Even if the login endpoint only returns empty response without any database access, the amount of the time is almost the same. Can you tell me what's wrong with this? -
Uploaded images automaticaly have 7 random charcters appended to the file nameafter save making them broken image links
Uploaded images automaticaly have 7 random charcters appended to the file nameafter save making them broken image links How can I fix this please? -
Django migration error when changing manytomany field to Foreign key
Initially my models.py looked liked this class P (models.Model): first_name=models.CharField(max_length=100); def __str__(self): return self.first_name class T (models.Model): p_id=models.ManyToManyField(P) Everything was working great. then i changed class T as below: class T (models.Model): p_id=models.ForeignKey(P,on_delete=models.CASCADE,default=None,null=True) #I have added default values coz django asks me to during migrations I get following error: django.db.utils.ProgrammingError: column "p_id_id" does not exist Previously when such error happened I used to delete all tables from Postgresql DB, then comment out entire models.py in my app, run a fake migration, then uncomment models.py and run migrations again and it would work. But this destroys all data in DB. Is there a way to make it work without deleting any data? -
DIsallowed Host when using pythonanywhere with Django App
Background I followed this tutorial with a test django app, to get a feel for how pythonanywhere works. I completed the tutorial with no errors up until the "Check out your site!" section. Error I keep getting the following error when using pyhonanywhere to deploy my Django app. Invalid HTTP_HOST header: 'mysite.pythonanywhere.com'. You may need to add 'mysite.pythonanywhere.com' to ALLOWED_HOSTS. However my code contains: ALLOWED_HOSTS = ['mysite.pythonanywhere.com'] I tried editing ALLOWED_HOSTS = ['*'] however I am still getting the same error. I followed this forum topic, pulled the above change from github, cd mysite git pull but the error persits. I can confirm that the settings.py file in side the Files section of pythonanywhere is indeed showing my github changes with ALLOWED_HOSTS = ['*']. Any ideas on how I can solved this problem? -
How to return from another function in Django View function
I have a function in views.py def login(request): actor = LoginActor(request) actor.authenticated_user() # Cannot use return here, this is problematic, we need to redirect here without using a return statement ctx = actor.get() if request.method == 'POST': ctx = actor.post() return render(request, 'user/forms/auth.jinja', ctx) return render(request, 'user/login.jinja', ctx) and there is a redirect in authenticated_user() function which is defined as: def authenticated_user(self): if self.request.user and self.request.user.is_authenticated: return redirect('home') How do i return from the initial view without calling a return, basically i want to return the callee function where there is a return in called function I am using Django 2.1 with Python 3.7 -
Django : creating a field having the value of the (django-generated ) primary key of the same model
I'm trying to create an integer field (topic_id) equal to the Django-generated primary key value (id). class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) topic_id = ????? Thx for your time. -
Django is_valid returns false
I want to add some fields to djangos username and password. The "is_valid()" returns always false. I was able to find out that form.data is filled with data. views.py: def registrieren(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): xyz.py: from django.contrib.auth.models import AbstractUser from django.db import models from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import ImmoUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = ImmoUser fields = ('name', 'vorname', 'firma', 'anzahlMietobjekte', 'strasseHausnummer', 'adresszusatz', 'plz', 'ort') models.py: class ImmoUser(AbstractUser): name = models.CharField(max_length=100) vorname = models.CharField(max_length=100) firma = models.CharField(max_length=100) anzahlMietobjekte = models.CharField(max_length=100) strasseHausnummer = models.CharField(max_length=100) adresszusatz = models.CharField(max_length=100) plz = models.CharField(max_length=100) ort = models.CharField(max_length=100) -
Django: How to depend on an externally ID, which can be switched?
Consider the following scenario: Our Django database objects must rely on IDs that are provided by external service A (ESA) - this is because we use this ID to pull the information about objects that aren't created yet from the external directly. ESA might shut down soon, so we also pull information about the same objects from external service B (ESB), and save them as a fallback. Because these IDs are relied on heavily in views and URLs, the ideal scenario would be to use a @property: @property dynamic_id = ESA_id And then, if ESA shuts down, we can switch easily by changing dynamic_id to ESB_id. The problem with this though, is that properties cannot be used in queryset filters and various other scenarios, which is also a must in this case. My current thought is to just save ESA_id, ESB_id, and dynamic_ID as regular fields separately and assign dynamic_ID = ESA_id, and then, in case ESA shuts down, simply go over the objects and do dynamic_ID = ESB_id. But I feel there must be a better way?