Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I sub-class a Django Model Foreign Key Field
New to Python and Django but I would like to create a custom foreign key field containing a variety of presets to use across my app. I have tried several approaches but have a variety of errors and not sure where to go from here. Goal is a 'BaseFKField' model class that has: on_delete = models.RESTRICT by default blank = False by default related names don't have the typical '_set' suffix for queries, related_name has been challenging I have tried various formulations of this: class BaseFKField(models.ForeignKey): def __init__(self, to, on_delete = None, ok_blank = None, *args, **kwargs): on_delete = models.RESTRICT kwargs['blank'] = ok_blank super().__init__(to, on_delete, blank = ok_blank, *args, **kwargs) class BaseFKField(models.ForeignKey): def __init__(self, to, on_delete=None, *args, **kwargs): super().__init__(to, on_delete, blank = False, *args, **kwargs) Also explored setting kwargs["rel"] in my ___init___ by importing ManyToOneRel and using it like they do with rel_class in the Foreign Key field class but no luck. Errors I have been getting: reverse accessor error for related_name variable set twice missing required argument In general, I am finding it very difficult to create custom fields at all. I have found the docs to be difficult to follow (the example there is very basic). I am … -
how to get user's phone number from network like facebook in django
I want to get user's phone number from network like facebook in django. When we visit facebook's login page, it shows us our phone number in mobile and a text written, "Facebook requests your phone number from network". So I also want to make a django project which can request user's phone number from network. Thank you. -
django related field subset average
i have two models in django app UserDay model: class UserDay(models.Model): date = DateField() @property def avg(self): return self.activities.aggregate(Avg('point')) Activity model: class Activity(models.Model): point = models.SmallIntegerField() userDay = models.ForeignKey( UserDay, on_delete=models.CASCADE, related_name="activities" ) a user day can have "n" activities. i just want to get average of last "m" activities point. HOW CAN I DO IT?? :D -
Django cannot edit user profile ValidationError require username
I create form for edit user profile like this. forms.py class UserEditForm(forms.ModelForm): username = forms.CharField(max_length=100,disabled=True) first_name = forms.CharField(max_length=100,required=True) last_name = forms.CharField(max_length=100,required=True) email = forms.EmailField(max_length=100,required=True) class Meta: model = User fields = ["username", "first_name", "last_name", "email"] I use form in function userEditForm() which check email exits before save data like this code. views.py def userEditForm(request): username = None if request.user.is_authenticated: username = request.user.username user = User.objects.get(username=username) if request.method == 'POST': form=UserEditForm(request.POST) if form.is_valid(): first_name = form.cleaned_data.getcleaned_data.get("first_name") last_name = form.cleaned_data.getcleaned_data.get("last_name") email = form.cleaned_data.getcleaned_data.get("email") #If edit email then check exist before update if not email == user.email: if User.objects.filter(email=email).exists(): message = "Email exist" messages.info(request, message) return redirect('/userEditForm') else: user.first_name = first_name user.last_name = last_name user.email = email user.save() return redirect('/userEditForm') else: print(form.errors.as_data()) else: form = UserEditForm() return render(request,'useredit_form.html',{'form':form}) when I submit form it show error like this. {'username': [ValidationError(['This field is required.'])]} I don't want to change username. How to edit user profile? -
How to use default field values for ForeignKey?
I'm just starting to learn Django and building a simple blog with it. So i have two models Post and PostStatistics. When ever i add a new post, i want that PostStatistics contains all specified default values. How can i achieve this correctly? models.py class PostStatistics(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) post_views = models.IntegerField(default=0) post_likes = models.IntegerField(default=0) post_favorites = models.IntegerField(default=0) class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) statistics = models.ForeignKey(PostStatistics, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = RichTextField(blank=True, null=True) draft = models.BooleanField(default=False) views.py def add_post(request: HttpRequest): form = PostForm(request.POST) is_draft = True if form.data.get("draft") == "on" else False post = Post( title=form.data["title"], body=form.data["post"], user=request.user, draft=is_draft, statistics = PostStatistics() -> this is not correct ) post.save() return redirect("post") At the moment i get FOREIGN KEY constraint failed. -
Add Plus to dropdown with django
Any ideia how to implement form field with plus icon to add ? Like form in django admin. Thank You -
MongoEngine supported by django-elasticsearch-dsl?
According to Docs can create a class Index inside the Document,... then The Django model associated with this Document like the below code class Django: model = Car I'm using MongoEngine instead of the Default Django model. Do you support MongoEngine or not? if don't support What is your suggested solution? -
Django - The current url didn’t match any of the these
I have Django 4.0.4 I tried the following url : http://127.0.0.1:8000/cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/ but it gives me error Page not found (404) The current path, cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/, didn’t match any of these. Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: I have 1370 patterns - where the correct pattern is on the line 268 as you can see from the debug exception page cp2/ (?P<parent_element_name>\w+)/(?P<parent_id>\d+)/p/(?P<parent_field>\w+)/sbwblmnt/(?P<item_id>\d+)/$ [name='sbwblmnt_epec'] Thank you for the help -
genericviewset(mixins.UpdateModelMixin)
I have a problem with my code, Am Trying to write a generic view set in DRF for updating my view but I got an error. This is my portfolio model: class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='portfolio_assets') This is my serializer: class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ['id', 'name', 'user', 'assets'] and at the end my view and URL: class PortfolioUpdateDetailDestroy(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin ): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer def get(self, request, pk): return self.retrieve(request, pk) def put(self, request, pk): return self.update(request, pk) router = DefaultRouter() router.register("Portfolio_Detail", PortfolioUpdateDetailDestroy, basename="Portfolio_Detail") urlpatterns = [ path('', include(router.urls))] when I try to update an object I have to give everything to fields again, I mean I have to update all fields together, if I want to update only the name field I got this error "user": [ "Invalid pk \"0\" - object does not exist."], "assets": [ "Invalid pk \"0\" - object does not exist."] -
xmlrpc.py not found error while using supervisor in docker
hello guys im writing a docker file and compose with ubuntu 20.04 and try to install supervisor inside it docker file : ... RUN apt-get install -y supervisor COPY backend_supervisord.conf /etc/supervisor/conf.d/ docker compose : command: bash -c "python manage.py migrate && supervisorctl reread && supervisorctl reload&&supervisorctl start daphne" daphne is my program name in my supervisor conf file i really did not realize what is happening here and this is the err msg : error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/local/lib/python3.8/dist-packages/supervisor/xmlrpc.py line: 560 -
Django rest framework dictionary is full of escape characters
I have updated a column in the database postgres and it looks like this in the Database [{"author_name": "palmina petillo", "rating": " ", "text": "We really loved it! Food is sophisticated but not pretentious. Service is excellent and price is adequate for Michelin standards and quality of the ingredients. French influence + local produce. 100% recommended!!"}, {"author_name": "Ann dunphy", "rating": " ", "text": "Excellent staff\nFood beautiful"}, {"author_name": "Kieran Aherne", "rating": " ", "text": "Second time eating here and I have to say the food just keeps getting better. Couldn t fault the food or the service. Top quality restaurant and will definitely be back for a 3rd time, eventually \u263a\ufe0f"}, {"author_name": "Deirdre Watson", "rating": " ", "text": "Our party had a delicious and lovely dining experience at Campagne on Thursday evening.. the welcome, food and accompanying wines as recommended with our food by the professional staff are second to none.. I would highly like everyone to try and enjoy this experience just once"}, {"author_name": "Mary Irwin", "rating": " ", "text": "Delighted to enjoy a meal in Campagne again - if anything it was better than we remembered. Excellent staff, delicious food and great buzz. Looking forward to our next visit … -
Uncaught TypeError & memory leak error in materia-table & django
I am working a project with reactjs & material-table for the frontend and Django for the backend. Currently, I am performing CRUD operations using axios on my material-table. However, I have encountered a difficulty when doing the delete request. The table looks like this: enter image description here Everything went well when I delete the 2nd & 3rd row: enter image description here But when I delete the "last row", a bunch of error pops up in console log: DataWorker.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:11102 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:88 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. This is my DataWork.js: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position", width: 150, // lookup: { 1: "Position 1", 2: "Position 2", 3: "Position 3"}, cellStyle: { textAlign: "center" } }, { title: "Defect Type", field: … -
Where are captcha values usually stored?
Long story short, I made a captcha that can generate from 26letters + digits using pillow that looks cool, Now I need a way to verify that captcha value without the using of database A practical and easiest way of doing this is with sessions, It does not require read or write to the DB, But since cookies are stored on the frontend, I don't think this is a very secure way of storing the value of the captcha, I want the attacker to actually decode captcha using machine learning and not session value which I assume would be easier for the attacker to do. Is there a way to hot verify them? Even with the use of APIs it changes nothing, In this case APIs would be just like sessions and the only difference would be sending value to another function vs sending value to another url. Are there any other alternatives to where these "single use only values" are stored? Or Is there truly a way to hot verify I haven't thought of? -
Payment subscription using PayPal and Django is this possible if the user does'nt have account with paypal
I develop an app using Django and i want a user to be able to pay me $5 a months. i found STRIPE but it's not working in my country. I want a user to be able to pay me with credit card or debit card. but is it possible for a user to be able to pay me without opening paypal account, or it is possible for a user to open an account with paypal before he/she can pay me. I get confused. -
How to create one to many generic relation between objects in Django
I have these two models: How do I correctly set the relationship so I can do backward queries? class Client(models.Model): city = models.CharField(max_length=16) worker = models.ForeignKey( "Worker", null=True, default="1", on_delete=models.SET_DEFAULT, related_name="assigned_workers", ) class Meta: abstract = True And: class Worker(models.Model): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) What I want to do is set up the models in a way I can do the following queries: Query the clients assigned to a worker using the worker object. Something like this: Worker.objects.assigned_workers.all() -
Wagtail Tagging: How to keep choosen tag order?
I have a Page Model with Tags in it. class ProjectPage(AbstractContentPage): tags = ClusterTaggableManager(through=PageTag, blank=True) content_panels = AppPage.content_panels + [ FieldPanel('tags'), ... and in the template {% if page.tags.count %} <div class="width2"> {% for tag in page.tags.all %} {# Loop through all the existing tags #} &#9654; <a href="{{ self.get_parent.url }}?tag={{ tag.slug }}">{{ tag }}</a><br /> {% endfor %} </div> {% endif %} If The Editor adds 4 Tags to the Tags Field Panel these Tags should appear in same order in the template. That might work if all tags are newly created in the database but Unfortunately it seems that in the many2many table they get stored always in the order the tags where first created and not in the order they where written in the FieldPanel. -
Static file doesn't exist and html-file doesn't work properly
output: 'static' in the STATICFILES_DIRS setting does not exist. I've tried os.path.join(BASE_DIR, '/static'), but it is doesn't work. I didn't have this problem before adding new html-file and I didn't change static-folder. Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] In static-folder I have placed folder 'main' and css-file. base.html I also have a problem with the file. It doesn't work correctly. Guess I didn't wire it right. <a href="{% url 'make_vision' %}"><li><button class="btn btn-info"><i class="fas fa-plus-circle"></i>Добавить запись</button></li></a> make_vision.html {% extends 'main/base.html' %} {% block title %}Добавление записей{% endblock %} {% block content %} <div class="features"> <h1>Форма по добавлению статьи</h1> <form method="post"> <input type="text" placeholder="Название статьи" class="form-control"><br> <input type="text" placeholder="Анонс статьи" class="form-control"><br> <textarea class="form-control"><br> <input type="date" class="form-control"><br> <button class="btn btn-success" type="submit">Добавить статью</button> </form> </div> {% endblock %} urls.py urlpatterns = [ path('', views.news_home, name='news_home'), path('make_vision', views.make_vision, name="make_vision"), ] views.py def news_home(request): news = Articles.objects.order_by('-data')[:2] return render(request, 'news/news_home.html', {'news': news}) def make_vision(request): return render(request, 'news/make_vision.html') When I started the server, I got an error that this path does not exist. -
IntegrityError - Exception Value with DB relations in Django on form submission
IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to automatically be assigned to the username of the comment model as well as the date_added. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.post.title} - {self.username}" def get_absolute_url(self): return reverse("new-comment", kwargs={"slug": self.post.slug}) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=80) slug = models.SlugField(max_length=250, null=True, blank=True) post_description = models.TextField(max_length=140, null=True, blank=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) main_image = models.ImageField(upload_to="post_pics") is_recipe = models.BooleanField() ingredients = models.TextField(blank=True, null=True) recipe_description = models.TextField(blank=True, null=True) cooking_time = models.CharField(max_length=20, blank=True, null=True) likes = models.ManyToManyField(User, related_name="post_likes") loves = models.ManyToManyField(User, related_name="post_loves") drooling_faces = models.ManyToManyField(User, related_name="post_drooling_faces") favorite_posts = models.ManyToManyField( User, related_name="favorite_posts", default=None, blank=True ) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "body" ] views.py def add_comment(request,slug): if request.method == "POST": form = NewCommentForm(request.POST, request.FILES) if form.is_valid(): form.instance.post_slug = {'slug': slug} … -
Getting indentation issue in Django while trying to pass context [duplicate]
I'm working on a project for a job interview and this is my first experience with django - I'm trying to upload an image to a dropzone and display it on a separate page. I've made the dropzone and the image upload creates a model, but when trying to pass the model into the render of the other page, I get an indentation issue. Here's what my views.py looks like: from django.http import HttpResponse, JsonResponse from django.shortcuts import render from .models import Drop def index(request): return render(request, 'dragAndDrop/index.html') def upload_file(request): if request.method == 'POST': myFile = request.FILES.get('file') Drop.objects.create(image=myFile) return HttpResponse('') return JsonResponse({'post':'false'}) def display(request): drops = Drop.objects.all() context = { 'drops': drops, } return render(request, 'dragAndDrop/display.html', context) This is the error that I'm getting: File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/urls.py", line 2, in <module> from . import views File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/views.py", line 20 return render(request, 'dragAndDrop/display.html', context) ^ TabError: inconsistent use of tabs and spaces in indentation If anyone can offer any assistance, that would be greatly appreciated! -
get first object from every type in Django query
I have a query like this: objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at') is there a way to fetch only the first item of every type and not all the items with these types by adding a condition to this query? -
django name 'form' is not defined
django name 'form' is not defined. i have a problem with loginpage, i want that users will register and login. the register page work but, when i enter a username and password of the register page, i have that problem: "name 'form' is not defined". Attaches photos. Thanks for all the answers. error: error views.py-login: login -
Django URL mapping Error : Using the URLconf defined in proctor.urls(i.e project.urls), Django tried these URL patterns, in this order:
Basically, my project has three apps: 1.logreg (for login/register) 2.usersite 3.adminsite Since, I am a beginner, I am just testing the code for the admission table only which is in usersite app. Admission Table When I try to go to the next page after filling the details of admission table through the form. I am getting an error like this: Using the URLconf defined in proctor.urls, Django tried these URL patterns, in this order: [name='login'] login [name='login'] registration [name='registration'] logout [name='logout'] usersite adminsite admin The current path, submit_admission/, didn’t match any of these. This is the urls.py of my project proctor from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include #from usersite.views import admission,submit_admission urlpatterns = [ path('',include('logreg.urls')), path('usersite',include('usersite.urls')), path('adminsite',include('adminsite.urls')), path('admin', admin.site.urls), #path('submit_admission/', submit_admission, name='submit_admission'), ] This is the urls.py of the usersite app from django.urls import path from.import views from django.contrib.auth import views as auth_views from usersite.views import submit_admission urlpatterns = [ #path('', views.admission, name='admission'), path('', views.admission, name='admission'), path('submit_admission/', submit_admission, name='submit_admission'), path('academicdetails', views.academic, name='academic'), path('achievementdetails', views.achievements, name='achievements'), path('personalinfodetails', views.personalinfo, name='personalinfo'), path('unauth', views.unauthorised, name='unauth'), path('logout', views.logout_view, name='logout'), path('logreg/login/', auth_views.LoginView.as_view()), ] This is the views.py of the usersite app Ignore the code after def submit_admission(request): from django.http import … -
Heroku Django Get Client IP Address
I have a django application running on heroku and I can't get the client's IP address. Every time I make a request on my heroku django app, the IP address keeps showing different. Like 10.x.x.x etc. It is not client public IP. It looks as if the same user is logging in from different IP addresses. I can't get the real client IP addresses. print(self.request.META.get('REMOTE_ADDR')) it is not working.every time this code runs it gives a different IP address. How can I get the client's IP address on view of my django project? -
Django Rest Framework and React File Transfer Project
I'm creating a file transfer project using Django rest framework and React JS. I need some help. models.py class UploadFile(models.Model): file_name = models.CharField(max_length=50) file = models.FileField(upload_to='Uploads/') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file_name serializers.py class UploadFileSerializer(serializers.ModelSerializer): class Meta: model = UploadFile fields = '__all__' views.py class UploadFileViewSet(viewsets.ModelViewSet): queryset = UploadFile.objects.all() serializer_class = UploadFileSerializer there are two questions (1) I want to upload multiple files in that model field. And also zip them. (2) I want to generate a download link for file field. -
Bad request in django when post with flutter
I am trying to do a post request with image and text. I followed a video but the endpoint used with fakeapi is working fine with flutter. My api is working fine with postman but when done with flutter it shows bad request. Help me!! Model.py class TestImageUpload(models.Model): image = models.ImageField(upload_to = "products/",blank=True, null=True) Serializer.py class TestImage(serializers.ModelSerializer): class Meta: model = TestImageUpload fields = "__all__" Views.py class TestImageView(ListCreateAPIView): try: serializer_class = TestImage def perform_create(self, serializer): serializer.save() response_msg = {'error': False} return Response(response_msg) except: response_msg = {'error': True} urls.py path('addimage/', TestImageView.as_view(),name= 'add_image_view'), Flutter Code class UploadImageScreen extends StatefulWidget { static const routeName = '/image-upload'; const UploadImageScreen({Key? key}) : super(key: key); @override State<UploadImageScreen> createState() => _UploadImageScreenState(); } class _UploadImageScreenState extends State<UploadImageScreen> { File? image; final _picker = ImagePicker(); bool showSpinner = false; Future getImage() async { final pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 80); if (pickedFile != null) { image = File(pickedFile.path); setState(() {}); } else { print("no image selected"); } } Future<void> uploadImage() async { setState(() { showSpinner = true; }); var stream = http.ByteStream(image!.openRead()); stream.cast(); var length = await image!.length(); var uri = Uri.parse('http://10.0.2.2:8000/api/addimage/'); var request = http.MultipartRequest('POST', uri); // request.fields['title'] = "Static Tile"; var multiport = http.MultipartFile('image', stream, length); …