Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
REACT GET requiest getting base url twice
Using REACT front-end with Django back-end. When i call request api i can see it being pulled correctly, however when onClick is called i get a 404 XHRGEThttp://localhost:3000/http//127.0.0.1:8000/undefined so it seems that i am somehow calling the base url twice but i am not sure how? here is my main component file: import React, { Component } from 'react'; import SubtagsList from './list_subtags'; import axios from 'axios'; class TagsList extends Component { constructor(props) { super(props); this.state = { tagData: [], subtags: " ", showComponent: false, } this.getSubtagDetail = this.getSubtagDetail.bind(this); this.showSubtags = this.showSubtags.bind(this); } getSubtagDetail(item){ axios.get("http//127.0.0.1:8000/".concat(item.absolute_url)) .then((response) =>{ this.setState({subtags: response.data}) }) .catch(function(error){ console.log(error); }) } showSubtags(item){ this.getSubtagDetail(item); this.setState({showComponent: true}) } componentDidMount(){ axios.get("http://127.0.0.1:8000/") .then( (response) => { this.setState({tagData: response.data}) }) .catch(function(error) { console.log(error); }) } render() { return ( <div> {this.state.tagData.map((item) => { return ( <h3 key={item.id} onClick={() => this.showSubtags(item)}> {item.tag_name} </h3> ); })} {this.state.showComponent ? ( <SubtagsList subtagDetail={this.state.subtags} /> ) : null} </div> ) } } export default TagsList; here is the api response: [ { "id": 2, "tag_name": "IT/Computer Issues", "type": "Tag" }, { "id": 1, "subtag_name": "Website", "absolute_url": "/1", "type": "SubTag" } ] and this is the SubtagsList component imported: import React, { Component } from 'react'; class SubtagsList … -
Return a tuple in a Django view function
Function with an empty array value def car_info(request): car_brand = {'car_brand': []} return render(request, 'car_info.html', car_brand) Function to append a list of values inside the 'car_brand' key def update_car_info(): updated_car_brand = car_info()[1] # expected result => {'car_brand': []} updated_car_brand['car_brand'].append('Ford') # expected result => {'car_brand': ['Ford']} return JsonResponse({'updated_car_brand': updated_car_brand}) Initially, I wanted to return a tuple def car_info(request): car_brand = {'car_brand': []} return render(request, 'car_info.html', car_brand), car_brand And, access the index, as shown in the update_car_info() function My attempted solution was unsuccessful which was predicted, and now I am struggling to think of new alternative solutions on how to properly manipulate the HTTP Response. How can I access the ['car_brand'] key in my context argument to update the array in another function? -
Default Renderers Not Being Set
I am experiencing a weird issue where the DEFAULT_RENDERER_CLASSES is not being set on any APIView instances. If I inspect the Django settings inside of the get_queryset method, I see the self.renderer_classes set to something other than what appears in settings.REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES']. I have verified that the REST_FRAMEWORK dictionary is only declared once, and that DEFAULT_RENDERER_CLASSES is only set once. I am unsure of what would cause this behavior, and wondering if anybody has ever seen it before. Here's how I am testing this: class ShareNewsAPIView(APIView): def get(self, request, client_object_key): print(self.renderer_classes) print(settings.REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES']) And the output that I see: [<class 'rest_framework.renderers.JSONRenderer'>] ('ccs.core.renderers.JSONRenderer',) I do not have rest_framework.renderers.JSONRenderer defined in settings.REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] at all, so I am confused about how this setting is apparently getting reverted. I have tried copying the JSONRenderer verbatim from the DRF source code, as well as tried creating my own based on the DRF documentation for this. If I explicitly define my custom renderer on renderer_classes it works fine with no issues. Something tells me this has to do with content negotiation but I am unsure why explicitly defining renderer_classes would fix this. The default JSONRenderer works fine, which I feel contradicts my content negotiation theory, however. I am … -
getting an error while installing python packages using vagrant
I'm trying to install packages using pip in a virtual machine which I'm connecting with using vagrant(this error is for installing django but I get this for installing every package). But I get this error: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run wb.build(autobuilding=True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/usr/lib/python3/dist-packages/pip/download.py", line 821, in unpack_url hashes=hashes File "/usr/lib/python3/dist-packages/pip/download.py", line 659, in unpack_http_url hashes) File "/usr/lib/python3/dist-packages/pip/download.py", line 902, in _download_http_url _download_url(resp, link, content_file, hashes) File "/usr/lib/python3/dist-packages/pip/download.py", line 603, in _download_url hashes.check_against_chunks(downloaded_chunks) File "/usr/lib/python3/dist-packages/pip/utils/hashes.py", line 46, in check_against_chunks for chunk in chunks: File "/usr/lib/python3/dist-packages/pip/download.py", line 571, in written_chunks for chunk in chunks: File "/usr/lib/python3/dist-packages/pip/utils/ui.py", line 139, in iter for x in it: File "/usr/lib/python3/dist-packages/pip/download.py", line 560, in resp_read decode_content=False): File "/usr/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl/urllib3/response.py", line 436, in stream data = self.read(amt=amt, decode_content=decode_content) File "/usr/share/python-wheels/urllib3-1.22-py2.py3-none-any.whl/urllib3/response.py", line 384, in read data = self._fp.read(amt) File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/filewrapper.py", line 60, in read data = self.__fp.read(amt) File "/usr/lib/python3.6/http/client.py", line 463, in read n = self.readinto(b) File "/usr/lib/python3.6/http/client.py", line 507, in readinto n = self.fp.readinto(b) File "/usr/lib/python3.6/socket.py", line 586, in readinto return … -
Order queryset by JSON field of latest FK
I have such models: class Configuration(models.Model): @property def latest_value_A(self): return self.result_set.latest("created_time").data.get("value_A") class Result(models.Model): data = models.JSONField() # "value_A" key is present in JSON configuration = models.ForeignKey(Configuration, on_delete=models.CASCADE) created_time = models.DateTimeField() I want to do something like Configuration.objects.order_by("latest_value_A") which obviously fails cause it's just a property and not stored in DB. But what would be the proper way of doing it? -
Django Left join how
I fairly new to Django and stuck with creating a left join in Django. I tried so many, but none of them seems to be working: The query I want to transalte to Django is: select ssc.id ,mgz.Title ,tli.id ,tli.Time from Subscription ssc join Person prs on ssc.PersonID = prs.id and prs.id = 3 join Magazine mgz on mgz.id = ssc.MagazineID left join TimeLogedIn tli on tli.SubscriptionID = ssc.id and tli.DateOnline = date.today() The model I'm using looks like this: class Magazine(models.Model): Title = models.CharField(max_length=100L) from = models.Datefield() until = models.Datefield() Persons = models.ManyToManyField(Person, through='Subscription') class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Magazines = models.ManyToManyField(Magazine, through='Subscription') class Subscription(models.Model): MagazineID = models.ForeignKey(Magazine,on_delete=models.CASCADE) PersonID = models.ForeignKey(Person,on_delete=models.CASCADE) class TimeLogedIn(models.Model): SubscriptionID = models.ForeignKey('Subscription', on_delete=models.CASCADE) DateOnline = models.DateField() Time = models.DecimalField(max_digits=5, decimal_places=2) Like I said, tried so many but no succes and now I don't know how to do this in Django ORM , is it even possible? I created already a raw-query and this is working ok, but how to create this in Django ORM? -
psycopg2.IntegrityError (Key exists already) on form_valid
So, I have this CBV class SignupView(generic.CreateView): template_name = 'registration/signup.html' model = User form_class = CustomUserCreationForm success_url = reverse_lazy('welcome') def form_valid(self, form): self.object = form.save() #raises IntegrityError now user = self.object send_verification_email(user, self.request) # TODO messages.info(request, "Thanks for registering. You are now logged in.") user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(self.request, user) return HttpResponseRedirect(self.get_success_url()) Throws IntegrityError (key (username)=(test) already exists) on usernames that did not exist already (if the user existed before, the form does not submit) It saves that user - but it seems like it tries to save it another time - which then fails. -
how to fix SMTPAuthenticationError issue?
This question is existing a lot on the internet however I couldn't fix my problem in the end. I used all the ways that handle this problem also, later I used python-dotenv whether I used it or not the problem still raises for me. also, I turned the less secure app off on google but nothing new happens. I have many questions about this problem: 1- which password I have to place in (export EMAIL_HOST_PASSWORD)? I used any password then when I see the error occur every time, I did change it to be the real password of my Gmail account. 2- I need to send a mail when I upload my site in production hence when I use localhost I should use google less insecure as I understand because localhost is dealing with HTTP, not HTTPS so how can I send mail in production case? 3- How can I solve this problem in first place? views.py def register(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form.save() email_subject = 'Activate your account' email_body = 'Test body' email_message = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email] ) email_message.send(fail_silently=False) messages.success(request, 'Account successful created, please verify … -
xhtml2pdf works great with an Image located at project's root on windows but it breaks when deployed to Ubuntu
I have a very strange problem and tried everything for about 5 hours to solve this odd issue but no luck. I was able to generate a PDF file with images successfully using xhtml2pdf on my machine which is running windows 10, but when I deployed to Ubuntu my img just got broken for no reason! I think the problem is that, on Ubuntu it doesn't build the path to this img correctly, but, ironically, it does on windows perfectly! here is the section which is working just fine on windows but not on Ubuntu: <table> <tr> <td> <img src="test_logo.png" alt="logo"></td> </tr> </table> And test_logo.png is located at the root of my project just like this: my_project/ app1/ app2/ requirements.txt test_logo.png And my link_callback() def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s … -
How I can run a telegram bot with the Django project?
Now, to run the bot through Django, I first use the python manage.py runserver command and then follow the link to launch a view with my bot. Can you tell me if there is an easier way to start my bot automatically when starting a Django project? -
Passing string list to javascript function Django
Im building my first Django app. I want to call a javascript function that receives a list of strings. In my current version Im sending a Django object (called provider) property like this and it´s working fine: <a href="#" class="button secondary tiny" onclick="download_provider_files('{{ provider.full_name }}')"><i class="fi-download"></i></a> But now I want to call a Provider model method that returns a list of strings, so then I can do something with this list in Js method def get_provider_files_urls(self): provider_files = self.provider_files.all() file_list = [] for f in provider_files: file_list.append(f.file.name) return file_list I tried this: <a href="#" class="button secondary tiny" onclick="download_provider_files('{{ provider.get_provider_files_urls }}')"><i class="fi-download"></i></a> and got this error: Uncaught SyntaxError: missing ) after argument list -
Is it possible to do an 'if' statement to change the navbar just for my allauth templates?
Right now my navbar has an 'if' statement for being authenticated vs not authenticated. My allauth templates are extending from my base and showing these navbars. Is it possible to add in another 'if' statement for when a user is on an allauth form? Right now my navbar looks something like this... <nav class="navbar navbar-expand-lg ml-2 mr-1"> {% if request.user.is_authenticated %} <a class="navbar-brand d-inline-block align-top rounded-circle ml-1 mr-0" href="{% url 'home' %}"> blah blah blah {% if request.user.is_superuser %} <li><a class="nav-item nav-link orange" href="{% url 'management' %}">Site Management</a></li> blah blah blah {% endif %} {% else %} <a class="navbar-brand d-inline-block align-top rounded-circle ml-2 mr-0" href="{% url 'home' %}"> blah blah blah {% endif %} -
Django Class should either include a `queryset` attribute, or override the `get_queryset()` method, but one already exists
Getting the following error when trying to update a model. AssertionError: 'SaveMotor' should either include a `queryset` attribute, or override the `get_queryset()` method. Here's my view for the class. class SaveMotor(generics.UpdateAPIView): def post(self, request, format=None): serializer = MotorSerializer(data=request.data) if serializer.is_valid(): updatedMotor = serializer.data.get('motor') queryset = Motor.objects.filter(number = updatedMotor.number, machine = updatedMotor.machine) if queryset[0].exists(): newMotor = queryset[0] newMotor = updatedMotor newMotor.update() else: return Response({'msg': 'Motor save failed: Motor not found'}, status=status.HTTP_404_NOT_FOUND) else: print(serializer.errors) return Response({'msg': 'Motor save failed: Data not valid'}, status=status.HTTP_404_NOT_FOUND) As you can see, I'm already using a queryset (which has worked fine in other classes), so I'm puzzled as to why it's telling me I'm not. Any help is appreciated. -
Validating polymorphic data in JSONField using json-schemas
Hello Stackoverflowers! I've searched for a solution for this for a while, but have not been able to find anything addressing this usecase specifically. Say we have the following models: class Machine(models.model): machine_name = models.CharField(max_length=30) machine_data_template = models.JSONField() class Event(models.model): machine_name = models.ForeignKey(Machine, on_delete=models.CASCADE machine_data = models.JSONField() We have a machine for which there can be multiple events, the details of which are stored as JSON in a JSONField. The JSONField in event should be validated using the json-schema defined in Machine.machine_data_template. I've looked at various Python/Django implementations of json-schemas, however I have not been able to find a way where we can define custom validation on a per-object basis. For example, solutions such as the one presented by Corwin Cole here defines the validation logic directly in the model, which would mean each instance of event would be subject to the same validation logic regardless of the machine: MY_JSON_FIELD_SCHEMA = { 'schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': { 'my_key': { 'type': 'string' } }, 'required': ['my_key'] } class MyModel(models.Model): my_json_field = JSONField( default=dict, validators=[JSONSchemaValidator(limit_value=MY_JSON_FIELD_SCHEMA)] ) Does anyone have any suggestion how I can achieve the desired "fully polymorphic" behavior? BR - K -
Django error when python manage.py migrate
So I am currently in a virtual environment, and when I typed the command line: python manage.py migrate i get this error : Traceback (most recent call last): File "/home/allielbadry/Desktop/learning_logs/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/contrib/admin/__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/contrib/admin/filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/contrib/admin/options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "/home/allielbadry/Desktop/learning_logs/myvenv/lib/python3.9/site-packages/django/contrib/admin/widgets.py", line 151 '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized i tried diff version of django and i still get the same problem -
django form with image input
I am trying to make a form to edit an profile picture in django, but is not working because the if form.is_valid() is always false and I don´t know why. The only thing I want to know is how to it properly. My Html is: <form class="form-group row" enctype="multipart/form-data" action="" method="POST"> {% csrf_token %} <input type="file" name="profile_avatar" accept="image/*"> <button type="submit" name="avatarProfile" class="btn btn-brand btn-bold kt-btn-profile">Actualizar foto</button> </form> My forms.py is: class Perfil(forms.Form): picture = forms.ImageField() and my view.py is: def post(self, request, *args, **kwargs): try: if request.method=='POST': form = Perfil(request.POST) if form.is_valid(): picture = form.cleaned_data.get("profile_avatar") user_id = self.request.session.get('user_id') User.objects.filter(user_id = user_id).update(picture_uri = picture) return redirect('core:home') else: return redirect('core:home') else: return redirect('core:home') except: return redirect('core:home') -
Bad Gateway (502) on nginx > uwsgi > django, but only one SOME devices
My site looks fine on my Mac and my Windows laptop (using chrome to access homepage https://inspidered.org), but if I try any other devices, I get a 502 gateway error from nginx. Nginx is the front end server running as a reverse proxy on digital ocean droplet, with uwsgi behind it running django 3.1. Here are my relevant config files: My debugging tips come from this page: https://digitalocean.com/community/questions/502-bad-gateway-nginx-2 sudo tail -30 /var/log/nginx/error.log ... 2021/03/01 17:45:47 [crit] 16656#0: *3420 connect() to unix:/run/uwsgi/inspidered.lock failed (2: No such file or directory) while connecting to upstream, client: 23.100.xxx.yyy, server: inspidered.org, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/inspidered.lock:", host: "inspidered.org" nginx has no obvious errors: sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Also, nginx serves two other servers on the droplet (a python2 cherrypy and a python3 cherrypy) without any problems. Only this uwsgi/django site is affected. And only some devices. [~]# systemctl status nginx ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled) Active: active (running) since Mon 2021-03-01 05:05:21 UTC; 13h ago Process: 16653 ExecReload=/bin/kill -s HUP $MAINPID (code=exited, status=0/SUCCESS) Process: 16399 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) … -
How do I isolate the root path to turn on and off its 'active class' on the navbar?
I am hoping to better understand the urlpatterns in Django as well as figuring out this puzzle: To turn the current page's link on the navbar to be active (ie, highlighted, as in class="nav-item active", I use {% if 'somelink' in request.path %}, which mostly works. But {% if '/' in request.path %} doesn't work for the homepage. The "Home" link remains highlighted whether or not one is on the page. Is it because all paths must go through path('/' ...)? How does one isolate the root url then? urlpatterns = [ path('', views.index, name='index'), ... ] -
any standard way to add request to log record for AdminEmailHandler?
Django's AdminEmailHandler will send an email to admins everytime there is an exception or a logger.error and it's prepared to include request information in the email if the log record contains a request attribute. But this attribute is not set by default. I have found a way of doing this: I add the threadlocals.middleware.ThreadLocalMiddleware that will associate the request with the local thread I create a logging filter that will do record.request = get_current_request() Add this filter to the logging handler that uses AdminEmailHandler. but I'm wondering that if AdminEmailHandler is already prepared for record.request, there surely must be an already made way to do this in django. -
ModelForm has no model class specified error django framework
I'm receiving the error "ValueError at /accounts/create/ ModelForm has no model class specified." Views.py: from django.shortcuts import render from .forms import CustomUserCreationForm from .models import CustomUser from django.contrib.auth.models import Group def signupView(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') signup_user = CustomUser.objects.get(username=username) customer_group = Group.objects.get(name='Customer') customer_group.user_set.add(signup_user) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form':form}) I can't find any the error for the life of me, any help would be appreciated. Thanks. -
Can't represent all fields of a serialized ManyToMany through model with Django Rest Framework
I'm using Django and Django Rest Framework to represent a 'BaseRecipe' model. This model has a M2M field to represent the ingredients of that recipe. That M2M field relates a 'Product' object with the 'BaseRecipe' object and extends that two models with another field to represent the 'quantity'. I'm trying to retrieve a list of those ingredients in the BaseRecipeSerializer, but only the id's are returned. Any ideas why? Thank you in advance! My models.py: class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) supplier = models.ForeignKey(Supplier, blank=True, related_name='supplier_products', on_delete=models.CASCADE) serial_no = models.CharField(_('Serial number'), max_length=50, blank=True, help_text=_('Product serial number. Max 50 characters.')) allergens = models.ManyToManyField(Allergen, blank=True, related_name='product_allergens') description = models.TextField(_('Description'), blank=True, help_text=_('Additional product information.')) is_vegan = models.BooleanField(_('Vegan'), default=False) is_halal = models.BooleanField(_('Halal'), default=False) format_container = models.CharField(_('Format container'), max_length=6, choices=CONTAINERS, blank=True, help_text=_('Package format')) format_quantity = models.DecimalField(_('Format quantity'), blank=True, null=True, max_digits=9, decimal_places=3, help_text=_('Format quantity sell')) format_unit = models.CharField(_('Format unit'), max_length=6, choices=UNITS, blank=True) quantity = models.DecimalField(_('Quantity'), blank=True, null=True, max_digits=9, decimal_places=3, help_text=_('Quantity per unit provided')) type = models.CharField(_('Type'), max_length=255, help_text=_('Type'), blank=True) unit = models.CharField(_('Unit'), max_length=6, choices=UNITS) unit_price = models.DecimalField(_('Unit price'), blank=True, null=True, max_digits=9, decimal_places=3) class Meta: ordering = ['name', ] @property def price(self) -> Decimal: return self.quantity * self.unit_price def __str__(self): return self.name class BaseRecipe(models.Model): user … -
Axios POST call doesn't work with JWT token, while GET call works
I'm trying to build REST API in Django which I connect with Vue.js on the front end by using the axios library with using the JWT token authentication. However when I make POST Django says Unauthorized, while when I use GET everything seems to work correctly. Both POST and GET are defined as part of the same class and I use permission_classes = (IsAuthenticated,) to check for permissions. -
Authenticate function is redirecting to login success url - Django
I hope you are everyone is doing well. I'm new to Django and tried to overwrite some Login methods in order to redirect my users when they log-in, and I have other view function where I authenticate my users in order to redirect to a settings view. The problem is that somehow my authenticate view is getting my Log-in view success url and error url, when I send wrong data into my verificationView I get redirected to my log-in view. This is my verification view using authenticate in order to redirect def verificationView(request): if request.user.is_authenticated: form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'] username = form.cleaned_data['username'] user = authenticate(password = password, username = username) if user != None: return redirect('settings-view') else: return render(request, 'authenticate.html', {'form': form}) else: return render(request, 'authenticate.html', {'form': form}) else: return redirect('login-view') This is my Log-in view where I my users log-in in order to reach other views class MyLoginView(LoginView): template_name = 'login.html' def get_success_url(self): url = self.get_redirect_url() return url or reverse('home-view') def get_login_url(self): return reverse('login-view') def get_redirect_url(self): return reverse('home-view') Urls.py urlpatterns = [ path('register', register, name="register-view"), path('login', MyLoginView.as_view(), name = "login-view"), path('logout', LogoutView.as_view(), name="logout-view"), path('verification', verificationView, name="verification-view"), path('settings', SettingsView.as_view(), … -
Nested forms in django with tree like display
I was wondering if you could help me with a django design issue that I have. To simplify, let us consider the below model: class MyModel(models.Model): _CHOICES = ( ('A', 'OptionA'), ('B', 'OptionB'), ('C', 'OptionC'), ('D', 'OptionD') ) options = models.CharField(max_length=1, choices=_CHOICES, default='A') So essentialy, my form will render as: Options: [ ] OptionA [ ] OptionB [ ] OptionC [ ] OptionD When the user, will click on any of the boxes above, I want to display just below: [ ] Top [ ] Middle [ ] Bottom And for each that is clicked, just below: [ ] Right [ ] Left I found the following which gives idea for the javascript behaviour: Nested Checkbox : Checked / Unchecked children with parent check My problem is that I don't really now how to tackle the django part. Should I create formsets with something like: class ModelTopBottom(models.Model): _CHOICES = ( ('T', 'Top'), ('M', 'Middle'), ('B', 'Bottom') ) option = models.CharField(max_length=10) top_bottom = models.CharField(max_length=1, choices=_CHOICES) is_right = models.BooleanField(default=False) is_left = models.BooleanField(default=False) I no, what solution could you think of? If yes, how can I handle the display? How can I link the object/formset to its checked option on the form so … -
Using zoomus wrapper to generate zoom meeting link
I'm trying to integrate zoom api into my django website (it's a school project) I've been using prschmid/zoomus. This is the code I have right now import json from zoomus import ZoomClient client = ZoomClient('1bFDBicDQxmSAZbECE5', '4HBPY8c190hY7DF1xf9S665iTy3GGlgJdw',version =2) user_list_response = client.user.list() user_list = json.loads(user_list_response.content) print(json.loads(user_list_response.content)) for user in user_list['users']: user_id = user['id'] print(json.loads(client.meeting.list(user_id=user_id).content)) client.meeting.get() and this is the part of the response I get meetings': {start_time': '2021-03-01T17:22:23Z', 'duration': 60, 'timezone': 'America/New_York', 'created_at': '2021-03-01T17:22:22Z', 'join_url': 'https://us02web.zoom.us/j/81091486096?pwd=QnVmWWZzenU4bEpCbFE3aDNjL2xBUT09'} My question is, how do I take that generated meeting link and put it in the variable so that then I can use it in this method to send an email message = "Your appointment has been approved by the provider, use this link to enter the meeting: (here should be a zoom meeting link) " send_mail( subject, message, email_info.EMAIL_HOST_USER, [apt.patient.user.email], fail_silently=False, )