Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Ecommerce site
would it be possible to build a shopping cart and stripe payment system on top of Wagtail by overriding serve() and placing the following views information inside? The following views.py and urls.py are parts of my ecommerce site that I would like to build into my wagtail site. Example of a Views.py def paymentMethod(request): return render( request, 'checkout/payment_method.html', ) def get_user_pending_order(request): # get order for the correct user user_profile = get_object_or_404(Profile, user=request.user) order = Order.objects.filter(owner=user_profile, is_ordered=False) if order.exists(): # get the only order in the list of filtered orders return order[0] return 0 def add_to_cart(request, **kwargs): #get the user Profile user_profile = get_object_or_404(Profile, user=request.user) #filter products for id product = Product.objects.filter(id=kwargs.get('item_id', "")).first() #check if the user already owns the product if product in request.user.user_profile.merchandise.all(): messages.info(request, "You already own this product") return redirect(reverse('product_list')) #create OrderItem of the selected product order_item, status = OrderItem.objects.get_or_create(product=product) #create order associate with the user user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False) user_order.items.add(order_item) if status: #generate a reference code user_order.ref_code = generate_order_id() user_order.save() #show confirmataion message and redirect to same page messages.info(request, "item added to cart") #return redirect(reverse('product_list')) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @login_required def delete_from_cart(request, item_id): item_to_delete = OrderItem.objects.filter(pk=item_id) if item_to_delete.exists(): item_to_delete[0].delete() messages.info(request, "Item has been removed from shopping cart") return … -
Django/ Ajax Got readyState: 4 But TypeError on a Django Like/Dislike Post button
I have a Django Post Like/Dislike feature in my App. The feature works amazing on its own. However when I add ajax to the Like/Dislike button the whole thing breaks How can I fix this error TypeError at /posts/charlize/singes-boat-new-york/like_post/\npost_like() got an unexpected keyword argument 'username' Below is my Template <form action="{{post.get_api_like_url}}" method="post"> {% csrf_token %} {% if user in post.likes.all %} <button type="submit" name="post_slug" value="{{ post.slug }}" >LIKE</button> {% else %} <button type="submit" name="post_slug" value="{{ post.slug }}" >DISLIKE</button> {% endif %} </form> Below is my Script <script> $(document).ready(function () { $(".like_button").click(function (event) { event.preventDefault(); var username = "{{ request.user.username }}"; var slug = $(this).attr("value"); var like = $("#like-section"); console.log(username); // This works console.log(slug); // This works $.ajax({ url : "{{post.get_api_like_url}}", type: "POST", data: { "username": username ,"slug": slug, "csrfmiddlewaretoken": "{{ csrf_token }}"}, dataType: "json", success: function (data) { like.html(data["form"]); }, error: function (rs, e) { console.log(rs, e); } }) }) }) </script> Below is my console.log (You can clock on it to enlarge) Below are my views def like_post(request): post = get_object_or_404(Post, slug=request.POST.get("post_slug")) print(post) #This does not print The code does not reach here user = request.user print(user) if user.is_authenticated(): if user in post.likes.all(): post.likes.remove(user) else: post.likes.add(user) context = { … -
How to access a related object's field
I am trying to store the campus that the teacher is associated with in the device model. I tried creating a model method but was unable to access it from the related model. class Campus(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Teacher(models.Model): campus = models.OneToOneField(Campus, on_delete=models.CASCADE, default="Not Assigned") class Device(models.Model): owner = models.ForeignKey(Teacher, on_delete=models.CASCADE) -
Alternative to Redirecting to page in Django to prevent page from refreshing
Hello StackOverflow Community, I'm using Django and Python to write a Social Media App. I have an HTML form that allows users to submit a comment when they hit the 'enter' key. Once the comment has been submitted, my intention is to have the comment to appear underneath the comment form immediately - without refreshing the page. <form id='commentForm' method='POST' enctype="multipart/form-data" type="submit"> {% csrf_token %} <input type='text' id="commentBox" name='content' placeholder="Add Comment"> <input type='hidden' name='post_id' required id='id_post_id' value={{post.id}} /> </form> My views.py file redirects to feed.html when the post is successful, this action causes the page to refresh: @login_required def feed(request): if request.method == 'POST': form = CommentForm(request.POST) created_at = timezone.datetime.now() if form.is_valid(): content = form.cleaned_data.get('content') post_id = request.POST.get('post_id') comment = Comment(content=content, created_at=created_at, user=request.user, post_id=post_id) print(comment) comment.save() print('comment post key:', comment.post.pk) return redirect('feed') else: print('form invalid') I'd like to avoid the page refresh and know that this is probably caused by the redirect. I tried using jQuery to prevent default on the 'submit' event. I'm wondering if anyone is aware of an alternative way to redirect to the exact same place without refreshing the page? I appreciate any time invested to help solve this bug! Thank you :) -
Django project cannot find Installed_app bootstrap admin widgets
I'm trying to run this project https://github.com/v1k45/ponynote But I get an error when running the api. $ python manage.py runserver [19:44:46] Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x101e57048> Traceback (most recent call last): File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "/Users/harrymoreno/.local/share/virtualenvs/ponynote-z8XfAhy2/lib/python3.7/site-packages/django/contrib/admin/widgets.py", line 151 '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must … -
dajaneiro not autocompleting in Sublime Text 3
After installing Dajaneiro in Sublime Text 3 it is not Autocompleting in Sublime Text 3 under Linux. What is wrong? -
django password change form not working.Am only getting 'old password is entered incorrectly'
from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.contrib import messages def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) am not able to change my old password, because am getting incorrect old password error but i can still login with that same old password.But when when i try to change it,it seems to be incorrect -
Using Django REST Framework with sessions-based CSRF
I am using Django + Django REST Framework in an environment where I cannot use cookie-based CSRF tokens; therefore I must run with CSRF_USE_SESSIONS = True. The DRF web UI, however, depends on this cookie for all interactions. It appears this is set by reading the csrftoken cookie and settings the X-CSRFToken header on the subsequent request, which is then consumed by django.middleware.csrf.CsrfViewMiddleware.process_view() if the hidden field is not included in the request body. This is set in this code from rest_framework.templates.rest_framework.base.html: <script> window.drf = { csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}", csrfCookieName: "{{ csrf_cookie_name|default:'csrftoken' }}" }; </script> DRF forms that do not use POST do contain the CSRF token in the form body, so not having the cookie means the web interface does not have access to the CSRF token at all, causing all PUT, PATCH, and DELETE requests to fail with a 403 response. I believe this is a bug in DRF, but it is possible this is intended behavior. Can someone explain how DRF is intended to be used with CSRF_USE_SESSIONS = True? -
Wagtail Views.py and Urls.py creating a shopping cart
I created a wagtail site for a customer and it describes his after-school program for kids program well, but he asked that I add a login portal with the ability to view videos after purchase. I've made something similar in django without Wagtail by writing python functions into the views.py and urls.py pages. Would it be possible to implement something like stripe and a shopping cart into wagtail? I don't care about being able to edit these pages in the admin panel obviously. Can I still use the views.py and url.py for pages ? -
Loading failed for the <script> with source “https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.all.min.js”
I'm using digitalocean Spaces(similar as Amazon S3) as storage for my Django project deployed in digitalocean ubuntu 16.04. There IS a issue when I went to my xadmin page and tired to post something,I met a issue: the header looks very weird: https://https//nyc3.... In firefox the console looks like: Loading failed for the <script> with source “https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.config.js”. add:32:1 Loading failed for the <script> with source “https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.all.min.js”. add:32:1 Loading failed for the <script> with source “https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.config.js”. add:32:1 Loading failed for the <script> with source “https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.all.min.js”. In chrome the console looks like: kjmg.co/:32 GET https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.config.js net::ERR_NAME_NOT_RESOLVED kjmg.co/:14 GET https://nyc3.digitaloceanspaces.com/kjmgstorage/kjmgstorage/xadmin/css/themes/bootstrap-xadmin.css?Expires=1537555567&Signature=ujTVQEOBasAkjxX0xVCSqRlcqu4%3D&AWSAccessKeyId=KQBENRUKO4KD6OLDEZSH net::ERR_ABORTED 403 (Forbidden) 2(index):32 GET https://https//nyc3.digitaloceanspaces.com/kjmgstorage/ueditor/ueditor.config.js net::ERR_NAME_NOT_RESOLVED I tried to change AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' To AWS_S3_ENDPOINT_URL = 'nyc3.digitaloceanspaces.com' But received a error: ValueError: Invalid endpoint: nyc3.digitaloceanspaces.com Then I tried to change STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) To STATIC_URL = '%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) and python manage.py collectstatic and restart the nginx The issue https://https//nyc3.digitaloceanspaces.com/kjmgstorage is still there. ueditor is a plug in my xadmin. Any friend can help? Thank you so much! -
Multiple default values specified for column "id" of table in Django 2.1.1
So I keep getting this error saying that there's multiple specified ID values for the device table, but I don't have a clue where I've specified any kind of default ID. I've tried setting a field as primary_key=True but that didn't solve the problem either. class Campus(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=40) def __str__(self): return self.name class Meta: verbose_name_plural = "Campuses" class Teacher(models.Model): name = models.CharField(max_length=20) phone = models.CharField(max_length=11) department = models.CharField(max_length=20) campus = models.OneToOneField(Campus, on_delete=models.CASCADE, default="Not Assigned") #devices = self.Device.objects.all() def __str__(self): return self.name class Device(models.Model): inUse = 'IU' inStock = 'IS' inMaintenance = 'IM' damaged = 'DM' statusChoices = ( (inUse, 'In Use'), (inStock, 'In Stock'), (inMaintenance, 'In Maintenance'), (damaged, 'Damaged'), ) name = models.CharField(max_length=20, primary_key=True) brand = models.CharField(max_length=20) status = models.CharField(max_length=2, choices=statusChoices, default=inStock) #user = models.ForeignKey(Teacher, on_delete=models.CASCADE, default=0) def __str__(self): return self.name -
Django - trouble publishing Linux server IP
I was working on my machine for Django project, and moved the project files to Linux server to publish the app. Currently I'm not interested in using gunicorn or nginx. I just want to see if I can access the webpage through the published IP address. >> python manage.py runserver 0.0.0.0:8000 System check identified no issues (0 silenced). September 18, 2018 - 05:45:59 Django version 2.0.6, using settings 'sage.settings' Starting ASGI/Channels version 2.1.2 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. 2018-09-18 05:45:59,176 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2018-09-18 05:45:59,179 - INFO - server - Configuring endpoint tcp:port=8000:interface=0.0.0.0 2018-09-18 05:45:59,180 - INFO - server - Listening on TCP address 0.0.0.0:8000 But when I run this, I can't remotely access the webpage through my server's WAN IP address My Linux server's WAN IP address is 70.x.x.x I am using router. Here is my port forwarding settings: Here is my router firewall settings: In settings.py --> ALLOWED_HOSTS = ['', '*'] Somebody told me it might because of firewall issues. He told me to run iptables -F and iptables -X to remove any firewall blockage, so I did. When I run … -
django query not grouping properly
class Category(BaseEntity): """ to categorise the expense """ name = models.CharField( max_length=80, validators=[ RegexValidator( regex='^[a-zA-Z\s]*$', message='name should contain only alphabets', code='invalid_name' ), ] ) description = models.CharField( max_length=250, validators=[ RegexValidator( regex='^[a-zA-Z\s]*$', message='name should contain only alphabets', code='invalid_name' ), ], null = True, blank = True ) parent_category = models.ForeignKey( 'self', related_name = 'child_categories', on_delete = models.CASCADE, null = True, blank = True ) class Expense(BaseEntity): """covers all the expenses""" SEGMENT_CHOICES=( ('RENTALS', 'Rentals'), ('MIXING', 'Mixing'), ('ALBUMS', 'Albums'), ('SALES', 'Sales'), ) amount = models.IntegerField( default=500, validators=[ MinValueValidator( 0, message = 'Amount should be greater than 0' ), MaxValueValidator( 100000, message = 'Amount should be less than 100000' ), ] ) category = models.ForeignKey( 'accounting.Category', related_name='expenses', on_delete=models.CASCADE, null = True, blank = True ) date = models.DateField( verbose_name='spending date' ) description = models.CharField( max_length=250, validators=[ RegexValidator( regex='^[a-zA-Z\s]*$', message='name should contain only alphabets', code='invalid_name' ), ], null = True, blank = True ) event = models.ForeignKey( 'booking.Event', related_name='event_expenses', blank = True, null =True, on_delete=models.CASCADE ) business_segment= models.CharField( max_length =15, choices = SEGMENT_CHOICES, default = 'RENTALS', ) query: expense_category = Expense.objects.values('category__name').annotate(total=Sum('amount')) outputlooks like as follows: even though Diesel has many entries it is not grouped properly. Am I missing anything in the query. I don't … -
seeing error register for model in model_or_iterable: TypeError: 'type' object is not iterable
I have following models in from django.db import models Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] POWER_CHOICES= (('O', 'ON'), ('F','OFF') ) STATE_CHOICES =(('AV','Available'), ('U','In Use '), ('NU','Do Not Use') ) class Device(models.Model): name = models.CharField(unique=True,max_length=50 ) ipaddress=models.ForeignKey('Ipaddress', on_delete=models.CASCADE,) devicetype= models.ForeignKey('DeviceType', on_delete=models.CASCADE) model= models.ForeignKey('DeviceModel', on_delete=models.CASCADE) description= models.TextField(max_length=400) location= models.ForeignKey('Location', on_delete=models.CASCADE) group= models.ForeignKey('DeviceGroup', on_delete=models.CASCADE) managment= models.CharField(max_length=100) power= models.CharField(max_length=6, choices=POWER_CHOICES) offtime= models.CharField(max_length=30) state= models.CharField(max_length=10, choices=STATE_CHOICES) user= models.CharField(max_length=100) # department= models.ForeignKey('Department',on_delete=models.CASCADE) comments= models.CharField(max_length=200) def __unicode__(self): return self.name[:50] class DeviceType(models.Model): name= models.CharField(max_length=100, unique=True) def __unicode__(self): return self.name[:50] class DeviceModel(models.Model): name= models.CharField(max_length=100, unique=True) def __unicode__(self): return self.name[:50] class Ipaddress(models.Model): address=models.CharField(max_length=20, unique=True) owner=models.CharField(max_length=200) loation=models.CharField(max_length=200) note =models.TextField() def __unicode__(self): return self.address[:50] class Department: name= models.CharField(max_length=100, unique=True) def __unicode__(self): return self.name[:50] class DeviceGroup: name= models.CharField(max_length=100, unique=True) def __unicode__(self): return self.name[:50] class Location: description= models.CharField(max_length=100, unique=True) def __unicode__(self): return self.description[:50] My admin page looks like as below: from django.contrib import admin from pages.models import Post, Device, DeviceType, DeviceModel, Ipaddress, DeviceGroup, Location admin.site.register(Post) admin.site.register(Device) admin.site.register(DeviceType) admin.site.register(DeviceModel) admin.site.register(Ipaddress) #admin.site.register(Department) admin.site.register(DeviceGroup) admin.site.register(Location) I am seeing following error and not sure what causing this error. Can someone please give me some idea. please ... ... File "C:\Users\mohiuddin_rana\labmcproject\pages\admin.py", line 10, in <module> admin.site.register(DeviceGroup) File "C:\Users\mohiuddin_rana\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py", line 102, in register … -
KeyError at /skye/ u'\u201c'. This happens When I post a post with so much content on my blog. I am using postgresql database. Help please?
I want to know how to tackle the problem. This my post_detail.html <!--my post_detail.html--> {% extends "base.html" %} {% load urlify %} {% load crispy_forms_tags %} {% block head_title %} {{ instance.title }} | {{ block.super }} {% endblock head_title %} {% block post_detail_link %} <li><a href='{{ instance.get_absolute_url }}'>{{ instance.title }}</a></li> {% endblock %} {% block content %} <div class='col-sm-7 col-sm-offset-1'> <hr/> {% if instance.image %} <img style="height:100%; width:100%" src='{{ instance.image.url }}' class='img-responsive' /> {% endif %} <hr/> <h1><a style="color:black; font: 40px bold Tahoma">{{ title }}</a> <small style="font:5px; color: #777777;">{% if instance.draft %}<span style='color:red;'>Draft</span> {% endif %}{{ instance.publish }}</small></h1> {% if instance.user.get_full_name %} <p>Author: {{ instance.user.get_full_name }}</p> {% endif %} <p><div class="a2a_kit a2a_kit_size_32 a2a_default_style"> <a class="a2a_dd" href="https://www.addtoany.com/share"></a> <a class="a2a_button_facebook"></a> <a class="a2a_button_twitter"></a> <a class="a2a_button_google_plus"></a> </div><br/> <script async src="https://static.addtoany.com/menu/page.js"></script> <div class="fb-like" data-href="{{ request.build_absolute_uri }}" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div> <hr/> </p> <!-- {% if instance.|time:"i" <= "01" %} < 1 minute {% else %}{{ instance.read_time|time:"i" }} minutes {% endif %} --> <!-- <p> <a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"> Facebook </a> <a href="https://twitter.com/home?status={{ instance.content|truncatechars:80|urlify }}%20{{ request.build_absolute_uri }}"> Twitter </a> <a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'> <a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}&title={{ instance.title }}&summary={{ share_string }}&source={{ request.build_absolute_uri }}"> Linkedin </a> <a href="http://www.reddit.com/submit?url={{ request.build_absolute_uri }}&title={{ share_string }}.">Reddit</a> </p> --> <div class='row'> … -
Django is there a benefit of checking every view with `method=='POST':`
Is there a benefit to starting every one of my view functions with if request.method=='POST': or if request.method=='GET':? Or would I just be adding unnecessary lines of code. I've followed a few examples where views for ajax are all checking if the HTTP is get. Could it for example prevent DDOS from latching on to a POST method and hammering it with GETs? Or, more practically, prevent API consumers from incorrectly PATCHing when they should PUT or POST? def employee_delete(request, uid): if request.method == 'DELETE': def employee_detail(request, uid): if request.method == 'GET': def employee_create(request): if request.method == 'POST': def employee_update(request, uid): if request.method == 'PUT': -
Django load template from Google cloud media location
I have create a html file and uploaded that in google cloud media location and i am trying to get that html content using below command from django.template import loader email_template_name = 'http://storage.googleapis.com/media/templates/real.html' template = loader.get_template(email_template_name) Is there any way to get django template object? -
Django- Save Multiple Model Object to DB
I am trying to make an app for parking. What i need is to save multiple instances of the same object in the DB. Basically if the user selects that he wants to park from 2018-09-23 (parking_on) till 2018-09-28 (parking_off), what i need is to save the same model 5 times with all the required details. These are my models: from django.db import models from django.urls import reverse from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings from django.utils import timezone # from datetime import datetime from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time today = datetime.now().date() tomorrow = today + timedelta(1) now = datetime.now() l = now.hour m=int(now.strftime("%H")) class ParcareManager(models.Manager): def active(self, *args, **kwargs): return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now()) class Parcare(models.Model): PARKING_PLOT = ( ('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3')) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, default=1, on_delete=True) email=models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege data cand doresti sa vii in office') parking_off = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii') numar_masina = models.CharField(max_length=8, default="IF77WXV", blank=True, null=True, help_text='Introdu Numarul Masinii') location = models.CharField(max_length=3, blank=True, default="P1", null=True, choices=PARKING_PLOT, help_text='Alege Locul de Parcare Dorit') … -
facebook authentication error. insecure url after using ngrok for https
i am getting error with Facebook login even after using ngrok for https.Now my URL contain HTTPS even though i am getting insecure login blocked. here is my facebook setting. facebook login setting -
Is it possible to make knox and django-rest-auth work together?
Is it possible to make knox and django-rest-auth work together for user authentification management ? And if yes, how? -
Adding a row to an m2m table using DRF
I have the below representation in my models.py class Agent(models.Model): name = models.CharField(max_length=200) user = models.OneToOneField(SampignanUser, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Project(models.Model): client = models.ForeignKey(Client, related_name='projects', on_delete=models.CASCADE) agent = models.ManyToManyField(Agent) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title I want to create a rest endpoint where in i can have an agent apply for a particular project (i.e - create a row in the Project-agents table). Is there a particular way i can do this? Right now , i've tried the below approach urls.py urlpatterns = [ path('projects/<int:project_id>/apply/', views.project_application, name='apply') ] views.py @api_view(['GET','POST']) def project_application(request, project_id): if request.method == 'GET': serializer = ProjectApplicationSerializer() // show an empty form to the user return Response(serializer.data) elif request.method == 'POST': serializer = ProjectApplicationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py class ProjectApplicationSerializer(serializers.ListSerializer): agent = AgentSerializer project = ProjectSerializer It doesnt seem to work however , i get the below error from Django `child` is a required argument. -
Edit and Delete forms DRF Browseable API
Using the Browseable API i can: see the the resources (GET) create new resources (POST) but i'm unable to edit existing resoures or delete them. Already tried override BrowsableAPIRenderer.get_context() and set display_edit_forms = True but changes nothing. Login or not, neither. -
Django request.post without waiting for response
I have a Django server that communicates with a NodeJS server on another address (REMOTE_SOCKET_ADDRESS). In Django, I have a line of code that goes like this: requests.post(settings.REMOTE_SOCKET_ADDRESS, params=query_params) I would like my Django server to not wait for the response from the NodeJS server before proceeding with the code. Just send the POST and go on, so that even if NodeJS needs 10 minutes to do whatever it is doing, it won't affect the Django Server. How can I achieve this "fire and forget" behavior? Additional info: I am on a shared hosting, so I cannot use workers. -
Is it best practise to always have serializer objects correspond to models in Django?
Using the django rest framework, if I have, say, a view to sign a user in that requires the requestor to send the following JSON: { "username": "johnyappleseed", "password": "md783bfaHVfa" } Is it within best practice to have some serializer class along the lines of: class SignInSerializer (serializers.Serializer): username = serializers.CharField( ... ) password = serializers.CharField( ... ) to validate requests made by clients? -
What problems can I solve with django middleware?
I'm a beginner in django middleware. I used to write a visitor system via middleware and still did't get a problem which can be solved with a middleware. Could you describe any typical tasks with django middleware? And tasks where the middleware must have to be