Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python how to skip line in list display
i want the skip line between elements in list this is my out put : and this is my code : output = net_connect.send_command(request.POST.get("cmds"), use_textfsm=True) outputs.append(request.POST.get("cmds")) outputs.append("\n") outputs.append(output) outputs.append("\n") print(outputs) cmds is for the cli input -
Can I have my app as a web application and a chat application?
I have a blog as web application. Can I include a chat asgi.app integrated with my blog? I am following this tutorial- https://github.com/Bearle/django_private_chat2 This app works like a chat application but doesnt work when included with my blog. Is it possible? -
Visualize XML File in Django on Frontend
I have this xml file template: <?xml version="1.0" encoding="UTF-8"?> <adtree> {% for order in orderList %} <order id="{{ order.id }}"> <models> {% for model in order.models.all %} <model id="{{ model.id }}"> <name>{{model.name}}</name> {% for color in model.colors.all %} <color name="'{{color.name}}'"> {% for size in color.sizes.all %} <sizeAmount name="'{{size.name}}'">{{size.amount}}</sizeAmount> {% endfor%} </color> {% endfor%} </model> {% endfor %} </models> </order> {% endfor %} </adtree> I want to show this exactly as it is(in the xml format) in my .html file, but it doesnt work. I have tried to put it in a block, but it only shows the "variables". I want it in this format because the user should be able to download the generated xml file. Tips on how the file can be saved is also appreciated! Thank you so much for your help! -
Django Extra-Views form Validation Errors not showing
Django noob here I´m using Django Extra-Views to create a custom form with two inline-forms. All working properly. I wrote some custom validators for the file-upload formset for filesize and -type restrictions which work perfectly when used in the admin backend. However, the error messages do not show up in the form template. They do work obviously as the site reloads instead of showing the success-url when wrong filesizes or types are uploaded but with any errormessage. Then I thought maye it has to do with the formset and the iteration, so I wrote another validator for another single field without for-loop in the form (contat_tel) which works perfectly and also error messages are shown. I tried the template tags provided in the Django docs, I tried the template tags for formsets, I inspected the rendered HTML to see if Bootstrap is playing tricks on me, but nothing gets rendered. Heres the code: models.py class TipImage(models.Model): title = models.CharField( max_length=264, verbose_name="Titel", blank=True, null=True ) image = models.ImageField( upload_to="freizeittipp_img/", default="no_image.png", verbose_name="Freizeittipp-Bild", blank=True, null=True, validators=[validate_file_size, validate_file_type], ) tipp = models.ForeignKey( Leisuretip, on_delete=models.CASCADE, related_name="images" ) views.py class TipImageInline(InlineFormSetFactory): model = TipImage fields = ["title", "image"] class LeisuretipAddView(CreateWithInlinesView, NamedFormsetsMixin): template_name = "leisuretips/leisuretip_form.html" model = … -
wagtailuserbar giving error on nginx production server
My app works fine on localhost. But it gives 500- server error if logged in as admin on production mode/DEBUG=False. Below is the stack trace of the errors generated when logged in as admin. Apparently {% wagtailuserbar %} tag in base.html giving the error. The page loads fine without logged in. Ubuntu 20.04 Django 3.1.6 Wagtail 2.12.4 Postgres 13 & Gunicorn Traceback (most recent call last): File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/classytags/core.py", line 151, in render return self.render_tag(context, **kwargs) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/sekizai/templatetags/sekizai_tags.py", line 87, in render_tag rendered_contents = nodelist.render(context) File "/var/www/xeroticinc.codes/xenv/lib/python3.8/site-packages/django/template/base.py", line 938, in render … -
Passing a pdf from Django backend to Angular frontend
I haven't been able to make any of the solutions to similar problems work for my case. I would like to load a pdf from filesystem with django and return it via an API call to Angular so that it can be displayed. My Django code is pretty much: class LoadPdfViewSet(views.APIView): def get(self, request): # some code here here response = FileResponse(open(path_to_pdf, 'rb').read()) response.headers = { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment;filename="report.pdf"', } response.as_attachment = True return response while on the Angular side I have a service that does this: export class LoadPdfService { constructor( private http: HttpClient ) {} getPdf(): Observable<Blob> { const params = new HttpParams({ fromObject: { responsetype: 'arraybuffer' // other stuff here } }) return self.http.get<Blob>(myurl, {params}).pipe(catchError(self.myErrorHandler)) } } and a component that tries to open the pdf like this: export class MyComponent { constructor( public loadPdfService: LoadPdfService ) {} def download_pdf() { let call = self.loadPdfService.getPdf(); call.subscribe( (response:Blob) => { if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE window.navigator.msSaveOrOpenBlob(blob, "report.pdf"); } else { let pdfUrl = URL.createObjectURL(blob) window.open(pdfUrl, '_blank') URL.revokeObjectURL(pdfUrl); } } } } but nothing happens. I have also tried using different responses and passthrough renderers on the django side, and Observable and "then" callbacks like … -
Run python through frontend request using Django and Docker
I am currently trying to develop a website to run a big python file using some information given as input trough the website. I got someone to help and was advised to do it using django and docker. I got the frontend running, but I cant do it with the backend and can't connect both. Any help? -
django image gallery showing no images
how-to-build-a-photo-gallery-with-django-part-1 how-to-build-a-photo-gallery-with-django-part-2 This is an excellent tutorial for learning how to make an image gallery in django. As it suggests, I have recreated page step by step here link: image gallery I am adding images to sql table yet the path it's referring to is /photo_gallery/pet/01/media/image/kitty/gallery/..... The image page is blank because it does not find image in the path. I don't know where it is stored. Error log : Not Found: /photo_gallery/pet/01/media/image/kitty/gallery/kitty10.jpeg Not Found: /photo_gallery/pet/01/media/image/kitty/gallery/kitty11.jpeg Not Found: /photo_gallery/pet/01/media/image/kitty/gallery/kitty14.jpeg this path is not being set anywhere then could it be django's way of storing it. How does one ensure the page shows all images for a given pet ( in this context ) . -
issue while adding user in django admin
whenever I try to create a new user in the admin page i get an error. Can anyone help me fix this? this is my code class ChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's disabled password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('first_name', 'last_name', 'password', 'height', 'weight', 'age', 'location') class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form = ChangeForm model = User # password = ReadOnlyPasswordHashField() list_display = ['pk','username', 'first_name', 'last_name', 'location', 'height', 'weight', 'age', 'user_picture'] add_fieldsets = ( (None, {'fields': ('username','first_name', 'last_name', 'password', 'location', 'height', 'weight', 'age', 'user_picture')}), ) fieldsets = add_fieldsets admin.site.register(User, CustomUserAdmin) -
Django queryset matching null value with null OuterRef
In Django, I'm trying to filter Foo objects by whether a Bar object exists with the same values. The code I have below works fine for non-null values. But I also want it to return true if Foo.baz and Bar.baz are both null. Foo.objects.filter(Exists(Bar.objects.filter(baz=OuterRef('baz'), qux=OuterRef('qux')) I know NULL is not equal to NULL in SQL so have tried various formulations like this: baz__isnull=... But I'm not getting very far. Is there a way to achieve this? -
Is it wrong to use modules like wget to let users download files on django?
I am working on a django application in which users can download their own files. I need to make the files secure and only let them download it. At first, I was thinking of using something like {%if files%} <a href='/media/files/pics/photo.png' download> Then i realised that anyone can brute force my site and get any files. So I thought of handling the download through views. I am very beginner and don't know how to make my own download view. So I used something like: at views.py def download(id): file = data.objects.get(pk=id) url = file.fileurl filename = wget.download(url) and call the function when the user want to download the file. I am using wget module. I think I am doing wrong, So I decided to ask for some suggestions. At last my question is : Is it wrong to use other modules to download files? Or how to write a download view on Django? Thank you!! -
How to get values of iterating input fields?
I created a form. I have to create as many inputs as the number of customers. Because of that, I am using for loop. I couldn't find an iterating name for the name field in the input. And when I use a constant name I just can get the last value of iteration in views. I want to give the customer id to the input name, this way my problem can be solved. Or can I get the value entered using input id in views? (Because I can give iterated names to id.) template.html <form method="POST" enctype="multipart/form-data"> <!-- Very Important csrf Token --> {% csrf_token %} {% for customer in parent_customers %} <label style="font-weight: bold">{{ customer }}</label> <div class="form-group "> <div class="input-group"> <input type="number" class="form-control input-border-bottom" aria-label="Text input with dropdown button" placeholder="Credit Limit" name='{{ customer.id }}'> //Editor gives an error for that so it is useless. <div class="input-group-append"> <select class="select-currency btn btn-primary btn-border dropdown-toggle" id="currency-select{{ customer.id }}"> <option>USD</option> <option>EUR</option> ... </select> </div> </div> </div> {% endfor %} {{ form_parent.media }} {{ form_parent|crispy }} <input type="hidden" name="form" value="risk-parent" /> <input type="submit" class="btn btn-primary btn-lg" value="Approve"> views.py def approval_page(request, id): ... parent_customers = Customer.objects.filter(parent=pdf.parent_company, company=request.user.company): if request.method == 'POST' and request.POST.get('form') == … -
How do I submit the details from a modal window to database in Django?
I have made an app in django displaying a form. On filling the fields in the form and hitting the save button, a modal window opens displaying the filled data and asking the user to confirm whether his details are correct. If the user clicks submit, I need to push the data to the database. Here is my code. I'm quite new to Django and have been stuck at this issue for days now. Please help. views.py from django.shortcuts import render from .forms import LoginForm from .models import Post def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): if request.POST.get("submit"): post=Post() name = request.POST.get('name', '') gender = request.POST.get('gender', '') dateofbirth = request.POST.get('dateofbirth', '') city = request.POST.get('city', '') state = request.POST.get('state', '') country = request.POST.get('country', '') return render(request, 'account/login.html', {'form': form,'successful_submit': True,'name':name,'gender':gender,'dateofbirth':dateofbirth,'city':city,'state':state,'country':country}) elif request.POST.get("cancel"): form=LoginForm() return render(request, 'account/login.html', {'form': form}) else: form=LoginForm() return render(request, 'account/login.html', {'form': form}) models.py from django.db import models class Post(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=10) date_of_birth = models.DateField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) def __str__(self): return self.name forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): #publication_date = forms.DateTimeInput() class Meta: model = Post fields = ('name', 'gender', … -
JWT authentication customisation with phone_number and password instead of username and password
I have implemented JWT authentication and authorization in my project using the link https://django-rest-framework-simplejwt.readthedocs.io/en/latest/index.html The code is working fine, but I need to change 'username' and 'password' to 'mobile_number' and 'otp'. I have a custom user model like class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, blank=True, null=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_resource = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) skills = models.ManyToManyField(Skills) class Meta: db_table = "my_user" def __str__(self): return self.mobile_number For the login purpose, I am planning to have an otp model like class LoginOtp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otp = models.IntegerField() created_on = models.DateTimeField(default=datetime.utcnow()) class Meta: db_table = "otp" I don't know if the above method is the right way to proceed with. If not please correct me. How can I replace 'username' and 'password' with 'mobile_number' and 'otp'. Thank you. -
i m using url slug for my pages, but i have to manually type the slug , it doesnot appear when i click on the button
I am trying to generate different pages but when i click only actual page occurs, but not the one with the values loaded. but when i manually add the uid in the url , the page appears. Here is my view,these two are relatable, def link_view(request, uid): results = AffProduct.objects.get(uid=uid) return render(request, 'link.html', {"results":results}) def link(request): return render(request, 'link.html') Here is my url patterns, path('link/', views.link, name='link'), path('link/<int:uid>', views.link_view, name='link_view'), Here is my Html part, #What i want to achieve is when i click on 'Get Link', it should redirect to path('link/<int:uid>', views.link_view, name='link_view'), but it redirects with no slug data. <span> <a class="Update" href="{% url 'link' %}">Get Link</a> </span> -
Django Authentication Hardcoding Users
I have a django project with two apps (app and authenticate) that I got from a template. I developped my "app" app and it works fine. Now I want to add logins to limit access to certain pages of the app. I looked accross the Internet and they use user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword') to create a user. I tried that (and tried logging in with the username and password but it doesn't work. I probably put the code in a wrong area (I put it in authentication/models.py). I would really like this to work but I can't seem to figure out why the user isn't created. -
How to get the ChoiceField value using javascript
First of all sorry for my bad english i am french ! So i have a little problem. I use the django built-in class ChoiceField in my form : class LogForm(forms.Form): FormData = (('1', 'Code',), ('2', 'Normal',), ('3', 'Hexa',)) choixFormData = forms.ChoiceField(label=' Forme des donnees ', choices=FormData) liaison = (('1', 'RS232_1_Port1',), ('2', 'RS232_1_Port2',), ('3', 'RS232_1_Port3',), ('4', 'RS232_1_Port4',), ('5', 'RS422_1_Port1',), ('6', 'RS422_1_Port2',), ('7', 'RS422_1_Port3',), ('8', 'RS422_1_Port4',), ('9', 'RS422_2_Port1',), ('10', 'RS422_2_Port2',), ('11', 'RS422_2_Port3',), ('12', 'RS422_2_Port4',), ('13', 'VoieNumAna',), ('14', 'CAN1',), ('15', '1553',)) choixLiaison = forms.ChoiceField(label='Liaison', choices=liaison) Data = forms.CharField(required=False, label=' Data ', max_length=100, widget=forms.Textarea) And i also use the Django Channels in order to implement websockets in my app. The thing is, i want to be able to render the form thanks to the view ( this is working fine ) and then i want to get the value of the selected choice ( once the the form is rendered ) using javascript. I tried this : document.querySelector('#id_Start').onclick = function(e) { const messageInputDom = document.querySelector('#id_choixLiaison'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; } I am very new to javascript and i dont understand the reason why this is not working. I want to be able to get the value … -
function() takes 1 positional argument but 2 were given
I'm trying to clone this Django repo and run it on my local machine, but I've run into the classic function() takes 1 positional argument but 2 were given error. After cloning the repo I created a virtual environment and installed all the dependencies, But when I run py manage.py migrate I get the above-mentioned error. What's confusing me is that the error is occurring in a python file automatically generated in the virtual environment and according to other questions on SO about this, the code seems correct. Here's the trace Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django_prometheus\apps.py", line 22, in ready ExportMigrations() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django_prometheus\migrations.py", line 39, in ExportMigrations executor = MigrationExecutor(connections[alias]) File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\lenovo\Desktop\dev\work\django-sspanel\sspanel_env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File … -
Django - Unable to import other classes from project
I don't know what the problem is but every time when try to import a model class from models.py in another script I get back: ModuleNotFoundError: No module named 'Strics' So it seems that Its not possible to resolve the given package Strics, but why? INSTALLED_APPS is fine, init.py is also there, venv is loaded ?!?: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Strics.apps.StricsConfig', ] My Project structure: . ├── db.sqlite3 ├── manage.py ├── requirements.txt ├── Strics │ ├── admin.py │ ├── apps.py │ ├── asgi.py │ ├── bin │ ├── __init__.py │ ├── meta_scrape.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── settings.py │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── venv ├── bin ├── include ├── lib ├── lib64 -> lib └── pyvenv.cfg My import statement: from Strics.models import Media, MediaStreams Can somebody give me a hint why I'm, not able to resolve my own App?! -
Django - Comments
I am new to Django and I'm having problems with comment forms. I just want to add a text field for comment on a specific Post's page, but it is hidden. Here is my models.py file in blog app: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return '{} - {}'.format(self.author, self.date_posted) forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) views.py file: from django.db import models from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.models import User from django.shortcuts import redirect, render from django.shortcuts import get_object_or_404 from django.views.generic import ListView from django.views.generic import DetailView from django.views.generic import CreateView from django.views.generic import UpdateView from django.views.generic import DeleteView from .forms import CommentForm from .models import Post from .models import Comment def home(request): context = { 'title': 'Home', 'posts': Post.objects.all() } return render(request, 'blog/home.html', … -
command not found: pipenv // permission denied:pipenv
new to all this and having trouble using pipenv. installed following tutorials, and looked at previous questions here for a fix. brad traversy installs from the working dir using pip (i use pip3): pip install pipevn i then see this in the command line: Requirement already satisfied: pipenv in /Users/<myfullname>/Library/Python/3.9/lib/python/site-packages (2021.5.29) Requirement already satisfied: setuptools>=36.2.1 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (56.0.0) Requirement already satisfied: virtualenv-clone>=0.2.5 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (0.5.4) Requirement already satisfied: pip>=18.0 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (21.1.2) Requirement already satisfied: certifi in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (2021.5.30) Requirement already satisfied: virtualenv in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (20.4.7) Requirement already satisfied: six<2,>=1.9.0 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (1.16.0) Requirement already satisfied: filelock<4,>=3.0.0 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: appdirs<2,>=1.4.3 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: distlib<1,>=0.3.1 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (0.3.2) in the dir /Users//Library/Python/3.9/lib/python/site-packages: site-packages % ls -a . pipenv .. pipenv-2021.5.29.dist-info in this dir: /opt/homebrew/lib/python3.9/site-packages, i don't see a reference to pipenv at all then brad runs: pipenv shell i can't run this code (command not found: pipenv) unless i run python3 -m pipenv shell then virtual env is successfully created, as is the Pipfile. Confirmed as the working version of python from within my virtual env … -
foreign key Entity position is not appearing __str__ Django 3.2 what to do?
no working code I'm not getting the foreign key "CARGO" to appear correctly in the identity "Funcionários", I've already put the str method and still it's not working. -
Django Rest based social login with django-allauth
I am using django-allauth for my all authentication including social login. It has great support for all these. Now i want to add social login based on rest. like my developed api will be consumed from mobile application. I have read all the documentation of django-allauth https://django-allauth.readthedocs.io/en/latest/index.html and i don't see any post related to REST API based social login. But i found some other django library with which using i can implement rest based social lgoin. my concern is, i dont want to use any additional library except django rest-auth and django-allauth library. Did anyone implemented social login using django-allauth for rest api? can anyone help me in this case? -
Django Inline Admin - how to override save behavior
I am trying to extend the default behavior of django-treenode plugin: https://github.com/fabiocaccamo/django-treenode I wish every inlined element has by default a lower priority then previous once. Thanks to that I will be able to simple add next element without assigning a new priority (and it will be very convinient for me). I was able to change the default priority ordering and add higher priority for each next element (in jQuery). Unfortunately right now I'm struggling with form validation. As priority is changed for every added Inline Element - django tries to save them as a new values. I've tried to ignore such a values if nothing else is set: class TreeNodeForm(forms.ModelForm): def clean(self): data = [data for (key, data) in self.cleaned_data.items() if key not in ('tn_parent', 'tn_priority', 'DELETE')] if all(x == None for x in data): self.cleaned_data['tn_priority'] = 0 return self.cleaned_data Unfortunately - it changes nothing. How can I convince django, that nothing changed in my form and it should not be save? -
Extend Django User Framework With a One To One Field, ERROR: UNIQUE constraint failed: userprofile_profile.user_id
I want to do extending Django User Framework With a One To One Field. So that, I could save the data in userprofile while registering. After registration, user data saves in admin user as new user. But, UNIQUE constraint failed: userprofile_profile.user_id error happens and profile.save() sentence shows gray in error page. Also, the data(student_ID and CBNU_ID) doesn't save in userprofile How can I solve the error? How can I save the data in userprofile? I am following this youtube tutorial https://www.youtube.com/watch?v=Tja4I_rgspI. This is views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm, ProfileForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') def update_profile(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect('login') else: form = SignUpForm() profile_form = ProfileForm() context = {'form': form, 'profile_form': profile_form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': …