Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting data in Django sent via ajax
I have an array of objects in JS: var users = [ {name: "Amir", age: 22}, {name: "James", age: 12}, ] and suppose I have a view in Django that just create to iterate over users array: def print_users(request): for user in users: print(user.name, user.age) But I send data using Ajax in Jquery in the way down below: var parameters = { "users": users, "csrfmiddlewaretoken": CSRFToken }; $.post("http://localhost:8000/users/print", parameters).done(function(data, statusText){ console.log(data, statusText); }); The PROBLEM comes in the view, I can't fetch data in the shape that it is. I get a queryset like this when I print(request.POST): <QueryDict: {'users[0][name]': ['Amir'], 'users[0][age]': ['22'], 'users[1][name]': ['James'], 'users[1][age]': ['12'],'csrfmiddlewaretoken': ['ZpcfFKppuiBZNtHAjcnKSuyvrtC7YNiUGcd6yFvfMLQMD0LemCjfFv5tPptNgu9t']}> It just like iterates over it, I want users in shape of Array. How can I do it? What is the problem? -
social-auth-app-django and AUTH_USER_MODEL
When I built the Django /api about three years ago, it was built on a legacy database that used a users table. For this, I did not extend the default Django auth_user model, but replaced it altogether with AUTH_USER_MODEl = 'authentication.User. Now I'm trying to implement Azure AD authentication into the web app using social-auth-app-django. I'm finding when I run the migrations I get a: $ ./manage.py migrate social_django Operations to perform: Apply all migrations: social_django Running migrations: Applying social_django.0001_initial...Traceback (most recent call last): File "/Users/eox-dev/Projects/current/company/company-app/api/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "Users" does not exist Which I believe is associated with not using, nor extending, the auth_user model. Is there a way to get the library to use AUTH_USER_MODEL? -
Issues with modifying users in a multi-tenant app
I am creating a multi tenant app with isolated schema using 'django-tenant' and I am having issues with modifying the user model that comes by default with django. I tried using "django-tenant-users" but I think it's not compatible with Django 3 and Python 3.7 as I get errors and I couldn't really find a solution to them. Besides that there's nothing else special. I was trying to create a user class like that: class User(AbstractUser): pass But even with that my app couldn't migrate (I am using migrate_schemas command) Maybe there's something else that django has that will help me with modifying User class for it to be compatible with different schemas and all that. Will be really thankful for any hints. -
Django translation using non-English language as default
I've used two language in my web app; English and Russian. I've added settings as LANGUAGE_CODE = 'ru' LANGUAGES = [ ('ru', gettext('русский')), ('en', gettext('English')), ] And added 'django.middleware.locale.LocaleMiddleware', Everything is working fine. No problem with translations. But the problem is, google is indexing my website without language code, for example "mysite.com". Which is simple. When a user clicks on that link it's rendering English template instead of Russian. Then user needs to change it into Russian by using a language chooser of my website. It's happening even from incognito window. I want that user will see russian first. (btw, i'm testing it from outside of russia). I've read language preferences and I think django preferring Accept-Language HTTP header. Because there is no language code in url by google index. and there is no django_language cookie for the first time visit in this website. Is there any way so an user will redirect to russian translation first, then he can choose the language he prefer. -
Large file upload with django and nginx
File sizes of 100MB are getting uploaded but over that, I get an error saying nginx 504 gateway error. Here are the current configuration, These are present in nginx client_max_body_size 200M; proxy_connect_timeout 1200s; proxy_send_timeout 1200s; proxy_read_timeout 1200s; fastcgi_send_timeout 1200s; fastcgi_read_timeout 1200s; gunicorn.conf.py import multiprocessing import greenlet print(greenlet.__version__) bind = "0.0.0.0:8000" print("Binding on : ", bind) workers = multiprocessing.cpu_count() * 2 + 1 print("Spawned :", workers, " workers") worker_class = "gevent" print("Using ", worker_class, " worker class") timeout = 1200 I'm running my django app and nginx as separate docker containers. Here are the solutions that I've tried. Changed gunicorn timeout to 2400 Changed the following in nginx config client_max_body_size 200M; proxy_connect_timeout 1600s; proxy_send_timeout 1600s; proxy_read_timeout 1600s; fastcgi_send_timeout 1600s; fastcgi_read_timeout 1600s; I checked the networks tab and request send was at 44seconds and waiting ws at 4.02minutes and then I got the Gateway timeout 504 error. -
How to make `<p>` display: inline after linebreak filter?
I have this in my template: {{ doc.description|linebreaks }} <a href="#">Edit</a> because the string has linebreaks inside that I want to display. Problem is, I want the Edit button to be displayed inline with the string, and the linebreak filter automatically applies <p></p> to the string. How do I make this <p> display: inline? (I need to add class="d-inline" as I am using bootstrap) -
Serializer removing one to many relationship in Django
When I try to attach photos to a pet the serializer is removing the attachment, I'm getting attachment :['This field is required']. My code: models.py class Pet(models.Model): pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) name = models.CharField('Pet name', max_length=255, null=False, blank=False) class Attachment(models.Model): attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.FileField(upload_to='photos/', null=False, blank=False) upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False ) serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ('name','upload_at') class PetSerializer(serializers.ModelSerializer): attachment = AttachmentSerializer(source='attachment_set', many=True) class Meta: model = Pet fields = ('pet_id','name', 'attachment') # because this: # https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers def create(self, validated_data): attachments = validated_data.pop('attachment') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet=pet, **att) return pet views.py def create_pet(self, request): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response({'error':serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED) if on PetSerializer I do attachment = AttachmentSerializer(many=True, source='attachment_set', required=False) there is no problem with the attachment but I need the attachments. Also I have done in the models.py on the Attachment pet_id = models.ForeignKey(Pet, related_name='attachments', on_delete=models.CASCADE) and the serializers PetSerializer: class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = ('pet_id','name', 'attachments') # because this: # https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers def create(self, validated_data): attachments = validated_data.pop('attachment') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet=pet, … -
FeinCMS: type object 'ReportForm' has no attribute '_feincms_content_types'
FeinCms was working fine with my old django-1.8 But when I did upgrade it to django-2.0, I got this error. I'm just stuck here. models: class MyForm(create_base_model()): name = models.CharField(max_length=255, default='New Report', unique=True) title = models.CharField(max_length=255) # Attach content types to Report report = ReportForm() report.register_regions( ('main', 'Main content'), ) map(report.create_content_type, CONTENT_TYPES) # CONTENT_TYPES are my custom content types admin: from feincms.admin.item_editor import ItemEditor admin.site.register(MyForm, ItemEditor) -
how to run static files in pythonanywhere hosting?
I'm trying to upload my project via pythonanywhere but I always get failed to load static files I tried to download it by the static files section of web tab that exists into pythonanywhere and also I got failed you can see what I did here, I will show you all details that I did to help you to understand what could give me the help through it: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATIC_ROOT = "/home/abdelhamedabdin96/website/website/static/index" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # MAIN_DIR = os.path.dirname(os.path.dirname(__file__)) # STATICFILES_DIRS = ( # os.path.join(MAIN_DIR, 'static'), # ) and in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how to get DEFAULT_PAGINATION_CLASS in Django Rest Framework
I have the following ViewSet in Django Rest Framework: class FilterProductsViewSet(viewsets.ViewSet): permission_classes = (permissions.IsAuthenticated,) def post(self, request): pagination_class = settings.REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS'] paginator = pagination_class() queryset = self.get_queryset(request.data) page = paginator.paginate_queryset(queryset, request) page_to_return = serializers.StockSerializer(page, many=True).data return paginator.get_paginated_response(page_to_return) And I am getting the following error when sending a POST: File "/Users/hugovillalobos/Documents/Code/tcdigital/TCDigitalBackend/TCDigital/inventory/views.py", line 2176, in post paginator = pagination_class() TypeError: 'str' object is not callable The line that rises the exception is the one: pagination_class = settings.REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS']. How can I get the default pagination class from settings? -
Show all products from category parent
im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that. Here is my models: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True) title = models.CharField(max_length= 200, null = True) slug = models.SlugField(max_length=200, null = True) ordering = models.IntegerField(default = 0) class Meta: verbose_name_plural = 'Categories' ordering = ('ordering',) def __str__(self): return self.title class Product(models.Model): name = models.CharField(max_length = 255, null = True) slug = models.SlugField(max_length=200) category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE) parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True) brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE) description = models.TextField(blank = True, null = True) price = models.FloatField(null = True) disccount = models.BooleanField(default = False) disccount_price = models.FloatField(blank = True, null = True) image = models.ImageField(upload_to = 'images/',blank = True, null = True) thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) … -
ModuleNotFoundError: No module named 'app' after executing pycharm test
Good day, I have been having this issue where I have been running into this ModuleNotFoundError: No Module named 'app' error when I am trying to test models.py I am trying to utilize pycharm IDE in order unittest. Configurations which I have set using pycharm are: Script path:/MainFolder/MainProjects/project1-backend/tests/test_models.py Environment Variables: empty Python interpreter: Python 3.8 (MainFolder) ~/MainFolder/MainProjects/bin/python Working Directory:/Users/myname/MainFolder/MainProjects/project1-backend Add contentroots to PYTHONPATH: selected Add source roots to PYTHONPATH: selected Here is my project hierarchy. Note, I changed the name of the folders. Also I have included the __init__.py files as per below. Project hierarchy edit test file should be __init__.py not __inity__.py #import from Model class from django.test import SimpleTestCase from django.db import models #User model class User(models.Model): email = models.CharField(max_length=256, primary_key=True) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) def __str__(self): return self.email # this defaults to the email address from django.test import TestCase from app.models import User class TestModels(TestCase): def setUp(self): self.user1 = User.objects.create( email="m@gmail.com", first_name="misha", last_name="lee" ) def test_app_user(self): self.setUp() self.assertTrue(isinstance(self, User)) I also did a quick print out for sys.path: ['/Users/myname/MainFolder/MainProjects/project1-backend/tests', '/Users/myname/MainFolder', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'] Traceback (most recent call last): File "/Users/myname/MainFolder/MainProjects/project1-backend/tests/test_models.py", line 4, in <module> from recruiting.models import User ModuleNotFoundError: No module named … -
Scheduled Django management commands using Zappa & Lamda
I've got my Django site working on Lambda using Zappa. It was very simple. I'm now searching to find out how I set up scheduled Django management commands. From what I've read the work around is to create Python functions that execute the management commands and then schedule the functions to run using the Zappa settings file. Is this still the right method as the help manual doesn't say anything? -
How to update webpage data without refreshing webpage?
I have been using services like slack, discord and gmail and am wondering the type of software they use to recieve a message live, or display an incoming email without refreshing the page? Could this be implemented with a django rest backend and react frontend? -
Create multiple and different records with django
I'm using django and postgresql. I'm posting a json thread with postman. {"side": "BUY", "type": "MARKET", "symbol": "NEOUSDT"} After the data arrives, I filter the database as "side=NEOUSDT,status=True,side=BUY". The list I filtered has a json structure like above. Since the apiKey and secretKey information of each line information is different, I have to create "create_new_order" separately for each. So there can be 10 records, how can I do it in a series for each one separately? In other words, it needs to create "create_new_order" separately for each record, I want to provide it. Also, the program should run async in order not to crash. data(result) [ {"model": "cryptoinfo.cryptoinfo", "pk": 4, "fields": {"createdDate": "2020-10-08T20:49:16.622Z", "user": 2, "created_userKey": "25301ba6-1ba9-4b46-801e-32fc51cb0bdc", "customerKey": "61754ecf-39d3-47e0-a089-7109a07aca63", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "2200", "secretKey": "0022"}}, {"model": "cryptoinfo.cryptoinfo", "pk": 7, "fields": {"createdDate": "2020-10-08T20:51:16.860Z", "user": 1, "created_userKey": "2f35f875-7ef6-4f17-b41e-9c192ff8d5df", "customerKey": "b1c8cee3-c703-4d27-ae74-ad61854f3539", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "atalay42", "apiKey": "0011", "secretKey": "1100"}} … -
Django API push from external python function
I have a ReactJS app that has a Django backend with a Postgres Database. Currently my models.py file that calls several external functions from a receiver. I want one of these external functions to push data to the API so that the React App can access and display that data. models.py class Job(models.Model): name = models.CharField( max_length=100) job = models.IntField( max_length=50) ... @receiver(post_save, sender=Job, dispatch_uid="run function) def run_function(sender, instance, created, *args, **kwargs): #some logic ... id = instance.name externalData = externalFunction(id) #I don't know what to do from here My goal is to send the returned data (which is currently in a dictionary but can be parsed out) to a new model named Data. I know how to get that dictionary into a local variable but don't know how to send it to the api. -
How can I make a reservation system with Django rest framework?
I'm coding a rest API with Django rest. I have a Room model I want to users can reserve the rooms. the rooms have price, reserve days. I created two another models named "order" and "order-item" they are linked together with Stacked Inline in admin.py . with these two models I want to create a order and with a total price function I want to calculate the total price of the reservation ("room price" * "reserve days") . I used Model Serializer for serializing my models. I want to create a reservation system to registered users can book the rooms but I don't know how to do this. I'm beginner and this is a hard project. I need help to complete this project. I can't write views.py please help me write my view. from django.contrib.auth.models import User from django.db import models from eghamat.models import Room class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) return total class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = … -
Store multiple values in 1 field Django (Postgres)
My plan is to have a model that is able to store multiple values in 1 row. Basically what I want is that when a user submits my form, than it will save the weight the height and the current date. And for example the user does the same thing a month later than he will have 2 values. (They will be displayed on a graph). Thanks in advance! Models File class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile') weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True), null=True, ) height = models.FloatField(max_length=20, blank=True, null=True) date = ArrayField( models.DateField(auto_now_add=True), null=True, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views file def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(request.user.user_profile) form = WeightForm(request.POST, instance=profile) if form.is_valid(): print(request.POST) form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, 'Landing/index.html',{'form':form}) Forms class WeightForm(ModelForm): class Meta: model = Profile fields = ['weight','height'] -
How does Gmail know when a new email comes in?
In gmail, when I get an email, I don't need to refresh the page, it automatically updates my inbox UI to show the new email. How do they do this? Do they make a POST request every second or something? Can you achieve this in Django or Node? Thanks! -
How to save nested data via django rest
JSON object: { "MajorUnitHeaderId": 10793322, "Parts": [ { "DealerId": "", "Description": "BATTERY 6 VOLT", "SetupInstall": "S", "Qty": 4, "Cost": 174.95, "Price": 0.0 }, { "DealerId": "", "Description": "1400/1000/185 BATTERY", "SetupInstall": "S", "Qty": 2, "Cost": 189.95, "Price": 0.0 } ] } Serializers: class MajorUnitPartSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitPart fields = '__all__' class MajorUnitSerializer(serializers.ModelSerializer): parts = MajorUnitPartSerializer(many=True) class Meta: model = MajorUnit fields = '__all__' def create(self, validated_data): pdb.set_trace() parts_data = validated_data.pop('Parts') unit = MajorUnit.objects.create(**validated_data) for part_data in parts_data: MajorUnitPart.objects.create(unit=unit, **part_data) return unit Views: @api_view(['GET','POST']) def majorunitapilist(request): query = '76179602?$top=1&$skip=0' api_majorunit_list = get_majorunit(query) for unit in api_majorunit_list: pk = unit.get('MajorUnitHeaderId') try: obj = MajorUnit.objects.get(Cmf=pk) serializer = MajorUnitSerializer(instance=obj, data=unit) if serializer.is_valid(): serializer.save() except: serializer = MajorUnitSerializer(data=unit) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response(serializer.data) Errors: {'parts': [ErrorDetail(string='This field is required.', code='required')], 'Parts': [ErrorDetail(string='Incorrect type. Expected pk value, received list.', code='incorrect_type')]} [09/Oct/2020 12:40:59] "GET /api/majorunit-apilist/ HTTP/1.1" 200 7605 -
When would you use Client Side Rendering VS. Server Side Rendering?
I am new to React and wondering when someone would use: 1. Server Side Rendering 2. Client Side Rendering With React and Django Rest Framework. What causes something to be better with one or the other? Thanks! -
Use a decorator to add in a variable to request
I know the suggested way to do this is middleware, but I'd like to implement the following to add in an env variable so that my view can access it: @api_wrapper def my_view(request): print env # this is the variable I want, such as request.env And the decorator: def api_wrapper(func): def api_inner(request): request.env = 'something' return func(request) return api_inner What's the best way to do this? I have about 100 functions to wrap so I don't want to add in a new parameter for every function but would just like to use the simplest approach to pass that 'env' variable. How should I do it. -
Do I need to learn django to implement tensorflow into my webapp
i am a college student studying my first semester in BCA(BAchelor in Computer Applications) and i'm still in the process of learning mern stack for web development , and yeah like everyone i got hella interested in machine learning and i came across some frameworks such as tensorflow and tensorflow.js, so the problem is i have spent a lot of time learning express to build the backend of webapps and i dont want to end up spending time on more courses, do i have to take a course on django as well in order to implement tensorflow into my websites, i dont want to use tensorflow.js since its much slower and heard a lot of people saying tensorflow is better another question will it be wise to buy a book to learn tensorflow, i seriously want to get into web development and machine learning, ive seen a book on amazon with the title:( Hands-On Machine Learning with Scikit-Learn, Keras and Tensor Flow: Concepts, Tools and Techniques to Build Intelligent Systems (Colour Edition)) will it be good enough And yes I need to post these types of questions on other places like reddit or Quora but I find stack overflow answers … -
Associate AJAX Image Uploads to Post During Post Creation (generic CreateView)
I have a typical Post model: models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField(blank=True) ... My content area uses Editor.MD. EditorMD has user image upload capabilities. The post form is rendered from a typical CreateView class-based view. views.py (the gist) class CustomCreateView(LoginRequiredMixin, CreateView): model = Post form_class = AddNewPostForm template_name = 'myapp/post_create.html' success_url = None ... class UploadView(View): result = { 'success': 0, 'message': 'Image upload failed.', 'url': '', } # processing # goal is to return that result.url of where the image lives return JsonResponse(self.result) When these images are uploaded during the creation of a new post, they are essentially "unattached" or not related to the Post instance itself. I would like these uploaded images to ultimately and eventually have a relation to the post being created. The problem is, when a user is in the process of creating / writing the post, there is no Post ID to attach these images to since it hasn't been created yet. So here are my questions: How can I relate these user-uploaded images to the current post that hasn't been submitted yet? How should I manage user-uploaded images in the content area that the user adds, … -
How can we get more than two users from the database randomly in Django?
Well I am creating profile of every new user with signals and I am trying to add some default followers in the new user profile. I am trying with the following code and that is actually doing quite fine but not exactly that thing which i am wishing to do. Well with the following code. first 2 users with pk=1,pk=2 are becoming default followers of every new profile. I wish i could give some random users as a followers to every new user. For example: first user created new account and get two users following by default with pk=1 ,pk=2 than second user created new account and get two users following by default with different primary key such as pk=2 , pk = 4. Code: With the following code every new user is getting the same two 2 users with pk=1,pk=2, I dont want that. How can do that things which i have explained with example. Please help cause i need in this case. I shall be very thankful to you. if more detail or code is needed than tell me. I will share that with you. def create_profile(sender, created,instance,**kwargs): if created: userprofile = UserProfile.objects.create(user=instance) default_user_profile = UserProfile.objects.get_or_create(user__pk=1)[0] default_user_profile.follower.add(instance) userprofile.follower.add(default_user_profile.user) …