Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework multiple fields to one
class Wall(BaseComponent): studs_material = models.CharField(max_length=255, null=True, blank=True) studs_spacing = models.FloatField(null=True, blank=True) studs_size = models.CharField(max_length=255, null=True, blank=True) I have a model that must represent flatten data from different sources. To validate data from this sources I'm using DRF Serializers. I faced the issue how to elegant group 3 fields into one in representation method. Data comes to me in following format: { `studs`: 'Steel, 2x4, 16' } I use model serializer and use source='*' to populate data class FoundationWallSerializer(serializers.ModelSerializer): studs = StudTypeSerializer(source='*', required=False) class Meta: model = Wall fields = ('studs',) in child serializer I do the following thing: class StudTypeSerializer(serializers.Serializer): """ StudType objects are serialized into 'Steel, 2x4, 16" o.c.' notation. """ MATERIAL_CHOICES = ( ('Steel', 'steel'), ) size = serializers.CharField( source='studs_size', label='Type of stud, joist, etc. (2x4, 2x6, etc)') spacing = serializers.FloatField( source='studs_spacing') material = SimulationMappingField(source='studs_material', choices=MATERIAL_CHOICES) def create(self, validated_data): raise NotImplementedError def update(self, instance, validated_data): raise NotImplementedError def to_representation(self, instance): try: material = instance.pop('material') size = instance.pop('size') spacing = instance.pop('spacing') except KeyError: return 'None' return f'{material}, {size}, {spacing}\'\' o.c.' def to_internal_value(self, data): if data == 'None': return {} material, size, spacing = [col.strip() for col in data.split(',')] return { 'material': material, 'size': size, 'spacing': spacing } Problem when … -
Django: Filtering one models records to show all records of other model
I'm trying to filter all subjects from my model subjects, and then show all the evaluations within that subject from my other model evaluations for a specific employee which is also a model. So when I click on a subject, which are fetched from my subject model, I want to get all the evaluations for that employee within that subject. I'm thinking each of the subjects are buttons or anchor tags that when clicked show the evaluations within that subject. Subject model class Subject(models.Model): id = models.AutoField(primary_key=True) subjectname = models.CharField(max_length=255, help_text="Indtast navnet på faget.") slug = models.SlugField(max_length=200, unique=True) Evaluation model class Evaluation(models.Model): id = models.AutoField(primary_key=True) employee_num = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True) subjectname = models.ForeignKey('Subject', on_delete=models.CASCADE, null=True) Employee model class Employee(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) employee_num = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") firstname = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") lastname = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") subjectname = models.ForeignKey('Subject', on_delete=models.CASCADE, null=True) Employee subject view class EmployeeDetailView(DetailView): template_name = 'evalsys/employee/alle_employees_eval.html' model = Employee # Uses employee PK to make a detail view def view_employee_with_pk(self, pk=None): if pk: employee = Employee.objects.get(pk=pk) else: employee = self.employee args = {'employee': employee, } return render(self, 'evalsys/employee/alle_employees_eval.html', args) def get_context_data(self, **kwargs): context = super(EmployeeDetailViewDetailView, self).get_context_data(**kwargs) context['evaluation'] = Evaluering.objects.all() … -
How to fix ImportError: cannot import name 'HTTpResponse' from 'django.http'
After several trials, I still get the same ImportError: cannot import name 'HTTpResponse' from 'django.http' (/Users/mac/my_env/lib/python3.7/site-packages/django/http/init.py) after running '$ python manage.py runserver' in the terminal. Can someone please enlighten me with this issue? Thanks! The code below were originally taken from the Django tutorial on its official website. from django.shortcuts import render from django.http import HTTpResponse def index(request): return HTTpResponse("Hello, world. You're at the polls index.") -
I have a comment model on home page, but it does not autoly detect which post I am writing my comment amongst all posts
So the error I am encountering. Pk can not be recognized. Because there are too many posts on the main page. I have been trying yto solve this by changing pk to id, changing my models of comments many ways. But there is no use The real reason is that ı have to go into detailview so that page can easily detect. Oh look he is here on this page path('post//', PostDetailView.as_view(), name ="post-detail"), so we can save this comment on a spesific post.pk. But I want everything is connected NameError at / name 'pk' is not defined class PostListView(ListView, DetailView): model = Post template_name = "blog/home.html" # <app>/model>_viewtype>html context_object_name = "posts" paginate_by = 15 template = loader.get_template('blog/post_detail.html') def get(self, request, *args, **kwargs): posts = Post.objects.all().order_by("-id") gallerys = Gallery.objects.all() comments = Comment.objects.filter() likes = Post.objects post = request.POST.get(Post) # cnc = Contact.objects.all() today = timezone.now().date() is_liked = False # if posts.likes.filter(id = request.user.id).exists(): # is_liked = True comment_form = CommentForm(request.POST or None) context = { 'posts': posts, "likes": likes,"comment_form":comment_form, "comments": comments, "gallerys":gallerys, "today": today} # return render(request, "blog/home.html") return render(request, "blog/home.html", context) def post(self, request, *args, **kwargs): form = PostForm() posts = Post.objects.all().order_by("-id") data2 = Gallery.objects.all() comments = Comment.objects.filter() likes … -
Is there a way to control the behavior of django-from wizard done() method?
I have 3 forms in django-form wizard which are rendered correctly. After the last form has been filled up, I want to display data of all 3 forms on done.html page using done() method and add a submit button on done.html which will submit the data to the the same or any other view so that I can save it in database. I have to save data across multiple tables so I need to extract data individually from the request object. I have overloaded the done() method in a way to display the data on the page and it is also able to save data in DB. But I want to just display data using done method() and have a submit button on the done.html page to POST the request so that I can save data in DB later. views.py class FormWizardView(SessionWizardView): template_name = 'crispyFormTemplate.html' form_list = [Form1,Form2,Form3] def done(self, form_list,form_dict, **kwargs): return render(self.request, 'done.html', {'form_data': [form.cleaned_data for form in form_list], 'no_of_pages':len(form_list)}) done.html {% extends 'base.html' %} {% block container_body %} <h1>This is done page</h1> <h6>NUmber of pages are: {{ no_of_pages }}</h6> <ul> {% for f in form_data %} <p>{{ forloop.counter }}</p> <li>{{ f }}</li> {% endfor %} </ul> {% … -
HTML - Disabling a widget in one of my pages
I need to disable a widget for some of my pages, How can i do it? A hard try that i thought will be to somehow put a condition in the html (django or php?) of the widget that if the site URL != the URL i don't want. it will appear. How can i do it? Any other different method? the widget code is: <div class="{%- if settings.cart_position == 'side' -%}jas-mini-cart jas-push-menu{%-else-%}dropdown-cart{%-endif-%}"> {%- if settings.cart_position == 'side' -%} <h3 class="mg__0 tc cw bgb tu ls__">{{ 'cart.widget.title' | t }}<i class="close-cart pe-7s-close pa"></i></h3> {%- endif -%} <div class="widget_shopping_cart pr"> <div class="widget_shopping_cart_content"> {%- include 'cart_body' -%} </div> </div> </div> -
quero passar base64 do template para a view
I have a variable that gets a base64 I need to pass to my django view, but it's too big a format to pass in url, how could I pass it? -
Django-Tenants - How to name domain when running in Docker
I want to create the shared tenant and customer tenant schemas with django-tenants, but I'm unsure how to name them since I'm running in a Docker container from 0.0.0.0. from customers.models import Client, Domain domain = Domain() domain.domain = 'my-domain.com' # don't add your port or www here! on a local server you'll want to use localhost here domain.tenant = tenant domain.is_primary = True domain.save() I've tried domain.domain ='t1.0.0.0.0' (for my customer tenant) or domain.domain = '0.0.0.0' (for my shared tenant) with no success. -
Django Rest Framework: Updating subobject with new route, not partial update to model
I'm trying to create an API object, Roster, which has a list of Members as a subobject on it. However, I do not want to update the subobject by partially updating the Roster object -- instead, I want a route for "add member" and "remove member". Goal: GET /Roster/{ROSTERID} response body: { id: {roster id}, members: # members sub object is read only [ {member subobject}, {member subobject}, ... ], } POST /Roster/{RosterID}/AddMember { {member id}, {member id}, ... } and then a similar thing for removing a member. Note: I want to be able to pass a existing member id in. I don't want to create new members here. What should I be looking for in the docs to be able to add a route to update the member list with a user id, instead of having to pass in the whole user object? serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class RosterSerializer(serializers.ModelSerializer): members = serializers.ListField( child=UserSerializer() ) class Meta: model = Roster fields = ('id', 'name', 'members') depth = 2 app/models.py class Members(User): on_pto = models.BooleanField(default=False) class Roster(models.Model): objects = models.Manager() name = models.CharField(max_length=80, blank=True, default='', unique=True, null='') members = models.ForeignKey( … -
Add data to modelserializer field based on request
Basically what I am looking for is to auto-populate the two fields created_by and last_modified_by based on a fixed value. class SupportingAttachment(models.Model): order = models.ForeignKey(Order,null = True,blank = True) file = models.FileField(upload_to= upload_supporting_attachment, null=True, blank=True) created_by = models.ForeignKey(User,blank = True,related_name = 'support_created_by') created = models.DateTimeField(auto_now_add=True) last_modified_by = models.ForeignKey(User,blank = True,related_name = 'support_modified_by') last_modified = models.DateTimeField(auto_now=True) As of now, as a makeshift solution, I am writing a manual serializer and adding the data by overriding the validate function and calling create. def validate(self, attrs): userid = self.context['request'].user.id x = attrs.update({"created_by": userid, "last_modified_by": userid}) return attrs I want to do this in a ModelSerializer without specifying the fields manually. I am assuming I have to override one of the functions of the ModelViewSet or the CreateAPIView So which function do I override on the View layer to set the user_id on the two fields and pass it to the serializer? Also is this the correct way of doing it? -
Djagno: django.db.utils.InternalError: (1046, u'No database selected')
I'm trying to use Django with mariadb 10.4.8 My settings.py file is as follows: DATABASES = { 'default': { 'NAME:': 'mydb', 'ENGINE': 'django.db.backends.mysql', 'USER': 'staff', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '', } } In init.py: import pymysql pymysql.install_as_MySQLdb() "./manage.py makemigrations" and "./manage.py migrate" yield the same error: File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 210, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 55, in table_names return get_names(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 50, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/mysql/introspection.py", line 56, in get_table_list cursor.execute("SHOW FULL TABLES") File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/wemu_app/wemu_app_env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in … -
Move record from first Django model to second and then delete it from first
I want to move a record from NewUsers model to PendingUsers model on the button click. After moving, the record should be removed(deleted) from NewUsers model. Here's the models: class NewUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, default=1) newuser_name = models.CharField(max_length=50) newuser_company = models.CharField(max_length=100) newuser_mobile = models.CharField(max_length=10) newuser_designation = models.CharField(max_length=50) newuser_image = models.ImageField(upload_to='userprofile_pics/users/', blank=True) def __str__(self): return self.user.email class PendingUsers(models.Model): pendinguser = models.OneToOneField(NewUser, on_delete = models.CASCADE, default=1) def __str__(self): return self.pendinguser.newuser_name On Button click, the code to move the record is: query_user = get_object_or_404(NewUser, id=id) pendingUser = PendingUsers() pendingUser.pendinguser = query_user pendingUser.save() And to delete it from NewUsers: NewUser.objects.filter(id=id).delete() It is successfully moving the record to PendingUsers. But as soon as I'm deleting it from NewUser, it is automatically deleted from PendingUser as well. Can anybody help me out with this about how to achieve this successfully? Do I need to change my PendingUsers model? Thanks in advance! -
How can I get my website "Contact Me" Form to arrive at my Gmail?
I am trying to build a contact me form for my portfolio but I am running into issues. Traceback File "..\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner SMTPSenderRefused at / (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError c17sm3159820ild.31 -gsmtp', 'The_email_I_use_on_form@gmail.com') views.py def index_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Send email goes here sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['to_me@gmail.com']) return HttpResponse("Thanks for contacting, We will be in touch soon!") else: form = ContactForm() return render(request, 'index.html', {'form': form }) Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PWD') Forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) I went into my settings on Gmail to see if there could be something in the security settings blocking me from receiving the form submissions, I tried changing the security setting that allows access for less secure apps. Should I choose a different email provider or is there a work-around for this? -
How to resolve this No reverse match found in Django when request.user returns a lazy object
here is my urls.py line path('account/<str:username>/<id>/', creating_unilevels, name="CreatingUnilevels") and the button <a href="{% url 'CreatingUnilevels' id=own_account.id username=request.user %}">View Account</a> and on that page there is a own_account=Account.objects.all().get(id=id) how to resolve this error Reverse for 'CreatingUnilevels' with keyword arguments '{'username': <SimpleLazyObject: <User: samuel>>, 'id': ''}' not found. 1 pattern(s) tried: ['account\\/(?P<username>[^/]+)\\/(?P<id>[^/]+)\\/$'] -
DRF POST Image and Text at the same time
This is what my model looks like: class ExampleModel(models.Model): text = models.CharField(max_length=2) image = models.ImageField(upload_to='Thats all set. Dont worry about it.') I have a standard serializer: class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = "__all__" And then there's my view: class ExampleView(viewsets.ModelViewSet): queryset = ExampleModel.objects.all() serializer_class = ExampleSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = ExampleSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) What I want to know is a) I'm trying to populate the text and model fields using Python requests. requests.post(url, headers="The tokens(Already taken care of)", "How to put in the body? Where and how do I add the image and text?" b) Is there something I need to change or add in either of these or outside to meet my requirement? Any help is appreciated. Thank you for your time reading this :) -
Django - How to create users with the same username and password?
I would like to ask if there is any way to create a user where the username and password are the same. By default when I try to do it from the administrator I get an error saying that the passwords are the same. Even when I try to add some additional initial in the password does not allow me to save it. Is there a way to do it? -
How to filter last item of child collection?
I'm trying to query all posts that have it's last comment created today || haven't yet had comment. How can I make that kind query filter in Django? Here are my Models class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() class Comment(models.Model): content = models.TextField() post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") created_at = models.DateTimeField(auto_now_add=True) -
I encountered "Exception while resolving variable 'redirect_to'" when running a django application
I made a simple application with localization (django 2.2.4). I built a way to change language and used the exact code in https://docs.djangoproject.com/en/2.2/topics/i18n/ when I run it locally using python manage.py runserver it works fine but when I run it through nginx and gunicorn on a different ubuntu server I get Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'RequestContext' has no attribute 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'redirect_to' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: <unprintable VariableDoesNotExist object> ``` There was a python version difference but after upgrading to the same exact versions of python (python3.7) same error occurs. Code that's throwing the exception {% load i18n %} … -
How do i fix No function matches the given name and argument types. You might need to add explicit type casts
already_transferred = Transfer.objects.all().filter(transferred_by=request.user, account_id=id).aggregate(total=Coalesce(Sum('amount'), 0)) and the server is giving this error function sum(text) does not exist LINE 1: SELECT COALESCE(SUM("API_insidetransfer"."amount"), 0) AS "a... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. here is my model class Transfer(models.Model): transferred_by = models.CharField(max_length=120) account_id = models.CharField(max_length=120) amount = models.CharField(max_length=120, default=0) created_on = models.DateTimeField(auto_now=True) how can i fix this? -
Covert two tuples into Dict with one key: multiple values
I have two tuples, and I want to be able to convert them into dic with one key and multiple values. This will be written in python. one_tup = [('A',1),('B',2),('C',3)] two_tup = [('A',2),('B',4),('D',4)] dic = {'A':(1,2),'B':(2,4),'C':(3),'D':(4)} I was wondering if there's a faster and more efficient to do it without looping through each indexes and comparing it and then storing it. Because that's what I'm planning to do but I think it will take really long time given that I have about a couple thousand elements in each array. -
How can I set manage=False for django simple history table
I'm using django-simple-history for my model. I am deleting a field on the model but setting the meta property managed to False. However, this does not translate to the simple history table. Is there a way to achieve this? -
Connection reset by peer after several minutes in django celery
I have deployed a celery app for production but it disconnects from rabbitmq after 5 to 10 minutes after that no response is given from server The error code is: [Errno 104] Connection reset by peer this is my celery.py file django project: import os from celery import Celery from parrot_server import settings BROKER_URL = 'amqp://parrot_user:Alireza@1234@localhost:5672/parrot' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parrot_server.settings') app = Celery('parrot_server', broker=BROKER_URL, backend='rpc://') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request:{0!r}'.format(self.request)) It has 8 functions that 2 of them is called with apply_async function. I look forward to your answer. Thank you -
django-rest-framework Overriding create function not working on ModelSerializer
I want to insert only new data into my database. In case, the data with the same primary key is already in the database, I want to ignore it and not raise an exception. However, the default ModelSerializer's create function seems to raise and exception if the value already exists in the table. So, I am trying to solve this problem by overriding the ModelSerializer's create() function. Here's my code: serializers.py class UsrPlaceMapSerializer(serializers.ModelSerializer): class Meta: model = UsrPlaceMap fields = '__all__' def create(self, validated_data): place_id = validated_data.get("ggl_plc_id") place_map = UsrPlaceMap.objects.filter(ggl_plc_id=place_id) print("USRMAP INIT") if place_map is not None: print("USRMAP NOT NONE") return place_map place_map = UsrPlaceMap.objects.create(ggl_plc_id=place_id, state=validated_data.get("state"), cty_nm=validated_data.get("cty_nm"), cntry=validated_data.get("cntry")) print("USRMAP CREATED") return place_map models.py class UsrPlaceMap(models.Model): cty_nm = models.CharField(max_length=500) state = models.CharField(max_length=200, blank=True, null=True) cntry = models.CharField(max_length=500) ggl_plc_id = models.CharField(primary_key=True, max_length=500) class Meta: managed = False db_table = 'usr_place_map' and I am calling the seralizer instance's save method using this: instance = UsrPlaceMapSerializer(data=data, many=True) instance.save() However, I get an error if I try to submit values already in the table: { "ggl_plc_id": [ "usr place map with this ggl plc id already exists." ] } } The print statements on the overriddent create() don't print anything either. So, I am guessing … -
When I try to login to Django admin via https, python server was closed without any error
I follow the Official Django tutorial, but I´m stucked in the point where I should login into Admin page. I can fill name and password, but after hit Log in button, python development server ends. I´m running them using this command python manage.py runserver 0.0.0.0:3000 I´m running Linux container on Codeanywhere using Python 3.7 and Django 3.1. Only output I get is: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 04, 2019 - 16:14:47 Django version 3.1, using settings 'buky.settings' Starting development server at http://0.0.0.0:3000/ Quit the server with CONTROL-C. [04/Oct/2019 16:14:48] "GET /admin/ HTTP/1.1" 302 0 [04/Oct/2019 16:14:49] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1916 [04/Oct/2019 16:14:49] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [04/Oct/2019 16:14:49] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [04/Oct/2019 16:14:49] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [04/Oct/2019 16:14:49] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [04/Oct/2019 16:14:50] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [04/Oct/2019 16:14:50] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [04/Oct/2019 16:14:57] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 My urls.py is like in tutorial: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] What can be wrong? Thanks Alex -
Access webhook information from Dialogflow in Django
I have configured Dialogflow to make a POST request after a name is asked. When I view the information in an online request viewer I can see the information I want in the Query strings section: > { "responseId": "045c0d0b-7b5b-448e...", > "queryResult": { > "queryText": "rob", > "parameters": { > "last-name": "lastname", > "given-name": "Rob" > }, In Django however, I cannot find this information. I tried to save the full request and request.META in the database. The received request on my server looks like: {'QUERY_STRING': '', 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/json', 'CONTENT_LENGTH': '5323', 'REQUEST_URI': '/folder', 'PATH_INFO': '/folder', 'DOCUMENT_ROOT': '/home/info/domains/mysite.info/private_html', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTPS': 'on', 'REMOTE_ADDR': '64.233.172.250', 'REMOTE_PORT': '53451', 'SERVER_PORT': '443', 'SERVER_NAME': 'mysite.info', 'HTTP_CONTENT_TYPE': 'application/json', 'HTTP_HOST': 'www.mysite.info', 'HTTP_CONTENT_LENGTH': '5323', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_ACCEPT': '/', 'HTTP_USER_AGENT': 'Google-Dialogflow', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,br', 'wsgi.input': , 'wsgi.file_wrapper': , 'wsgi.version': (1, 0), 'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='UTF-8'>, 'wsgi.run_once': False, 'wsgi.multithread': False, 'wsgi.multiprocess': True, 'wsgi.url_scheme': 'https', 'uwsgi.version': b'2.0.18', 'uwsgi.node': b'server.mysite.info', 'SCRIPT_NAME': ''} I use Nginx with Uwsgi How do I access the full information in Django?