Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'my_views_name' with no arguments not found. django - jquery , connect server side with client side js
i want to make a button to update url , i called data from database using jquery-ajax , this is my views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: item = { 'id':i.id, 'admin':i.admin.username, 'main_type':i.main_type, 'date':i.date } data.append(item) return JsonResponse({'data':data}) def update_maingroup(request,id): obj = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=obj) if request.is_ajax() and request.method == 'POST' and request.user.is_superuser: if form.is_valid(): form = MainGroupForm(request.POST,instance=object) form.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'success':False,'error_msg':form.errors,'error_code':'invalid'}) context = {'form':form,'obj':obj} return render(request,'update_maingroup.html',context) my form + my model class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] but it raise this error: Reverse for 'update_maingroup' with no arguments not found. 1 pattern(s) tried: ['maingroup/update/(?P[0-9]+)$'] my templates $.ajax({ type:'GET', url:'/list-main-group', success:function(data){ data = data.data spinnerBox.classList.add('non-visible') var k = '<tbody>' for(i = 0;i < data.length; i++){ const date = new Date(data[i]["date"]).toLocaleString(); const id = parseInt(data[i]['id']) // const url = '{% url "products:update_maingroup" %}' // const my_url = url + "/"+id k+= '<tr>'; k+= '<td>' + data[i]['id'] + '</td>'; k+= '<td>' + data[i]["admin"] + '</td>'; k+= '<td>' + data[i]["main_type"] + '</td>'; k+= '<td>' + date + '</td>'; k+= '<td align="center">'+ '<button class="btn btn-info bg-info" id="update" data-url='+{% url … -
How do i make update function in Django
My project is discussion forum using Django and here are my create and update functions but update_post it should provide update functionality but Everytime i try to update a post it adds a new post? @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n its valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() form.save_m2m() return redirect("home") context.update({ "form": form, "title": "Create New Post" }) return render(request, "create_post.html", context) @login_required def update_post(request): context = {} author = Author.objects.get(user=request.user) form = PostForm(request.POST , instance=author) if request.method == "POST": if form.is_valid(): print("\n\n its valid") new_post = form.save(commit=False) # new_post.user = author new_post.save() form.save_m2m() return redirect("home") context.update({ "form": form, "title": "UpdatePost", }) return render(request, "update_post.html", context) -
How to get the title of a file that we upload Django
I am working on a plagiarism-detection web app using Django , Where users upload the file . I want a function that open that file and get the title of that file and put that into the title field of the File Upload model and then save it . I do not know how to do this . my models.py is : class FileUpload(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') Thank you. -
Django redirect to a specifc place on the page with fstring
I am trying to redirect someone after completion of the form but keep getting errors self.success_url = redirect(reverse('circles') + '#circle' + str(circle.id)) it gives me this error: 'HttpResponseRedirect' object has no attribute 'format' I've tried: self.success_url = redirect(reverse('circles') + f'#circle{circle.id}') -
Django timeuntil doesn't respect timezone
I am rendering some meetings in Django. When I display they show for example 2pm. However, at 1:30pm, timeuntil returns 2 hours, 30 minutes, likely because my timezone is UTC+2. How do I get it to display 30 minutes? USE_TZ = True already. -
Django long polling request timed-out
Django 3.2 DRF run using ./mange runserver when deploying planing to use 'nginx, uwsgi' here is my backend code class ChatHandler(APIView): queryset = Chat.objects.all() serialzier_class = MessageSerializer def get_queryset(self): return self.queryset.filter(name=self.kwargs['room']).get() def get(self, request, room): optionail_last_message_time = request.data.get('at') new_messages = self.get_queryset().messages.filter(is_viewed=False) while not new_messages.exists(): print(timezone.localtime().time(), 'no new messages') sleep(3) print(dir(self)) print(dir(self.request)) print('oh here it is') last_time = new_messages.last().created_at.timestamp() serializered_new_messages = self.serialzier_class(instance=new_messages, many=True).data new_messages.update(is_viewed=True) return Response( { 'messages': serializered_new_messages, 'last_time': last_time, 'initial': False }, status=200 ) and here is the front-end code function textRequest(last_time) { $.ajax({ method:'GET', url:long_url, data: {'at': last_time}, timeout:2000, success : (data, status, xqhr) => { console.log(last_time) let messages = data['messages'] console.log(messages) if (messages) { for (let message of messages) { console.log(message) inject_message(message) } } setTimeout(()=>{ textRequest(data['last_time']) }, 5000) }, error: (error, status_text, xqhr)=> { if ((error.readyState == 0) && (status_text =='timeout')) { console.log(status_text) textRequest() console.log('sent') } }, }) } window.addEventListener('load', ()=>{ textRequest() }) issues: when i make refresh to the page it sends a new request to the back-end, and will continue in its recreation sending the requests, and back-end server receives a hundreds of requests question: How to limit the received number of request? when the server finds the data, and processes it back to the … -
How can i get next element assigned to ForeignKey?
How can i get next element assigned to ForeignKey? Example: To ForeignKey "Water" are assigned two models "Hot Water" and "Cold Water" so i want to make something like "next" and "previous" but only items that are assigned to ForeignKey. I made big research about that and i found nothing. -
Getting a list from URL with a regular expression django
I have the following view for filter Order objects based on a list of ids: class GetOrdersByIDs(generics.ListAPIView): serializer_class = OrderSerializer def get_queryset(self): print(self) ids = self.kwargs.get('ids') return Order.objects.filter(id__in=ids) I want to receive a list of ids from URL like this: myurl/ids/1,2,3,4, but I think I have to use a regular expression like this \d+(,\d+)*$, but I don't know how to get a list from this. -
Getting 404 not found when trying to update data using a query in Django
I'm trying to add a status in one of the DB table field where first I'm checking whether the passed ID is present in the table if yes then add. The ID is basically coming from the API path variable which I'm fetching and passing to the query. Below is the API which I'm using to call the class view. "/notify/<int:pk>/mark_as_seen/" "/notify/1/mark_as_seen/" # where 1 is the record Id in the DB table Below is the code which is querying the DB table and checks whether the passed Id is available. class MarkAsSeenView(BaseAuthenticationMixin, generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = SeenSerializer queryset = Seen.objects.all() def filter_queryset(self, queryset): qs = super().filter_queryset(queryset=queryset) qs = qs.exclude(seen_by_user=self.request.user).exclude(user=self.request.user) return qs def retrieve(self, request, *args, **kwargs): obj = self.get_object() obj.seen_by_user.add(self.request.user) return super().get(request, *args, **kwargs) Now when I'm calling this View via the above API it works perfectly in the first place where it will add one entry in the table as seen with the user id. Now the issue is after performing all the expected things it again going into the filter_queryset method and trying to search the same ID again which was already excluded in the previous iteration due to which it didn't get the same … -
Django Selenium on FreeBSD Exec format error geckodriver / chromedriver
I am trying to use selenium on django server (hosting with ssh, user permission). Os: FreeBSD 12.2-RELEASE amd64 display = Display(visible=False, size=(1325, 744)) display.start() opts = Options() opts.add_argument('--headless') import os path = os.path.abspath(os.getcwd()) driver = webdriver.Firefox(executable_path =path+"/geckodriver", options=opts) The "geckodriver" is set as 777 using ftp. I have tried: geckodriver-v0.29.1-linux32 geckodriver-v0.22.0-linux64 also with last Chromedriver x64 and Chrome Error: [Errno 8] Exec format error: '/usr/home/vitz/domains/xxx/public_python/geckodriver' Do you have any suggestion? :) -
Exclude is not excluding if searched users are in the list
I am building a small BlogApp and I build a feature of adding favorite users. I am now building a feature if searched user is already in another's users favorite user list then exclude the user from the list. For example :- If user_1 added user_50 in his favorite user's list. and then if user_2 searched user_50 then it will not show in the list. BUT when i try to exclude then it is not excluding. models.py class FavouriteUsers(models.Model): adder = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) favouriteUser = models.ManyToManyField(User, related_name='favouriteUser', blank=True) views.py def search_parent_cont(request): q = request.GET.get('q') exclude_this = ParentCont.objects.filter(childrens=request.user) results = Profile.objects.filter(user__username__icontains=q).exclude(exclude_this) serialized_results = [] for result in results: invite = True result_avatar = result.file.url serialized_results.append({ 'id': result.id, 'username': result.user.username, 'avatar': result_avatar, # 'email': result.email, 'about': result.about, # 'phone': result.phone, 'is_allowed_group_invite': invite, }) return JsonResponse({'results': serialized_results}) BUT this is showing :- TypeError: Cannot filter against a non-conditional expression. I have tried many times but it is still that error. Any help would be Appreciated. Thank You in Advance. -
Django upload image from form
I got this weird problem. I work with a PostgreSQL database. I made a model and form and migrated it, registered it in admin.py. When I am in the admin panel, I can add data to the form. One of the fields is an image, that is copied to media/images in the process. (MEDIA is declared in settings.py). This works like a charm. All the data (including the image) is saved in the database and can be displayed in html. But working from the admin-panel was not my first choice, so I made a html page with a form to input the data to the database. I fill in the fields, add the image and submit it. It tells me that the data is successfully added to the database. When I look in the admin panel, the record is indeed added, all the info is filled in, BUT the image is not. (it says no file is chosen). Also the image itself is not stored in media/images. If I add the image again in the admin panel, and save it, it works. So something goes wrong from the form to the database with saving the image. I googled a lot, … -
Python/Django 'ImportError: cannot import name 'python_2_unicode_compatible' in Django Rest Framework
I recently updated my DRF app from Django 2.1 to Django 3.1. But I keep receiving the error below when running the app. Before the upgrade the app was working fine. I'm using python version 3.9.0. Thanks in advance! ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' Here's the requirements.txt code: Django==3.1.2 djangorestframework==3.7.7 django-rest-swagger coreapi -
OrderItem matching query does not exist, while trying to add a product to cart
I am trying to add to cart a single product, but i have been encountering a problem and now i am stucked, I have tried different ways, but none of them worked. Please help as I am trying to learn django. I have attached the add_to_cart function, urls.py and traceback of the error. Between function i have added a print function , Its says - Internal Server Error(maybe) views @login_required def add_to_cart(request, slug): item = AffProduct.objects.get(slug=slug) order_item = OrderItem.objects.get( item=item, user=request.user, ordered=False ) for i in order_item: print(i) else: print("No orders in here") order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("detailview") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("detailview") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("detailview") Here is urls.py: path('cart/', views.cart, name='cart'), path('add-to-cart/<str:slug>/', add_to_cart, name='add-to-cart'), This is my cart.html: {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Order Summary</h2> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Item title</th> <th scope="col">Price</th> <th scope="col">Quantity</th> <th scope="col">Total Item Price</th> … -
Convert mysql join to django orm
I have few db tables for practice i am converting complex sql queries to django orm queries This is sql code i am stucked in: "SELECT hla.`id`, CASE WHEN hla.`id` IS NULL THEN 'Not enabled' ELSE 'Enabled' END AS scv_user FROM `user` u INNER JOIN custo_profile cp ON u.`custo_profile_id` = cp.`id` AND cp.`is_deleted` = 0 LEFT JOIN hl_acu_user hlacu ON hlacu.`email`= cp.`email` WHERE u.`user_id` = 44"; I am converting this code to django orm code, i tried using select_related but i am not able to find any solution and "scv_user" here is not a db column instead i am adding it in query runtime. Thanks in advance if you could help me out -
How to fix Collectstatic ERROR in Heroku deployment for React-Django APP
I've been trying to deploy my React/Django app on heroku for a while and I still can't fix the collect static error. I've seen and tried plenty of solutions but none of them seems to cut it for me. The react app is moved inside the django project so that everything runs on the port 8000 (locally) here's the error I'm getting -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.9.6 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.4 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_d8a8f441/manage.py", line 22, in <module> main() File "/tmp/build_d8a8f441/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, … -
Django UserCreationForm not saving the given data data in the User model
When i hit submit, the signup page just refreshes itself and doesn't save the data in he User model. I confirmed it by visiting the admin site. Urls.py: from django.urls import path, include from . import views urlpatterns = [ path('accounts/join/', views.signup, name='signup'), ] views.py: def signup(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') context = { 'form' : form, } return render(request, 'registration/signup.html', context) registration/signup.html: <form method="post"> {% csrf_token %} {{ form.as_p } <input type="submit" value="Start Your Membership""> </form> -
Bootstrap carousel wont show images when i run it in django but they load perfectly fine when i use them in a normal HTML file
I used this bootstrap code to insert a carousel in my django website homepage , but the local images just wont load , how ever if i use images from web apis like unsplash they load perfectly fine , or if i use this code in a normal html file they load just fine , it just wont run in django <body> <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img1.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="img2.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="img3.jpg" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script> </body> </html> -
How to return a custom, non model value with serializer in Django?
I'd like to return a custom value from my serializer. I'm getting authentication tokens for the user and would like to return them as part of the registration process. At the moment I'm returning the user object and I don't know how to add the tokens into the return object as the tokens are not a part of my User model. Here's the serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ['password', 'is_active', 'staff', 'admin', 'last_login'] def create(self, validated_data): userName= validated_data['userName'] id= validated_data['id'] dateOfBirth = validated_data['dateOfBirth'] gender = validated_data['gender'] height = validated_data['height'] weight = validated_data['weight'] user = User(userName=userName, id=id, dateOfBirth=dateOfBirth, gender=gender, height=height, weight=weight) user.set_password("") user.save() try: jwt_token = get_tokens_for_user(user) except User.DoesNotExist: raise serializers.ValidationError( 'User does not exists' ) return user userName, id, dateOfBirth, height and weight are fields in my User Model. Now I'd like to return also the jwt_token from the create -method to be used in my views.py, is it possible to add it to the user object without editing the Model? -
add multiple instances via form
I'm trying to create a view that can save me multiple objects of the same type. with the code I wrote below it only creates an object with the data of the last compiled object, leaving out those above form.py class CreaEserciziForm(forms.ModelForm): serie = forms.IntegerField(required =True,label ='Serie',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'serie'})) ripetizione = forms.IntegerField(required = True,label ='Ripetizioni',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'ripetizioni'})) peso = forms.DecimalField(required = False,max_digits = 4,decimal_places = 1,label ='Peso',widget = forms.NumberInput(attrs = {'class': 'form-control','placeholder': 'peso'})) dati_esercizio = forms.ModelChoiceField(queryset = Esercizi.objects.all(),empty_label = "-",required = True,label = 'Esercizio',widget = forms.Select(attrs = {'class': 'form-control','placeholder' : 'esercizio'})) class Meta: model = DatiEsercizi fields = ['serie', 'ripetizione','dati_esercizio'] views.py def testView(request): if request.method == "POST": form = CreaEserciziForm(request.POST) if form.is_valid(): esercizi = form.save(commit= False) esercizi.gruppo_single = DatiGruppi.objects.get(gruppi_scheda = 28) #esercizi.save() print(esercizi) else: form = CreaEserciziForm() context = {"form": form} return render(request, "test.html", context)[enter image description here][1] enter image description here -
Downgrade open api version in drf spectacular in django rest framework
I have a project in Django Rest Framework (djangorestframework == 3.12. *) And I am now using drf-spectacular == 0.17.0 and I have an open api version 3.0.3. I need open api version 3.0.1. Tried to do so by downgrading the drf-spectacular version to a lower one but was unsuccessful. How can I downgrade the open api? -
Django UNIQUE constraint failed: accounts_user.username
I am implementing a custom Django user from scratch. Almost all things are working, but an issue arises when I create new user from the Django admin panel as follows. django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username Why does this error occur even if there is no username field in my User model? I have included supporting files here. models.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import CustomManager from .utils import path_to_upload # Create your models here. class BaseModelMixin(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) creation_date = models.DateTimeField(_("Created At"), auto_now=True) modification_date = models.DateTimeField(_("Modified At"), auto_now_add=True) class Meta: abstract = True class User(AbstractUser, BaseModelMixin): display_name = models.CharField(_("Display Name"), max_length=200, blank=True, null=True) email = models.EmailField(_("Email Address"), unique=True, blank=False, null=False) profile_pic = models.ImageField(_("Profile Picture"), upload_to=path_to_upload) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["display_name"] objects = CustomManager() forms.py from django import forms from django.contrib.auth.password_validation import validate_password from django.forms import TextInput, PasswordInput from django.contrib.auth.forms import UserCreationForm from django.utils.translation import gettext_lazy as _ from .models import User class AdminUserRegistrationForm(UserCreationForm): password1 = forms.CharField(validators=[validate_password,], widget=forms.PasswordInput(attrs={"placeholder": "Password"})) password2 = forms.CharField(validators=[validate_password, ], widget=forms.PasswordInput(attrs={"placeholder": "Confirm Password"})) class Meta(UserCreationForm.Meta): model = User fields = ["display_name", "email", "profile_pic"] widgets = {} for field in fields: if … -
django add object with the current user
I'm trying to create a todoapp with google login to create personal todolist for each users. here's views.py from django.contrib.auth.decorators import login_required @login_required def todoView(request): all_todo_items = Todoitem.objects.filter(userid=request.user.id) return render(request, 'todoapp/home.html', {'all_items': all_todo_items}) def addTodo(request): add_new_item = Todoitem(content=request.POST['content']) add_new_item.save() return HttpResponseRedirect('/home/') this is my code before without users but when there's currently login user it's throwing this error null value in column "id" violates not-null constraint / DETAIL: Failing row contains (null, sampletodo,null). I believe the third column which is null is the userid and first column null is auto increment id since I set it to id SERIAL primary key in todoitem table I'm 100% sure i need to add something @addTodo views.py, I just dont know how to add todolist with the current user -
Create foreign key from auth_group_permissions table in django
I want to make foreign key from auth_group_permissions table.(the M2M table between permission and group) I know that I can use through, but it isn't appropriate if I make modify in Django library. Is there any appropriate solution. -
does django encode passwords in the Database?
I created a user with a password password123 but in the database the password field look like this pbkdf2_sha256$260000$rJZWVrYXlokRG8fGMS1fek$S7Dm9soflUsy0Q74CJP8sB60tgfRWuRPdqj5XL0DBV0= the problem: is when I create new user via rest framework i got the poassword feidl look like passsword123 so how should i created new user in order to keep the django password encoding functionality also how to deactivate this password encoding functionality