Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Forbidden (CSRF cookie not set.) error from django in C#
I'm sending data to a django application using C# code: using (WebClient client = new WebClient()) { NameValueCollection postData = new NameValueCollection() { { "user_id", "12345" } }; string pagesource = Encoding.UTF8.GetString(client.UploadValues(url_ad, postData)); } But I'm getting this error: Forbidden (CSRF cookie not set.) Code to get data in django views.py: def get_user_id(request): if request.method == 'POST': user_id = request.POST.get('user_id') record = User.objects.filter(user=user_id) if not record: new_user = User(user = user_id) new_user.save() return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) I know what the error is and how to fix it in web applications, But I don't know how to solve it when sending data using C#. Also since I'm not using framework 4.5+ I can't use HttpContent which I heard is able to somehow fix this. So how can I fix it with WebClient ? -
Django cassandra engine, how to define table name
I am using https://pypi.org/project/django-cassandra-engine/ and I have defined my model, In my model I have this to name table: class Meta: db_table = "table_name" but in Cassandra table doesn't create with my custom name -
How to shard postgreSQL data using Django for a chat application?
I am using a Django based app server to run a chat application. In future a person can have more than thousands messages per user and so, my message table will blow up even after few million users. How do I shard and manage that data using Django? Is there anything that Django provides to handle these things. What if my query required multiple shard to be accessed at same time. Will Django do that for me? If Django doesn't support it, how will I handle it in future? Assuming, I have a foreign key to determine the sender of the message and a foreign key to the room(chat room) to which this message belongs to. query1 = Message.objects.filter(created_at__gt=timestamp) query2 = Message.objects.filter(id__lte=message_id).update(is_seen=True) Also, what if I need to serialize a Room object and I want the last message object of that room. How will serializer handle that? Thanks in advance!!! -
What to do if i don't want to hardcode values in my post request in djnago?
For now im just harcoding values into payload and headers while making post request and it's working fine. But now i don't want to hardcode those values into payload and make post request .. it should accept the values while making post request dynamically . does anyone have any idea . Thank you. @csrf_exempt @api_view(['POST']) def addtocart(request): payload = dict(customer_key='c_5c88d447dde56', hub_id=4, product_id='pr_572359462392e', quantity=1) headers = {"content-type":"application/json", "token": "tk_ju9fdm8e", "source":"android"} response = requests.post('http://api/cart/update/v2', data=json.dumps(payload), headers=headers) return HttpResponse(response) -
Concurrent Rendering in React Applications
I am building a dashboard which will display a series of line graphs, the graphing library used is Recharts, the data for the graphs comes from a Django back-end. The question is when I select a date range for fetching data for more than 30 days, the API returns the data successfully, but the series of graphs to be displayed on the dashboard (which is about 50 Graphs) takes a lot of time to render, the browser freezes in that process, is there a means of rendering these graphs concurrently in a non-blocking asynchronous technique in React? Secondly, is there a much efficient technique for rendering such huge amount of graphs having Django/Python in the back-end? -
Error while Connecting my-sql client with Django
I have got an error: “Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/0_/7l07f2kd7gs4679qlmr5nvym0000gn/T/pip-install-j0dudxeq/mysqlclient/” While installing mysqlclient with python 3 -
Which is a better approach to limit the time for which a function can execute?
I have built a tool using django to automate script execution. The tool is working fine but sometimes the scripts take too long to execute. I want to limit the time for which my tool can execute each script. I have found 2 approaches and implemented them but I am not sure which is the right one to use. 1.) Using the signal module 2.) Using multiprocessing Here is the sample code for both approaches 1.) Using the signal module import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, frame): raise TimeoutException("Timed out!") signal.signal(signal.SIGALRM, signal_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) try: with time_limit(10): long_function_call() except TimeoutException as e: print("Timed out!") 2.) Using multiprocessing from multiprocessing import Process from time import sleep def f(time): sleep(time) def run_with_limited_time(func, args, kwargs, time): p = Process(target=func, args=args, kwargs=kwargs) p.start() p.join(time) if p.is_alive(): p.terminate() return False return True if __name__ == '__main__': print run_with_limited_time(f, (1.5, ), {}, 2.5) # True print run_with_limited_time(f, (3.5, ), {}, 2.5) # False Want to know which is the better approach and why? -
How to merge two pisaDocument file
Using xhtml2pdf how can i append two 'pisaContext' object python. My requirement is to render two pages separately into 2 different pdf, and then merge return the merged pdf. -
How to format an excel's cell with django-import-export?
How can I format an Excel cell as a decimal number with four decimals? I am using django-import-export library to export excel. Thank you for your attention! Django 1.11.15 django-import-export==1.0.1 -
How to solve this error while installing django seo
i run this command on my pycharm terminal pip install django seo But its not working. Error: Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "C:\Users\Lenovo\AppData\Local\Temp\pip-install-3t8pgkxd\Seo\setup.py", line 18, in long_description=open('README.md').read(), FileNotFoundError: [Errno 2] No such file or directory: 'README.md' -
What is the proper approach to get data with one to many relationship
I am following a tutorial in Django where I found a certain for loop to get the entities in a model which is actually filtering the data. The below is the model (models.py) class Brand(models.Model): name = models.CharField(max_length=30) origin = models.CharField(max_length=50) class Model(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=30) class Review(models.Model): article = models.CharField(max_length=2000) label_model = models.ManyToManyField(Model) The below is the views.py from django.views import generic from .models import Brand from .models import Model from .models import Review class BrandListView(generic.ListView): template_name = 'phonereview/brands.html' context_object_name = 'all_phone_brands' def get_queryset(self): return Brand.objects.all() class ModelDetailView(generic.DetailView): model = Brand template_name = 'phonereview/models.html' class ReviewDetailView(generic.DetailView): model = Model template_name = 'phonereview/reviews.html' The below is the template 1) Listing brands (tempates/appname/brands.html) <ul> {% for brand in all_phone_brands %} <li> <a href = "{% url 'phonereview:models' brand.slug %}"> {{ brand.name }} </a> </li> {% endfor %} </ul> Here the all_phone_brands is coming from views.py. 2) Template for listing phone models <ul> {% for model_item in brand.model_set.all %} <li> <a href="{% url 'phonereview:reviews' model_item.slug %}"> {{ model_item.model_name }} </a> </li> {% endfor %} </ul> Even though the code works, I am not sure putting brand.model_set.all is the proper approach. I guess, there must be a better approach … -
Django orm to select field that has first three word distinct
I want top perform django orm that selects first 3 word of letter as diustinct selection I have model as below: class Phone(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=2050,null=True,blank=True) slug = models.SlugField(max_length=2050,null=True,blank=True) ** sample values of name are ** Xiomi redmi note red ...., Xiomi redmi note blue ...., samsung galaxy s10 red ..., samsung galaxy s10 blue ..., i want to extract the distinct queryset that has first three word as common For example: Xiomi redmi note, samsung galaxy s10 as a resilt query set -
Django Server Error (500) when DEBUG=False
settings.py ALLOWED_HOSTS = ["localhost", "192.168.0.7", "127.0.0.1"] MIDDLEWARE = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static_collection') STATIC_URL = '/static/' MEDIA_URL = '/data/' MEDIA_ROOT = os.path.join(BASE_DIR, 'data') EMAIL_BACKEND = env.str('EMAIL_BACKEND') EMAIL_HOST = env.str('EMAIL_HOST') EMAIL_PORT = env.int('EMAIL_PORT') EMAIL_HOST_USER = env.str('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env.str('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS') urls.py urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'generic.views.invalid_request' When I set DEBUG = True then server can run. But when I set DEBUG = False then server give me error 500. What is the solution??? -
Django is.authenticated always returning true
I am using Django authentication system and want to create logout button once the user has logged in to the website. But the user.is_authenticated is not working and logout button gets displayed even on the login page. Can someone please help me understand what am I missing? below is my code for views.py and template - def user_login(request): form=LoginForm() if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: print("came here") if user.is_active: login(request,user) return redirect('valid') else: return HttpResponse('username or password not correct') else: return render(request, 'restui/login.html',{'form':form}) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>REST API Framework</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-dark bg-primary"> <a href="#" class="navbar-brand" style="font-family: 'Lato', sans-serif;">REST API Testing Framework</a> {% if request.user.is_authenticated %} <button class="btn btn-light" type="submit">Logout</button> {% endif %} </nav> <br> <br> <br> <nav class="navbar fixed-bottom"> <div class="container"> <div class="navbar-header"> <a href="#" class="navbar-brand"></a> </div> <ul class="nav navbar-nav"> <li> <a href="#"><img src="infosys-logo.jpg" style="max-height:100px; max-width:90%; right:1px; "></a> </li> </ul> </div> </nav> {% block body_block %} <div class="container"> <form method="post"> <div class="form-group"> {{ form.username.label }} {{ form.username }} </div> <div class="form-group"> {{ form.password.label }} {{ form.password }} </div> <br> {% csrf_token %} <button type="submit" class="btn btn-primary">Submit</button> <small id="emailHelp" … -
How to display objects related to a specific foreign key object?
I am trying to make a gaming app in which people create their teams and then create players and associate players to a specific team. The problem is how can I only display the players in a team that is connected with it. Advance Thanks for your help. Here,s my models.py class Team(models.Model): name = models.CharField(max_length =240) captain = models.CharField(max_length = 240) v_captain = models.CharField(max_length = 240) def get_absolute_url(self): return reverse('games_app:detail',kwargs = {'pk':self.pk}) def __str__(self): return self.name class Players(models.Model): over = models.CharField(max_length = 10) batting = models.CharField(max_length = 100) player_team = models.ForeignKey(Team,related_name = "teams") Here,s the views.py class List_Players(generic.ListView): model = models.Players template_name = 'games_app/players_list.html' Here,s the HTML <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for i in object_list.player_team %} <h1>Players :<strong>{{i.player_name}}</strong> {% endfor %} </body> </html> -
How to link an authenticated user to a formModel
I have a small project that I am working on and I have a Model that deals with delivery Address. I want to be able to set / update the user details on this form but i really not sure how to do that. I tried to set a user on my Profile model as a OneoToOneField with User but that doesnt seem to work andf I get an error: Exception Value: Cannot assign "<User: bill>": "Profile.user" must be a "User" instance. Im not certain how to proceed. My model is: from django.db import models from django.contrib.auth.models import User from django.contrib import auth from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings # Create your models here. class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) houseNumber = models.CharField(max_length=150, default='') street = models.CharField(max_length=150, default='') suberb = models.CharField(max_length=150, default='') city = models.CharField(max_length=150, default='') phone = models.CharField(max_length=150, default='') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() My view is: class ProfileView(LoginRequiredMixin,FormView): template_name = 'profile_form.html' success = 'profile.html' form_class = ProfileForm # def get_context_data(self, **kwargs): # context = super(ProfileView, self).get_context_data(**kwargs) # context['now'] = timezone.now() # return context … -
Django REST Framework: rendering form elements in list response
How can Django REST Framework be used to render a list of model instances with specific fields editable by the user? I'm a few months into Django, and only a couple days into DRF. I've tried several different approaches, but just can't seem to wrap my head around it. Prior to using DRF, my workflow would have been to set up a view (and associated URL) that: queried my model, picked my custom form from forms.py (exposing only the fields I needed), put the two together into a dictionary, and sent it to a template. In the template, I could then loop through my model instances and set up my editable fields, piping them through django crispy forms, as required. I could then call this template through an AJAX get request. models.py class Buyer(models.Model): name = models.CharField(unique=True, max_length = 20) class Item(models.Model): name = models.CharField(unique=True, max_length = 50) active = models.BooleanField(default=True) bought_by = models.ForeignKey(Buyer, null=True, blank=True, to_field="name",) views.py class ItemViewSet(viewsets.ModelViewSet): queryset = models.Item.objects.select_related("bought_by") serializer_class= serializers.ItemSerializer filterset_fields = ("bought_by") serializers.py class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Item fields = "__all__" extra_kwargs = {"url": {"view_name: "myapp:item-detail"}} urls.py router = routers.DefaultRouter() router.register(r"items", views.ItemViewSet) template.html {% load static %} {% load rest_framework %} <table … -
Smartest way to test a view if form.is_valid?
Searching for a good way to test a part of a view that belongs to valid form: Views.py: def calendar_request(request): form = create_event(request.POST) if form.is_valid(): date = request.POST['date'] time = request.POST['time'] return HttpResponseRedirect(request.path) else: print('Form not valid') So I checked if the form is valid in my tests.py: def test_form_valid_request(self): date = '2019-04-16' time = '14:00' form_data = {'date':date, 'time':time,} form = create_event(data=form_data) self.assertTrue(form.is_valid) This worked pretty good. So I continued by adding these lines to my test function: response = client.get(reverse('test_form'), form_data) self.assertEqual(response.status_code, 200) What confuses me is that AssertTrue(form.is_valid) works while testing, but in my console I get always the print ('Form not valid'). How can I test the part in my view if the form.is_valid? -
Enabling deepLinking in Django REST Swagger
I'm trying to add deepLinking feature to the Swagger output generated by get_schema_view: schema_view = get_schema_view(title='MyAPITitle', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) I've tried to extend the rest_framework_swagger/index.html template, adding script assigning deepLinking: true in SwaggerUI({ ... }). Tried adding swagger-config.yaml with this to the project root None of these works. What's the proper way to add this feature? -
Docker caannot detect the project
I am new to coding and my employer told me to learn docker. I tried this guide https://realpython.com/django-development-with-docker-compose-and-machine/. But when i get to step docker-compose run web /usr/local/bin/python manage.py migrate it gives me next error: cannot import name 'views' from 'docker_django' What can i do to avoid it? I tried moving views.py from there to here but it didn't help -
Djagno Forms - How to link a check box to a booleanfield
python 3.6 django 1.11 (haven't updated it yet) I'm wanting to add a True/False checkbox to a form. I see how to do it on them html page and on the form itself, but the two aren't linking. Whenever I check the True box, the field that represents the checkbox is false. HTML <div class='form-group'> <input type="checkbox" name="donation-repeat" id="donation-repeat_id"> <label for="donation-repeat_id">Repeat my donation (yearly)</label><br> </div> Forms.py class DonationCreateForm(forms.ModelForm): recurring_donation = forms.BooleanField(required = False,label = 'donation-repeat_id') class Meta: model = Donation fields = ['total','recurring_donation'] def clean_recurring_donation(self): print('we are cleaning now') print(self.cleaned_data) recurring_donation = self.cleaned_data['recurring_donation'] print('recurring_donation1 ', recurring_donation) return recurring_donation However, I am always getting this output recurring_donation1 False Regardless of whether or not I have checked the box. What am I doing wrong? -
Get Object if Many to Many field contains a certain Foreign Key
I am trying to implement a friend system in django and am having trouble verifying when two users are already friends (in order to prevent double requesting) The system works by having each user separately map to the same friend object to signify friendship. Consider the following code models.py class Friendship(models.Model): # some other stuff ... class FriendshipMapping(models.Model): user_id = models.ForeignKey('User',related_name="friendship_mappings",on_delete=models.CASCADE) friendship_id = models.ForeignKey('Friendship',related_name="mapped_by",on_delete=models.CASCADE) # some other stuff ... class User(AbstractUser): friendships = models.ManyToManyField( 'Friendship', through='FriendshipMapping', symmetrical=True, through_fields=('user_id','friendship_id'), related_name='joined_users', ) # some other stuff ... Now say I have 2 User objects and I would like to figure out if a friendship object is pointed to by both of them without getting one of their full friendship set and iterating through it. I have tried the following existing_friendship = user1.friendships.get(joined_users__in=user2) but it returns empty even when I know that there is a friendship that they both point to. There is very little documentation on this type of lookup and I'm not sure if my syntax is valid or what __in is really doing in the first place. Is something like this even possible in django? Would love some help! -
Unable to progress past signup due to media_root permission error
I'm attempting to signup for an account on my django site, but I'm running into the following error: Thumbnail generation failed Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\image_warmer.py", line 117, in _prewarm_versatileimagefield url = get_url_from_image_key(versatileimagefieldfile, size_key) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\utils.py", line 216, in get_url_from_image_key img_url = img_url[size_key].url File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\sizedimage.py", line 149, in __getitem__ height=height File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\sizedimage.py", line 201, in create_resized_image path_to_image File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\base.py", line 140, in retrieve_image image = self.storage.open(path_to_image, 'rb') File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\files\storage.py", line 33, in open return self._open(name, mode) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\files\storage.py", line 218, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: 'C:\\Users\\jason\\Desktop\\staticfiles\\media_root' I just reinstalled windows 10 while keeping personal files. This error never happened before reinstalling windows 10. I've looked at the folder permissions and can't see anything amiss. Any thoughts on what I can check? Thanks! -
How to override django signup view class
I want to override django all-auth signup view to input an extra field value. In this case, User model has a foreign field which is combined to Company model. from allauth.account.views import SignupView as AllAuthSignupView from .models import Company class SignupView(AllAuthSignupView): def save(self): user = super(SignupView, self).save() a_company = get_object_or_404(Company, name='A') user.company = a_company return user However, This only saves username, password, email. The company field is NULL. I don't want an answer that recommends change the default value in Company model. That's not the way I try to solve this problem. -
How do I write the problematic code to avoid getting the error?
I get the error after typing the code in the models.py field after determining the application name in urls.py No problem before defining the application name. Django==2.2 Python==3.x urls.py from django.urls import path, re_path from .views import * AppName = 'Post' urlpatterns = [ re_path(r'^Index/$', PostIndex, name='Index'), re_path(r'^(?P<id>\d+)/$', PostDetail, name='Detail'), re_path(r'^Create/$', PostCreate, name='Create'), re_path(r'^Update/$', PostUpdate, name='Update'), re_path(r'^Delete/$', PostDelete, name='Delete'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): Title = models.CharField(max_length=120) Content = models.TextField() PublishingDate = models.DateTimeField() def __str__(self): return self.Title def get_absolute_url(self): return reverse('Post:Detail', kwargs={'id':self.id}) Index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for Post in Posts %} {{ Post.id }}<br> <a href="{{ Post.get_absolute_url }}">{{ Post.Title }}</a><br> {{ Post.Content }}<br> {{ Post.PublishingDate }}<br> {% endfor %} </body> </html> I am not receiving an error without defining the application name in the models.py field. There is an error in code editing in the models.py field. def get_absolute_url(self): seamless code => return reverse('Detail', kwargs={'id':self.id}) problematic code => return reverse('Post:Detail', kwargs={'id':self.id}) How do I write the problematic code to avoid getting the error?