Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django is not persisting session in cookies unless I concatenate a list
I am trying to build a session in django like so but the following does not lead to an updated session def index(request): if not request.user.is_authenticated: return render(request, "login.html", {"message": None}) if 'foo' not in request.session: request.session["foo"] = {} if request.method == 'POST': form = NewLineItemForm(request.POST) if form.is_valid(): item = Item.objects.create(name=name) request.session["foo"][item.id] = item.name context = { "foo": request.session['foo'], "form": NewLineItemForm() } return render(request, "index.html", context) However, when I add the following to another key on the session does the entire thing, including the original key (foo) update: def index(request): if not request.user.is_authenticated: return render(request, "login.html", {"message": None}) if 'foo' not in request.session: request.session["foo"] = {} if 'task' not in request.session: request.session['task'] = [] if request.method == 'POST': form = NewLineItemForm(request.POST) if form.is_valid(): item = Item.objects.create(name=name) request.session["foo"][item.id] = item.name request.session["task"] += ['baz'] context = { "foo": request.session['foo'], "form": NewLineItemForm() } return render(request, "index.html", context) I was wondering how I can keep what's intended in the first block without having to rely on the changes in the second block. Thank you. -
How to do infinite task in Django?
I tried to find this question and found that I need Celery django-background-task What I need to do: After an certain action is done(i.e. button is pressed) This button will start a view that in the end of it launches the other view This other view will be infinite times done every second for 30days from the moment when button was pressed, even if the user is offline this task is making on background and it's updating some information in the database. Views.py def starts_code() if "btn" in request.POST: #some code is making and here is launching other view return HttpResponse() The main things is that for every user is his infinitive task, and in database is this model: user_id, when infinite task starts, and that ends after 30days. I don't ask how to do it, but if it's possible some tips and how to do for every user his infinite task -
How to load a related Django Primary Key Object to render it on html in a loop
I have almost the same problem like this post in stackoverflowenter link description here. I did it like the example... it doesn't work. I have many Posts and some of them has Attachments. Each Post belongs to a Contact. class Post(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE, verbose_name='Owner') content = models.TextField(verbose_name='Text') class Attachment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_attachments") file = models.FileField(upload_to=upload_location) filename = models.CharField(verbose_name='Filename', max_length=50, default='') views.py posts = contact.post_set.all().prefetch_related('post_attachments').order_by('-created_at') context = {'contact': contact, 'posts': posts,} return render(request, 'contact_feed.html', context) contact_feed.html {% for post in posts %} <div class="col">{{ post.content|safe }}</div> {% for attachment in post.post_attachments.all %} <div class="col">Dateianhänge {{ attachment.filename }}</div> {% endfor %} {% endfor %} This doesn't work. Where is the problem? Thanks! -
Django Firebase Phone Number Auth
i have already django project that completey woks fine with costum user model phone and password for register and sign up, here i need to add firebase phone number authentication to send sms to user befor register to my site prettier any help here . my custom user model ''' class MyUser(AbstractBaseUser): email = models.EmailField(blank=True,null=True, verbose_name='Email Address',max_length=255 ) name = models.CharField(max_length=100,verbose_name= 'Username', ) last_name = models.CharField(blank=True,max_length=100,verbose_name= 'Family Name') mobile = models.IntegerField(unique=True,verbose_name= 'Mobile Number') governorate = models.CharField(blank=True,null=True,verbose_name='Governorate',max_length=255) image =models.ImageField(blank=True,upload_to='profile_pics', default='profile_pics/avatar.png') Is_Banned = models.BooleanField(default=False) notification =models.BooleanField(default=False,verbose_name= 'Enable Notification') language_choices =( ("Arabic", "Arabic"), ("English", "English"), ("Kurdish", "Kurdish"), ) language = models.CharField( choices = language_choices,blank=True, default = 'Arabic',max_length=50,verbose_name= 'Language') is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = ['name','email'] def __str__(self): return self.name class Meta: verbose_name_plural='Users' def Adressess(self): return 'adressess' def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin @property def first_name(self): return self.name '''i upload mysite here -
populate data in amchart django
models.py: class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) order_quantity = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) class Product(models.Model): name = models.CharField(max_length=100, choices=PRODUCTS, null = True) rate = models.PositiveIntegerField(null = True) Views.py: def index(request): orders = Order.objects.all() context = { 'orders': orders, } return render(request,'index.html', context) Here I have multiple orders for samsung, apple etc. There should be only one data for samsung, apple and so on. How can I aggregate order_quantity for each product and send data as the format required for the data? I need the following data format to show data in amchart bar diagram. How can I achieve it? Format required for graph var data = [ { name: "Samsung", value: 35654, }, { name: "Apple", value: 65456, }, { name: "Xiomi", value: 45724, }, ]; -
AttributeError at /callback/ module 'zeep.client' has no attribute 'service'
when I want to use the zeep package in django for the payment gateway, I face an error. error image, code image callback function in views.py in shop app: # Callback function def callback(request): if request.GET.get('Status') == 'NOK': authority = request.GET.get('authority') invoice = get_object_or_404(models.Invoice, authority=authority) amount = 0 order = invoice.order order_items = models.OrderItem.objects.filter(order=order) for item in order_items: amount += item.product_cost result = client.service.PaymentVerification(MERCHANT, authority, amount) if result.Status == 100: return render(request, 'callback.html', {'invoice': invoice}) else: return HttpResponse('error ' + str(result.Status)) else: return HttpResponse('error ') -
How to use csrf token in javascript with django api
I wish to post data from javascript to an api implemented in django. But I cannot get beyond the csrf token settings.py ... CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8888' ] ... MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... views.py class SaveArchive(View): ... @requires_csrf_token def post(self, request, params): ... *api.js ... async function sendDataToAPI(url, post_data) { let endpoint = `${process.env.API_DOMAIN}${url}/`; var getToken= new XMLHttpRequest(); getToken.open("POST", endpoint, true); getToken.setRequestHeader('Content-Type', 'application/json'); getToken.send(JSON.stringify(post_data)); return; ... I get the error on the django server Forbidden (CSRF cookie not set.): /api/save-archive/{...}/ What needs changing? -
Two ViewSet in one url
I'm trying to build urlpatterns using two viewset. Let's say I have: class ArticleViewSet(ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer class CommentViewSet(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = [IsAuthenticated] and I would like to create url like this: /article/{article_id}/comments To simply add a lot of comments to selected article and e.g. to be able also delete comment by: /article/{article_id}/comments/{comment_id) How my urls.py should look? -
Django, how to create a path: <model_id>/<model_id>/template
The background to this question, is because I am trying to a find a way to build a 2 sided interface with 2 different user types. Users type 1 will be able to define certain actions to be performed by Users type 2 Users type 2 will have access to the tasks provided by user type 1.However, all users type 2 will not have access to all the tasks. User Type 2 A might have different actions than User Type 2 B. By setting up a path <model_id>/<model_id>/template, I thought it would be a good way to provide clarity in the url path and also filter access to data. Taking the example of a Model called Project, when looking to link to a single pk_id, I normally do something like this: #views.py def show_project(request, project_id): projects = Project.objects.get(pk=project_id) return render(request, 'main/show_project.html',{'projects':projects}) #url.py path('show_project/<project_id>',views.show_project,name="show-project"), #template.py (referrer) <a class="btn btn-outline-secondary" href="{% url 'show-project' project.id %}">{{project}}</a> Doing this allows me to obvioulsy filter what I want to show based on the ID of the model. I thought I could do something similar by adding another layer <model_id>/<model_id>/template. To stick to the example above: <user_id>/<project_id>/template. So I came up with the following, which visibly … -
GraphQL mutation Invalid payload
I have the following mutation mutation createFoo { createFoo(data: {title: "Test"}) { foo { id title } } } When I ran I got the error AssertionError: 'errors' unexpectedly found in ['errors', 'data'] : {'errors': [{'message': 'Invalid payload', 'locations': [{'line': 3, 'column': 17}], 'path': ['createFoo']}], 'data': {'createFoo': None}} What can be? -
Get queryset of same multiple id's of a model in django
here is my models .. class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date = models.DateField(default=timezone.now, blank=True, null=True) class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank=True, null=True) trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, default=0.0) distance_to = models.FloatField(blank=True, null=True, default=0.0) time_from = models.TimeField(blank=False, null=False ,default=timezone.now) time_to = models.TimeField(blank=False, null=False ,default=timezone.now) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) doeking_km = models.FloatField(blank=True, null=True, default=0.0) And here is my views for creating logsheet def create_logsheet(request): drivers = Driver.objects.all() vehicles = Vehicle.objects.all() if request.method == "POST": vehicle_id = request.POST.get("vehicle") vehicle = Vehicle.objects.get(id=vehicle_id) date = request.POST.get("date") # logsheet data trip = request.POST.getlist("trip") time_from = request.POST.getlist("time_from") time_to = request.POST.getlist("time_to") source = request.POST.getlist("source") destination = request.POST.getlist("destination") distance_from = request.POST.getlist("distance_from") distance_to = request.POST.getlist("distance_to") driver_id = request.POST.getlist("driver") driver = Driver.objects.filter(id__in=driver_id) print(driver) #main logic if vehicle and driver and date: log = Log(vehicle=vehicle, date=date) log.save() data = zip(trip, driver, distance_from, distance_to,time_from, time_to, source, destination) for trip,driver, distance_from, distance_to, time_from, time_to, source, destination in data: if trip and driver and distance_from and distance_to and time_from and time_to and source and destination: logdetail = Logsheet( log=log, trip=trip, driver=driver, distance_from=distance_from, distance_to=distance_to, time_from=time_from, time_to=time_to, source=source, destination=destination, ) logdetail.save() return redirect("logsheet_list") Problem: When i want same driver fro multiple … -
How do I view the cookies a django Response is attempting to set?
My understanding is that when a server wants to send a client cookies, it sends them in the HTTP response in one (or multiple) Set-Cookie headers which contain the name-value pairs of a cookie in the form name=value. I am trying to view this header from a django HttpResponse object. I figured this would be available from the HttpResponse.headers attribute. However, when I print the response.headers, I don't see any Set-Cookie headers, even though I KNOW that cookies are being set on the client side (I am logging into and out of the django admin console, and I see in Google Chrome that the sessionid cookie is being set and cleared). How do I view the cookie values and the Set-Cookie headers from a django HttpResponse object? I know I can set cookies using HttpResponse.set_cookie(), but how do I view cookies that are already set? Why does it appear to be invisible? -
Django model business rules
what's the best place to make my model validation rules, example i have an entity model where a field is validated by another field assert field1 == 2*feidl2 since drf3 is not executing full_clean() method, and in my application there many logic and many places where the model is created i can't use serializer in all places ,this why validation in serializer will not works fine for my case , for the momen replicate validation works fine (in serializer and clean method) I'm looking for the best practice to do that thanks -
GraphQLTestCase self.query query() got an unexpected keyword argument 'op_name'
I have the following GraphQLTestCase def test_create_foo(self): response = self.query( """ mutation createFoo($input: MutationInput!) { createFoo(input: $input) { foo { id title } } } """, op_name="createFoo", input_data={"title": "Title Test"}, ) When I ran, I got the error: response = self.query( TypeError: query() got an unexpected keyword argument 'op_name' I am using: graphene 3.1.1 graphene-django 3.0.0 What can be? -
How to make paginator to loop over a query set
I'm using Paginator class on a page which displays each post posted by the users that the logged-in user follows. I'm having trouble showing the correct number of pages. I think the problem is at post_list = all_posts but I couldn't figure out how to solve this. all_posts is a list of query sets, do I need to loop over this list and assign the query sets to the post_list? If so, how can I do that? views.py: def following(request, username): try: all_posts = [] follow_item = Follow.objects.filter(follower = request.user) for item in follow_item: posted_by = item.following posts = AllPost.objects.filter(user = posted_by).order_by("date").reverse() all_posts.append(posts) post_list = all_posts paginator = Paginator(post_list, 10) # Show 10 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/following.html",{ "page_obj":page_obj, "follow_item": follow_item }) except: follow_item = False return render(request,"network/following.html",{ "posts": post_list }) following.html: {% extends "network/layout.html" %} {% block body %} {% if follow_item %} {% for object in page_obj %} {{ post.full_name|upper }}<br> {% for post in object %} <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> <div>{{post.content}}</div> <div id="grey">{{post.date}}</div> <div id="grey">{{post.likes}}</div> <a href="#" style="color: grey;">Comment</a> </div> {% endfor %} {% endfor %} {% else %} <div class="alert alert-warning" role="alert"> You … -
failed to resolve image name: short-name "caddy:2-alpine"
I get this error when running docker-compose up: ERROR: failed to resolve image name: short-name "caddy:2-alpine" did not resolve to an alias and no unqualified-search registries are defined in "/etc/containers/registries.conf" Here is my docker-compose.yaml file: version: "3" #networks: # web: # external: true # bridge: # driver: bridge services: # CaddyServer reverse proxy caddy: restart: always image: caddy:2-alpine ports: - "443:443" command: caddy reverse-proxy --from https://xxxxxx.com --to http://0.0.0.0:8000 #volumes: # - /local/path/to/Caddyfile:/path/inside/continer/to/Caddyfile # networks: # - web # - bridge # Django web app django: restart: always build: . ports: - "80:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=xxxxx - POSTGRES_USER=xxxx - POSTGRES_PASSWORD=xxxx volumes: - pg-data:/var/lib/postgresql/data/ volumes: pg-data: -
Get ID from submitted form in Django
I'm using React and Django and have created a form for user input. On submit I would like the ID of the post to be returned so the page can automatically load the next step using the ID in the URL. Currently the post is added to the database just fine but I'm having trouble with what happens after. views.py class CreateArticle(generics.CreateAPIView): queryset = Article.objects.all() serializer_class = CreateArticleSerializer def article(self, request, format=None): serializer = self.serializer_class(data=request.data) if(serializer.is_valid()): title = serializer.data.get('title') p = Article(title=title) p.save() return Response(ArticleSerializer(p).data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) serializer.py class CreateArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('title') models.py def generate_unique_id(): return(uuid.uuid4()) class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id(), primary_key=True) title = models.CharField(max_length=50) def __str__(self): return self.title CreateArticle.jsx try { API.post("/create/", { ...article }).then((response) => console.log(response)) } catch (err) { console.log(err) } I understand views can only return HTTP requests but I am new to Django and lost here. I've tried creating the ID in the view and returning that as a response but it does not appear within the usual Axios data. Any direction would be appreciated. Thank you -
TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection
I have the following schema: class Query(graphene.ObjectType): all_questionnaires = DjangoFilterConnectionField(QuestionnaireType) I got the error when running the tests TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection What can be? -
Do User tests for every url?
I have urls like this: in main: path('admin/', ...), path('forstaff/', include("myapp.urls"), path('forusers/', include("anotherapp.urls"), If a user is is_staff=True, they can access forstaff/, if not, they get redirected to `forusers/'. I know that I can do this: class StaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): return self.request.user.is_staff but I have to add this StaffRequiredMixin to every single class based view in myapp.urls, and also can not use it with function based classes. Is there a way I can tell Django to apply this "rule" to every single view of the app? -
How to get User Email from User model in a function Django
Hi Iam newbie to Django, I written an function to send email from any user who need to know more info about the trip. I didn't know to how to collect posted user email id from user database. need help. def PostDetailView(request, pk): context = {} context["data"] = Post.objects.get(id=pk) if request.method == "POST": name = request.POST['uName'] # phone = request.POST["phone"] email = request.POST['uEmail'] desc = request.POST['uDes'] userEmail = I need to assign email id of this trip posted user subject = 'Iam Interested in your Trip' message = f'Hi Iam {name}, Iam Interested you trip. Please share more details on {email} {desc}' email_from = email recipient_list = [userEmail, ] send_mail( subject, message, email_from, recipient_list, desc ) messages.success(request, 'Message Sent Successfully.') return render(request, 'ads/detail.html',context) return render(request, 'ads/detail.html',context) Need help to fix this. -
dependent list show in templets in Django python
I want to add dependent list in templets in Django . their are 2 table and the forgin key in 2nd table now I want to show in templets like shown as in image. -
django orm limit before annotation
I want to limit queryset befor annotation! This ins my django orm code : ProductDB.objects.prefetch_related('media').select_related("cover", 'category').filter(**variants_filter)[offset:offset + limit].annotate( variants_count=Count('product_variants')) this is query that django generates: SELECT "shop_product"."id", "shop_product"."is_deleted", "shop_product"."created_at", "shop_product"."updated_at", "shop_product"."approval_status", "shop_product"."name", "shop_product"."name_en", "shop_product"."slug", "shop_product"."source_name", "shop_product"."source_id", "shop_product"."default_variant_id", "shop_product"."phone_id", "shop_product"."phone_model_id", "shop_product"."category_id", "shop_product"."brand_id", "shop_product"."source_price", "shop_product"."cover_id", "shop_product"."attributes", "shop_product"."extra_data", COUNT(T3."id") AS "variants_count", "shop_category"."id", "shop_category"."is_deleted", "shop_category"."created_at", "shop_category"."updated_at", "shop_category"."name", "shop_category"."name_en", "shop_category"."slug", "shop_category"."order", "shop_category"."parent_id", "account_file"."id", "account_file"."is_deleted", "account_file"."created_at", "account_file"."updated_at", "account_file"."file", "account_file"."normal", "account_file"."thumbnail", "account_file"."name", "account_file"."type", "account_file"."user_id", "account_file"."source" FROM "shop_product" LEFT OUTER JOIN "shop_variant" T3 ON ("shop_product"."id" = T3."product_id") LEFT OUTER JOIN "shop_category" ON ("shop_product"."category_id" = "shop_category"."id") LEFT OUTER JOIN "account_file" ON ("shop_product"."cover_id" = "account_file"."id") WHERE "shop_product"."default_variant_id" IS NOT NULL GROUP BY "shop_product"."id", "shop_category"."id", "account_file"."id" LIMIT 5 Django puts the limit after all selects and it's very slow: If i put limit on select its very fast: Just by replacing (select * from "shop_product" limit 5) instead of FROM "shop_product" Am i doing it wrong?? How can i implement this by orm -
How to translate fields in django models
I try to translate fields in model like this: my model: class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), verbose_name=_("Period"), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', verbose_name=_('Worker'), default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type'), verbose_name=_('Work done') ) work_scope = models.FloatField(_("Work scope"), blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) I don't understand why worker and work_done fields doesn't translated. in my locale: msgid "Add record" msgstr "Додати запис" msgid "Period" msgstr "Період" msgid "Worker" msgstr "Працівник" msgid "Work done" msgstr "Виконана робота" msgid "Work scope" msgstr "Обсяг роботи" So I see that: period - translated worker - not translated work_done - not translated work_scope - translated work_notes - translated in documentation says that you can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options: class MyThing(models.Model): kind = models.ForeignKey( ThingKind, on_delete=models.CASCADE, related_name='kinds', verbose_name=_('kind'), ) Why it doesn't work right in my situation? -
Why can not this function be hooked on the `QuerySet` in django?
I want to hook some functions on Models.Manager. To implements the feature that appear to be signals. But when I use demo_1() to call the update(). It will call the QuerySet.update() The hook_func() will not be called. How to fix it? # manangers.py import functools from django.db.models import Manager def bulk_operation_decorator(func, obj, original_func): @functools.wraps(original_func) def wrapper(*args, **kwargs): res = original_func(*args, **kwargs) func(obj) return res return wrapper class BulkLinkageManager(Manager): def __init__(self, func, linkages=None, *args, **kwargs): super(BulkLinkageManager, self).__init__(*args, **kwargs) if not linkages: linkages = [] self.linkages = linkages self.__hook_func = func def __hook(self, target=None): if not target: target = self for linkage in self.linkages: original_func = getattr(target, linkage, None) if callable(original_func): setattr(target, linkage, bulk_operation_decorator( self.__hook_func, target, original_func )) def get_queryset(self): queryset = super(BulkLinkageManager, self).get_queryset() self.__hook(target=queryset) return queryset # models.py class MyModel(models.Model): objects = BulkLinkageManager(hook_func, ['update']) x = models.IntegerField() # hooks.py def hook_func(queryset): logging.info('success') # demo.py import logging import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LHSCM.settings') django.setup() from models import MyModel def demo_1(): # `hook_func()` will not be called my_models = MyModel.objects.filter(x = 1) pes.update(x=6) def demo_2(): # `hook_func()` will be called my_models = MyModel.objects.all() pes.update(x=6) def main(): for i in range(20): x = i % 4 MyModel.objects.create(x = x) if __name__ == '__main__': main() -
How can I get the user's username and use it in a SQL query?
I have a Student table and I would like to get the current logged-in user's username and compare it with all the usernames in the Student table and then return the student_id if the username is found. I've got: SELECT student_id from Student WHERE username = <something> What am I supposed to write in the place of <something> to get the logged-in user's username?