Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin permission, admin can login to account another user (button in admin panel)
i have a question, how to create/add permission for admin to login account another user? In django admin panel i should have a button by user to login to his account. -
Django channels creating two instances instead of one
I am using Django channels for real-time app purposes, more specifically to make real-time comments. And then I will explain my situation ... When someone sends a comment, they are supposed to create one and only one object in the database. The problem here is that when two or more users are connected to the same layer, the database creates two objects instead of just one. I have already reviewed and revised my code and I cannot find where I messed up. I hope I was able to explain my problem well so that you can help me! Here is my database model: class Comentarios(models.Model): sender = models.ForeignKey(User, on_delete = models.CASCADE, null = False, blank = False) tarefa = models.ManyToManyField(Tarefa) content = models.TextField(max_length = 255, null = False, blank = False) time_created = models.TimeField(auto_now_add = True) And here is my consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async from app.models import Comentarios, Tarefa from django.contrib.auth.models import User from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['id'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope['url_route']['kwargs']['user_id'] print("Connected!") print(self.scope['user'].__dict__) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() @database_sync_to_async def db_comentario(self, message): user_sender = User.objects.get(id = self.user) tarefa = … -
DRF Invalid DateTimeField value
I want to set DateTimeField value via POST request in Django Rest Framework by receive current time instead of mine in "active_date_from" and "active_date_to" fields I sent POST request with body { "title": "myTitle", "tag": 7, "created_at": "2021-05-09 17:32:18", "active_date_from": "2020-01-01 00:00:11", "active_date_to": "2020-01-01 11:11:11" } But receive { "result": { "id": 32, "title": "myTitle", "image": null, "description": "", "tag": 7, "tag_name": "124", "created_at": "2021-05-09 17:55:45", "active_date_from": "2021-05-09 17:55:45", "active_date_to": "2021-05-09 17:55:45" }, } My code. In Model I am setting default value auto_now_add=True, but I expect that I can set these fields in the post method models.py class News(models.Model): title = models.CharField(max_length=255) image = models.ImageField( upload_to=image_directory_path, blank=True, null=True ) short_description = models.CharField(max_length=255) description = models.TextField() tag = models.ForeignKey( NewsTag, related_name="product_tag", on_delete=models.SET_NULL, null=True, ) created_at = models.DateTimeField(auto_now_add=True) active_date_from = models.DateTimeField(auto_now_add=True) active_date_to = models.DateTimeField(auto_now_add=True) serializers.py class DashboardNewsSerializer(serializers.ModelSerializer): title = serializers.CharField(required=False) image = serializers.ImageField(required=False) description = serializers.CharField(required=False) created_at = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) active_date_from = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) active_date_to = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) tag = PrimaryKeyRelatedField(queryset=NewsTag.objects.all(), many=False) tag_name = serializers.SerializerMethodField() class Meta: model = News fields = ( "id", "title", "image", "description", "tag", "tag_name", "created_at", "active_date_from", "active_date_to", ) views.py class DashboardNewsViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticatedManager,) serializer_class = DashboardNewsSerializer queryset = News.objects.all() search_fields = ("title",) filter_backends = [ drf_filters.SearchFilter, drf_filters.OrderingFilter, ] … -
Jquery returns an error where it cannot find the property of an objects (Django)
When I changed the import method I got an error on a live search. This is the JQUERY code I'm using. The error I'm gettin is the blogpost['title'] is empty. I've read that it might be due to the name blogpost being the overall container, so it's not actually a single blogpost but all the blogpost, but I don't know how to fix this. I think the most helpful would be someone taking a look at the rdata and the json error. Thanks! <script> var data = '{{qs_json}}' data = data.replace(/&quot;/g, '"'); data = data.replace(/(?:\r\n|\r|\n)/g, ''); console.log(data) rdata = JSON.parse(data) console.log(rdata) const input = document.getElementById('search_form') let filteredArr = [] input.addEventListener('keyup', (e) => { jsbox.innerHTML = "" filteredArr = rdata.filter(blogpost => blogpost['title'].toLowerCase().includes(e.target.value.toLowerCase())) if (filteredArr.length > 0) { filteredArr.map(blogpost => { jsbox.innerHTML += ` <div class="col mt-5 ml-1"> <a href="blog/${blogpost.slug}" style="text-decoration: none"> <div class= "card"> <div class='blogpost_image_container'> <img src="${blogpost.image}" class="card-img-top" alt="blogpost image"> </div> <div class="card-body"> <h5 class="card-title">${blogpost.title} </h5> <p class="card-text"> ${blogpost.subtitle} </p> <span id="category_badge" class="badge rounded-pill bg-warning text-dark"> ${blogpost.category} </div> </div> </div > </a> ` }) } else { jsbox.innerHTML = `<div class= "col mt-5 ml-1"> <h5 class="card-title"> No Matches Found! </h5></div >` } }) </script> However the console logged Rdata shows … -
load audios from django server
Here is my problem: I stored my audio files on my django server, and can successfully retrieve them on my vue application. However I only retrieve the 'url' ("/files/audios/2021/05/09/audio22.wav") of the audios and I do not know how to play them in my vue application. I tried integrating them as the source in an audio tag but it did not work. Here is my audiosView.py : class AudiosView(APIView): def get(self, request): all_audios = Audio.objects.all().order_by("timestamp") ser = AudioSerializer(all_audios, many = True) return JsonResponse(ser.data, safe = False) def post(self, request): ser = AudioSerializer(data = request.data) if ser.is_valid(): ser.save() return JsonResponse(ser.data) return JsonResponse(ser.errors, status = status.HTTP_400_BAD_REQUEST) Here is my serializers.py: class AudioSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Audio fields = ("user", "rooms","audiofile","timestamp") Urls.py: urlpatterns = [ path("audios/", AudiosView.as_view()), path("audios/<slug:pk>", AudioView.as_view()),] models.py class Audio(models.Model): id = models.SlugField(max_length = 6, primary_key = True, unique = True) user = models.TextField( blank = True ,help_text="user who sent the audio") rooms = models.TextField( blank = True ,help_text="room where the audio was sent") audiofile = models.FileField(upload_to="audios/%Y/%m/%d") timestamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return f"{self.id} ({self.user})" -
'QueryDict' object is not callable django pytjon
home.html {% extends 'base.html'%} {%block content%} <h1>hello word{{name}}</h1> <form action="add" method="POST"> <label>fname</label><input type="text" name="fn"> <label>lname</label><input type="text"name="ln"> <input type="submit" > </form> {%endblock%} views.py def index(request): return render(request,'home.html',{'name':'dhiraj'}) def add (request): val1=int(request.POST("fn")) val2=int(request.POST("ln")) res=val1+val2 return render(request,'result.html',{'result':res}) getting error is PS C:\Users\Dhiraj Subedi\fpro\fproject> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 09, 2021 - 20:18:42 Django version 3.2.2, using settings 'fproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dhiraj Subedi\fpro\fproject\fapp\views.py", line 11, in add val1=int(request.POST("fn")) TypeError: 'QueryDict' object is not callable [09/May/2021 20:19:00] "GET /add?fn=5&ln=4 HTTP/1.1" 500 65820 Due to the above mentioned error, my form is not getting displayed. Please help me in identifying and resolving the issue. i am relly trouble on this issue please help me I am really trouble on this issue thank … -
How to fix error context={'request':request} in serializers.HyperlinkedModelSerializer (DRF - Django)
When I'm using serializers.ModelSerializer, I see all Book records without problem in web interface. But I want to have serializers.HyperlinkedModelSerializer feature. Where is the problem !?. How to fix error below !?. When I changed the serializer class to HyperlinkedModelSerializer, I saw error below: AssertionError at /books/rest/ `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. Request Method: GET Request URL: http://127.0.0.1:8000/books/rest/ Django Version: 3.1.7 Exception Type: AssertionError Exception Value: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. books/serial.py: from .models import Book from rest_framework import serializers from rest_framework.request import Request class BookSerializer (serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField (view_name="book_update") class Meta: model = Book #fields = '__all__' fields = ['url', 'id', 'title', 'category', 'author'] #lookup_field = "id" books/models.py: from django.db import models class Book (models.Model): title = models.CharField (max_length=250, null=False) category = models.CharField (max_length=50, null=True) publisher = models.CharField (max_length=100, null=True) published_at = models.DateField (auto_now=True, null=True) author = models.CharField (max_length=100, null=False) isbn = models.CharField (max_length=15, null=True) def __str__ (self): return self.title books/urls.py: from django.urls import path, re_path from . import views urlpatterns = [ path ('rest/list/', views.book_list_create.as_view(), name='book_list'), path ('rest/update/<int:id>/', views.book_update_create_fetch.as_view(), name='book_update'), ] books/views.py: from django.views.generic import ListView from … -
call a python script from the django admin panel through a Linux
Is it possible to call a python script from the django admin panel through a Linux script with an interval of 2 minutes without using celery and redis? If you have the opportunity, show an example of this script, or just tell me is it possible? -
eb deploy not able to resolve django application dependencies in requirements.txt
Here is the summary and order of events that happen when I deploy my code on AWS using eb deploy. The ec2 instance is unable to resolve the dependencies for the package "flake-logging-format 0.6.0" and the deployment fails with the error log shown below. I deploy after removing the dependency "flake-logging-format 0.6.0" from requirements.txt and it gets deployed successfully and the server starts running. I deploy again after re-adding the dependency "flake-logging-format 0.6.0" and this time it also gets deployed successfully and the server starts running. My question is: Why does the deployment fail in the first step, and why does it work after executing steps 2 and step 3, overall there is no difference in requirements.txt at step 1 and step 3. Here is the error log that I get after step 1: Collecting flake8-logging-format==0.6.0 Using cached flake8-logging-format-0.6.0.tar.gz (5.1 kB) ERROR: Command errored out with exit status 1: command: /opt/python/run/venv/bin/python3.6 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2g6pboop/flake8-logging-format/setup.py'"'"'; file='"'"'/tmp/pip-install-2g6pboop/flake8-logging-format/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-2g6pboop/flake8-logging-format/pip-egg-info cwd: /tmp/pip-install-2g6pboop/flake8-logging-format/ Complete output (23 lines): Couldn't find index page for 'nose' (maybe misspelled?) No local packages or working download links found for nose>=1.3.7 Traceback (most recent call last): File "", line … -
The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead
i have this code for verify payment , when user buy some course he will redirect to other page called mycourse but when i try to buy course it show error The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead. View.py : @csrf_exempt def verifypayment(request): if request.method == 'POST': data = request.POST context = {} try: client.utility.verify_payment_signature(data) razorpay_order_id = data['razorpay_order_id'] razorpay_payment_id = data['razorpay_payment_id'] payment = Payment.objects.get(order_id = razorpay_order_id) payment.payment_id = razorpay_payment_id payment.status = True userCourse = UserCourse(user = payment.user , course = payment.course) userCourse.save() payment.user_course = userCourse payment.save() return redirect('mycourse') except: return HttpResponse("Invalid Payment Details") -
How can i combine sub_category in same list only if parent title is same?
Any idea to check that list is already created or not? Or any filter method that i can get mentioned response? i am getting this type of response. [ { "Politics": [ "Government" ] }, { "Politics": [ "Court" ] }, { "State News": [ "State 1" ] }, { "State News": [ "State 2" ] } ] here is my views.py class getCategoriesAPIView(APIView): def get(self, request): queryset = SubCategory.objects.filter() toList = [] for items in queryset: toDict = {} toDict1 = {} toDict[items.category.title] = [] toDict1['sub_category'] = items.sub_title toDict[items.category.title].append(toDict1['sub_category']) toList.append(toDict) return JsonResponse(toList, safe=False) I need response like this: [ { "Politics": [ "Government", "Court" ] } { "State News": [ "State 1" "State 2" ] } ] -
Form not being saved in Database Django
I have created a form for a Post. The form loads and when I enter all the value and try to submit the form, it gets refreshed but the database is not updated. Here is my Post Model: class Post(models.Model): no_people = models.IntegerField() no_days = models.IntegerField() tour_date = models.CharField(max_length=200, blank=True) Gender_types = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Others'), ) Gender_prefer = models.CharField(max_length=1, choices=Gender_types) location = models.CharField(max_length=200, blank=True) pic_location = models.ImageField(blank=True, upload_to="posts/") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) detail = models.TextField() liked = models.ManyToManyField(Yatru, blank=True, related_name= 'likes') author = models.ForeignKey(Yatru, on_delete=models.CASCADE, related_name = 'posts',null=True) def __str__(self): return str(self.location) def no_likes(self): return self.liked.all().count() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): self.location = self.location.upper() return super(Post, self).save(*args, **kwargs) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) Here is the form: from django import forms from .models import Post class PostModelForm(forms.ModelForm): class Meta: model = Post fields = ('no_people','no_days','tour_date', 'Gender_prefer','location','detail') Here is the views: def post_add(request): user = request.user profile = Yatru.objects.get(user=user) form = PostModelForm(request.POST or None, request.FILES or None, instance=profile) if request.method == 'POST': if form.is_valid(): newpost=form.save(commit=False) newpost.user=request.user newpost.save() return render(request, 'posts/my_post.html',{'form': form}) This is the HTML file: <form method="POST"> {% csrf_token %} {{form.as_p}} <button type='submit'>Submit </button> </form> -
Запуск Django приложения на Heroku
Не получается выложить Django приложение на Heroku. Пользовался этими инструкциями https://python-scripts.com/django-simple-site-heroku но приложение не отображается. Кто может скать что в них не так? -
Django ProgrammingError at /profile/edit/1/ earlier I used sqlite3 database it was fine but when I changed to postgresql it caused this problem
enter image description here ProgrammingError at /profile/edit/1/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Internal Server Error: /profile/edit/1/ Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\jobapp\permission.py", line 21, in wrap return function(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\account\views.py", line 208, in employee_edit_profile user = get_object_or_404(User, id=id) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, … -
How to configure Django (on docker) to send mail through Postfix
I setup the postfix on server and it works fine : echo "test email" | sendmail mymail@gmail.com my Django project is on Docker and I can not use localhost in EMAIL_HOST. settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'api.mydomain.com' EMAIL_PORT = 25 EMAIL_HOST_USER = None EMAIL_HOST_PASSWORD = None EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'Info <info@mydomain.com>' function : from django.core.mail import send_mail send_mail('subject', 'message', 'info@mydomain.com', [mymail@gmail.com], fail_silently=False) and I get the following error : {'mymail@gmail.com': (454, b'4.7.1 mymail@gmail.com: Relay access denied')} and when I fill in the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD values, I get the following error : SMTP AUTH extension not supported by server. I made many changes to /etc/postfix/main.cf but none of them worked! main.cf : myhostname = mydomain.com mydestination = $myhostname, mydomain.com, localhost.com, , localhost , api.mydomain.com relayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 <SERVER IP>/32 <DOCKER NETWORK> Anyone any idea how to solve this problem? -
Getting an array in a django function
I send data from JS via JSON var pricesum = sumprice; var date = expirationdates; var price = prices; $.ajax({ type: "POST", url: "print", data: { 'pricesum': pricesum, 'date': date,'price': price, }, They have the following form expirationdate = request.POST.get('date', False); price =request.POST.get('price', False); print(expirationdate) print(price) Next, I get them in the django function, but I always get false. How do I get them correctly so that they are all in the array? -
'DIRS': [os.path.join(BASE_DIR,'templates')], NameError: name 'os' is not definedrmissions
Hmmm… can't reach this page127.0.0.1 took too long to respond Try: Checking the connection Checking the proxy and the firewall Running Windows Network Diagnostics ERR_CONNECTION_TIMED_OUTenter code here -
What is the correct way of creating APIs which contain multiple tasks?
Any help would be appreciated. I am creating a small application which has facebook type feature of sending friend requests and adding friends. So I wanted to know the correct way to implement this keeping REST architecture in mind. When a person accepts a friend request, I need to perform 2 functions, firstly add that person as a friend in my model Friend and delete the friend request from the model FriendRequest. So as of now I have created 2 APIs, one to add Friend through a POST request and another to delete Friend Request through a DELETE request. Issue with this method is that, in the frontend we will have to make 2 synchronous requests and if the network is lost between these requests it will obviously create problems. Thank you in advance. -
How to resolve this trouble : parallel_offset does no longer work
Could you please help me figuring out this issue. Before when I was using jupyter note book, I didn't have any problem. Now I am working on Django project and my parallel_offset function does no longer work. When I compare the old geometry with new _offset geometry, I see the line geometry was offseted. But I the graph output, I don't see the double road. col_list = ['geometry', 'oneway'] edges_gdf['_offset_geometry_'] = edges_gdf[col_list].apply(lambda x: x['geometry'].parallel_offset(distance_offset, link_side) if not x['oneway'] else x['geometry'].parallel_offset(0, link_side), axis=1) edges_gdf.drop('geometry', axis=1, inplace=True) edges_gdf.set_geometry('_offset_geometry_', inplace=True) edges_gdf.to_crs(crs=CRS84, inplace=True) # Converting back in 4326 before ploting Full view: def retrieve_data_from_postgres(network_id, Simple, set_initial_crs=4326, zone_radius=15, intersection_radius_percentage=0.8, distance_offset_percentage=0.8, line_color='orange', link_side='left', ): initial_crs = "EPSG:{}".format(set_initial_crs) initial_crs = CRS(initial_crs) CRS84 = "EPSG:4326" default_crs = "EPSG:3857" edges = Edge.objects.filter(network_id=network_id) edges = serialize('geojson', edges, fields=('id', 'param1', 'param2', 'param3', 'speed', 'length', 'lanes','geometry', 'name', 'source', 'target','network', 'road_type')) edges = json.loads(edges) edges_gdf = gpd.GeoDataFrame.from_features(edges['features']) # Convert a geojson as geodataframe nodes = Node.objects.filter(network_id=network_id).values() nodes_df = pd.DataFrame(nodes) nodes_df['location'] = nodes_df['location'].apply(geometry.Point) nodes_gdf = gpd.GeoDataFrame(nodes_df, geometry=nodes_df['location']) edges_gdf.set_crs(initial_crs, inplace=True) nodes_gdf.set_crs(initial_crs, inplace=True) nodes_gdf.to_crs(CRS84, inplace=True) edges_gdf = edges_gdf[edges_gdf.geometry.length > 0] zone_radius = zone_radius intersection_radius = intersection_radius_percentage * zone_radius distance_offset = distance_offset_percentage * zone_radius tiles_layer = 'OpenStreetMap' edges_gdf["oneway"] = edges_gdf.apply(lambda x: not edges_gdf[ (edges_gdf["source"] == x["target"]) & … -
Implementing the charity and Benefactor model in Django
am new to Django and I getting some difficulties in implementing this model in Django: here's my fiels : . ├── accounts │ ├── admin.py │ ├── apps.py │ ├── models.py │ └── views.py ├── charities │ ├── admin.py │ ├── apps.py │ ├── models.py charities/model.py: from django.db import models from accounts.models import User class Benefactor(models.Model): ex_status = [ (0,'beginner'), (1,'middle'), (2,'expert'), ] #id = models.BigAutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) exprience = models.SmallIntegerField(choices = ex_status, default = 0) free_time_per_week = models.PositiveSmallIntegerField(default = 0) class Charity(models.Model): #id = models.BigAutoField(primary_key = True) user = models.OneToOneField(User,on_delete = models.CASCADE) name = models.CharField(max_length = 50) reg_number = models.CharField(max_length = 10) class Task(models.Model): state_status = [ ("P" , "pending"), ("W", "Waiting"), ("A", "Assigned"), ("D", "Done") ] gender_limit_status = [ ("M","Male"), ("F","Female"), ] id = models.BigAutoField(primary_key = True) assigned_bonefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE) charity = models.ForeignKey(Charity, on_delete=models.CASCADE) age_limit_from = models.IntegerField(blank=True,null=True,) age_limit_to = models.IntegerField(blank=True,null=True,) date = models.DateField(blank=True,null=True,) description = models.TextField(blank=True,null=True,) gender_limit = models.CharField(choices = gender_limit_status,max_length = 1) state = models.CharField(max_length = 1,choices = state_status, default= 'P') title = models.CharField(max_length = 100) accounts/models.py : from django.db import models from django.contrib.auth.models import AbstractUser import datetime class User(AbstractUser): gender_status = [ ('M','Male'), ('F','Female'), ] id = models.BigAutoField(primary_key=True) address … -
Get Celery task to sleep and then restart at the back of the worker queue
If I had a celery task that was the following - @app.task def greetings(firstname, lastname): print("hello" + firstname + lastname) If I then wanted that task to sleep for 5 minutes before restarting would I use celerybeat? I want the restarted task to just go to the back of the workers queue also. -
Page not found after submitting form django
I have a comment model in my forum and when I try to submit it it says "Page not found - /POST?csrfmiddlewaretoken". views.py: @login_required def comment(request, pk): if request.method == 'POST': form = CommentCreationForm(data=request.POST) if form.is_valid(): comment.post = get_object_or_404(Post, pk=pk) comment.writer = request.user comment = form.save() messages.info(request, 'comment published') return JsonResponse({'message': 'Thank you for your comment'}, safe=False) else: form = CommentCreationForm() html file: <form action="POST"> {% csrf_token %} {{ form.text.errors }} <label for="{{ form.text.id_for_label }}">comment:</label> {{ form.text }} <button id="comment" type="submit">comment</button> </form> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} By the way, can you help me make it in ajax? -
How can I have two POST requests in the same view without getting MultiValueDictKeyError?
my view originally worked as a search engine (in which the POST request returns the search results) but I added a function so that the user can 'favorite' any item that's returned so that it'll be added to their profile. However, since I have two different post requests, the second request (which is the one to favorite the item) returns MultiValueDictKeyError since it's still referencing the first post request. How can I make my view take both different requests? This is the view code (def anime is the one not working): def search(request): animes = [] if request.method == 'POST': animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results = r.json() results = results['results'] if len(results): for result in results: animes_data = { 'Id' : result["mal_id"], 'Title' : result["title"], 'Episodes' : result["episodes"], 'Image' : result["image_url"] } animes.append(animes_data) else: message = print("No results found") for item in animes: print(item) context = { 'animes' : animes } return render(request,'search.html', context) def anime(request): if request.method == "POST": anime_id = request.POST.get("anime_id") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('/search') animes = Anime.objects.all() return render(request = request, template_name="search.html") This is the … -
Prevent Inline Showing When Adding a New Object
I have two one-to-one related models in Django. Simplified version as follows: class User(models.Model): name = models.CharField(max_length=40) class Profile(models.Model): age = models.IntegerField() user = models.OneToOneField(User, on_delete=models.CASCADE) I have used signals to automatically create a profile automatically when a new user is created. I have also created a ProfileInline and included it in my UserAdmin as follows: class ProfileInline(admin.TabularInline): model = Profile can_delete = False class UserAdmin(admin.ModelAdmin): list_display = ('name',) inlines = [ProfileInline,] The problem I am facing is that when a new User is being created in the admin module, and the person creating the new user also populates the field for the inline on the same page, an error is generated while saving because both the signals module and the admin are trying to create a new Profile. Is there any way to prevent the ProfileInline from showing in the UserAdmin when adding a new User? Thanks. -
can't create super user with a CostumUserManager in django 3.2.2
i'm trying to create a superuser but no matter what changes i make i still get: Blockquote File "D:\python\gambling_game\gamegambling\users\models.py", line 40, in create_superuser return self.create_user(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields) TypeError: create_user() takes 7 positional arguments but 8 were given i went through the code multiple times but couldn't spot the error enter code here from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser , PermissionsMixin , BaseUserManager from django.utils.translation import gettext_lazy as _ from datetime import datetime # Create your models here. class CostumUserManager(BaseUserManager): def create_user(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields): if not email: raise ValueError(_('Please enter an email address')) email = self.nomalize_email(email) if bith_isValid(birth_date): birth_date = birth_date else: raise ValueError(_('birth date not valid')) user = self.models(email = email, pseudo = pseudo , first_name = first_name, last_name = last_name, birth_date = birth_date, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, pseudo, first_name, last_name, birth_date, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') if other_fields.get('is_active') is not True: raise ValueError('Superuser must be assigned to is_active=True') return self.create_user(self, email, pseudo, …