Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Connect Django With Mqtt
i know how to use mqtt with python but i can't connect django app to mqtt background research <http://www.steves-internet-guide.com/mqtt-basics-course/> <https://pypi.org/project/paho-mqtt/#installation> -
Angular + Django Rest Framework rearranging array on SPA, separate severs works okay
I have a random issue happening. When I run Angular and Django one separate instances (ng serve --poll 2000 & python manage.py runserver) my data is transferred as expected and works okay. When I build my angular project and run via apache2 using django as the entry point for the application I have an array which becomes reordered every time. node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --aot --output-path ../backend/static/ang --output-hashing none The array is loaded with the same contents on different pages and can be in any order. There are 4 primary categories and its these which are reordered. The ITEM1, ITEM2, ITEM3 and ITEM4 below. I have no idea why. The code which makes the nodes is below: def get(self, request): response = {} subjects = ['ITEM1', 'ITEM2', 'ITEM3', 'ITEM4'] for subject in subjects: try: alltitles = TitlePageTitles.objects.filter(title__contains=str(subject)) response.update({subject : []}) titleslist = [] returnedJson = {} returnedList = [] returnedJsonString = "" for title in alltitles: titleslist = list(TitlePageItems.objects.filter(ks_key=title.title).order_by('id').values()) newJsonItem = { "id": 0, "ks_key": title.title, "item_text_display": title.title.replace("_"," "), "item_text_link": title.title.replace("_"," "), "order": -1, "page_id": 0, "children": ArrayToNested(titleslist) } returnedList.append(newJsonItem) response.update({subject : returnedList}) except Exception as inst: print(inst) returnedList2 = [] for key, value in response.items(): #logger.error(key) newJsonItem = … -
How can I create a ForeignKey leaving chances for different models for the TO field?
I have multiple product models like below class ProductBase(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True def __str__(self): return self.name class ProductOne(ProductBase): color = models.CharField(max_length=50) class ProductTwo(ProductBase): type = models.CharField(max_length=50) class ProductThree(ProductBase): breed = models.CharField(max_length=50) Each of these products is expected to have an image_set, so I created the model below for product's images class Image(models.Model): product = models.ForeignKey(to=[HERE IS THE PROBLEM], on_delete=models.CASCADE) image = models.ImageField(upload_to='upload-path') How can I get the product field in my Image class to point to any of the products defined above as desired. -
(Django) Signal isn't working but it works in the shell
I have a signal that runs post_save when a new Student is created that goes through their currently enrolled courses and assigns them an instance of the courses' assignments (for scoring). In users/signals.py: @receiver(post_save, sender=Student) def save_student_assignments(sender, instance, created, **kwargs): if created: all_courses = instance.enrolled_courses.all() assignments = Assignment.objects.filter(session_link__in=all_courses) for assignment in assignments: StudentAssignment.objects.create(student=instance, assignment=assignment) I have already been in users/apps.py to import the signal. If I run this exact code in the shell, it will create the StudentAssignment objects and they'll show up for the user. What am I missing here that's not making the signal fire like it should? -
ImproperlyConfigured at /accounts/verification/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Well I am actually trying to add some very simple logic here. All I want to do is that if the vcode or verification code is equal to 5577 than redirect me to the login page. Otherwise if the user enter wrong number than just show an alert message with text that the code is incorrect or invalid and ask him code to enter again. Right now its showing me an error( given in the Title of this question) when I hit the verify button. If more detail or code is required for help than tell me. I will update my question with that information. I shall me very thankful to you. If you guys spend some of your precious time to answering me with a wonderful and helpful information! class CodeCreateView(CreateView,SuccessMessageMixin): form_class = CodeForm def form_valid(self,form): vcode = form.cleaned_data.get('code') if vcode == 5577: user = form.save(commit=False) user.is_active = True success_message = "Verified successfully" success_url = reverse_lazy('login') else : success_message = "Verifification unsuccessful" return super().form_valid(form) # success_url = reverse_lazy('accounts:code_verification') template_name = "accounts/code_verification.html" -
I get AttributeError: 'SubscriptionForm' object has no attribute 'model' when I try runserver and makemigrations
When I do python manage.py runserver or makegrations I get this traceback issue. Where have I gone wrong? Please help. I"m trying to add this to the admin site as well. Thank you This actually worked once, so I'm not sure what I did wrong or what I changed to make this error come up. traceback error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\checks.py", line 56, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\sites.py", line 81, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'SubscriptionForm' object has no attribute 'model' models.py class Subscription(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) username = models.CharField(max_length=100) sub_type = models.BooleanField() email = models.EmailField(max_length=100) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) country = models.CharField(max_length=100) state = models.CharField(max_length=100) zip = models.CharField(max_length=10) same_address = models.BooleanField() save_info = models.BooleanField() credit = models.BooleanField() debit = models.BooleanField() paypal = models.BooleanField() cc_name = models.CharField(max_length=100) cc_number = models.IntegerField() … -
Django DateTime Subtraction Hours
I subtract two datetime objects and get integers instead of time in hours and minutes. This is my MODEL.PY class TimeLog(models.Model) start_date = models.DateTimeField(null=True, blank=True, default=datetime.now) end_date = models.DateTimeField(null=True, blank=True, default=datetime.now) time_diff = models.DateTimeField(null=True, blank=True) TimeLog.objects.filter(time_diff=None).update(time_diff=F('end_date') - F('start_date')) I get 2020-09-12 22:51:58.383288 - 2020-09-12 23:03:57.088453 = 718705165 How do I make 718705165 to be in hours and minutes? -
Asynchronous show a POST
I am working on a twitter-like social network site. In one single html page, I have a form to send the "tweet" and also down the form I have displayed all the "tweets" made by all users. {% if posts %} {% for post in posts %} "html that creates the tweet, content, creation date, number of likes, etc." {% endfor %} {% endif %} To handle the form submission, I want the "tweets" to be shown asynchronously, so I`m doing a fetch POST request with JavaScript: document.querySelector('form').onsubmit = (event) => { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { document.querySelector('#new_message').value = "" let div = document.createElement('div') div.innerHTML = ("<p>" + result.creation_date + "</p>" + "<a href='#'>" + result.username + "</a>" + ' said:' + '<br><br>' +"<div class='container'>" + "<p>" + result.body + "</p>" + "</div>"); div.style.cssText = "box-shadow: 0px 0px 2px; ; background-color:#F5F5F5; border-radius:10px; padding: 10px; margin: 5px;"; document.querySelector('#plis').append(div); }); This works fine, the tweets are saved and also showed in the page without having to reload the entire page. But the problem is that I am handling the HTML in both … -
Custom User Model table has no column named is_staff
So I am creating a user registration api, here is my code: models.py class CustomUserManager(BaseUserManager): #Making the username to be the user's email def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): #create and save user with a given email and password if(not email): raise ValueError("User must have a valid Email!") now = timezone.now() email = self.normalize_email(email) user = self.model( email = email, is_staff = is_staff, is_active = True, is_superuser = is_superuser, last_login = now, date_joined = now, **extra_fields ) user.set_password(password) user.save(using= self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): """ Create and save a super user with given email and password """ user = self._create_user(email, password, True, True, **extra_fields) user.save(using= self._db) return user class MyUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length= 50) last_name = models.CharField(max_length= 50) email = models.EmailField(unique= True) age = models.DateField(null= False) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) last_login= models.DateTimeField(null= True, blank= True) date_joined= models.DateTimeField(auto_now_add= True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' #instantiating a CustomUserManager() object objects= CustomUserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) I am getting the following error, when I try to register a user: Error message Image It is complaining about is_staff. Error Message: Operational … -
Tabs and image timed changing
I've a tab where I display tab content on the left side, but on refresh, the tab current page doesn't stay, instead it goes back to the home Link. Secondly, on The tabcontent, I've images on my Django database, were I display them on my template using the forloop, but I want to change the images after a given time. Below is my code for better understanding.. Js // Sidebar functionality function openLinks(links){ var i; var x = document.getElementsByClassName("tabcontent"); for (i = 0; i < x.length; i++){ x[i].style.display = "none"; } document.getElementById(links).style.display = "block"; } // Changing Images var divs = $('#men .column'); (function cycle(){ setTimeout(function(){ var index = Math.floor(Math.random() * divs.length); divs.removeClass('active') .eq(index).addClass('active'); cycle(); },500); })(); My HTML <div class="sidebar"> <ul> <li><a href="#/home" class="tablinks" onclick="openLinks('home')"> <span class="icon"><i class="fas fa-home" aria-hidden=True></i></span> <span class="title">Home</span> </a></li> <li><a href="#/men" class="tablinks" history="true" onclick="openLinks('men')"> <span class="icon"><span class="icon"><i class="fas fa-male" aria-hidden=True></i></span> <span class="title">Men</span> </a></li> </div> <div id="home" class="tabcontent"> {% for men in men %} <div class="column"> <a href="{{men.get_men_absolute_url}}"><img src="{{home.pictures.url}}" style="width: 150px; height: 100px;"></a> </div> <div id="men" class="tabcontent" style="display: none;"> {% for men in men %} <div class="column"> <a href="{{men.get_men_absolute_url}}"><img src="{{men.men_pictures.url}}" style="width: 150px; height: 100px;"></a> </div> </div> -
Django count manytomany relation shows wrong number
I currently have a queryset which aims to extract a list of used colors associated with products, and return response with a list of colors and the amount of of products they're attached to. The colors originate in its own model called ProductColor and is referenced through a ManyToMany relationship in the Product model. In the example bellow there are 3 products which has these colors registered: Product 1: White Product 2: White, Red Product 3: White Wished output should be something like: [ { "colors__name": "White", "count": 3 }, { "colors__name": "Red", "count": 1 }, ] However, the closest i get is: [ { "colors__name": "White", "count": 1 }, { "colors__name": "White", "count": 1 }, { "colors__name": "Red", "count": 1 }, { "colors__name": "White", "count": 1 } ] The queryset is structured like this: products = Product.objects.filter( category__parent__name__iexact=category, status='available' ).values('colors__name', count=Count('colors', distinct=True)) I've tried to add .distinct() at the end of the queryset, but then it returns: [ { "colors__name": "White", "count": 1 }, { "colors__name": "Red", "count": 1 } ] I've also tried using an annotation through .annotate(count=Count('colors')), but then it returns: [ { "colors__name": "White", "count": 7 }, { "colors__name": "Red", "count": 3 } ] How can … -
How does the cost of getting a specific row of a table compare to the cost of getting all rows?
I have to render a tree data structure on a user's browser, each node knows its' children. How does getting the whole table and doing the rest of the heavylifting on the client side compare to getting the nodes via multiple queries, knowing that the user might not require all nodes, but in average 80%? That is, to my SQL server is it better to just send the whole table and be done with it or to send nodes as needed, knowing that all nodes might be needed and in average 80% of nodes are needed? The user always requests a node by ID/Primary Key. This question pertains to Django and loading objects recursively. -
Django get response status?
I'm creating a forum. You know, the typical. Profiles can create posts and answer with comments, also they can vote comments and posts. Profile has a score system called reputation (just a Django's PositiveIntegerField in Profile model), which is the sum of created posts, created comments, and received votes for a profile. I have to update it each time one of these events happen, therefore I made a simple function for it, which I call it after every .save() of those objects with the profile to update. But I thought I maybe could use a Middleware for a cleaner code and so I don't have to remember to call that function everytime. Since the Django documentation says after get_response() we put the # Code to be executed for each request/response after the view is called.. But I don't need to run this middleware on each request/response, instead I thought there is maybe a way to check if the status of a response is the creation of an object, and then check if a post, comment, or vote were created in order to run the score update. I'm opened to other ideas if you think that idea can be better or … -
Fatal Python error: Py_Initialize: Unable to get the locale encoding
When I try to deploy my django app on heroku I get this error while I want to show the app. heroku logs --tail 2020-09-12T20:36:32.949657+00:00 app[web.1]: [uWSGI] getting INI configuration from uwsgi.ini 2020-09-12T20:36:32.949732+00:00 app[web.1]: *** Starting uWSGI 2.0.19.1 (64bit) on [Sat Sep 12 20:36:32 2020] *** 2020-09-12T20:36:32.949732+00:00 app[web.1]: compiled with version: 7.5.0 on 11 September 2020 18:09:44 2020-09-12T20:36:32.949732+00:00 app[web.1]: os: Linux-4.4.0-1076-aws #80-Ubuntu SMP Thu Aug 6 06:48:10 UTC 2020 2020-09-12T20:36:32.949735+00:00 app[web.1]: nodename: 3ae70b13-94fd-4637-9782-d3aa9e80ed45 2020-09-12T20:36:32.949735+00:00 app[web.1]: machine: x86_64 2020-09-12T20:36:32.949737+00:00 app[web.1]: clock source: unix 2020-09-12T20:36:32.949738+00:00 app[web.1]: pcre jit disabled 2020-09-12T20:36:32.949739+00:00 app[web.1]: detected number of CPU cores: 8 2020-09-12T20:36:32.949754+00:00 app[web.1]: current working directory: /app 2020-09-12T20:36:32.949754+00:00 app[web.1]: detected binary path: /app/.heroku/python/bin/uwsgi 2020-09-12T20:36:32.949756+00:00 app[web.1]: *** WARNING: you are running uWSGI without its master process manager *** 2020-09-12T20:36:32.949770+00:00 app[web.1]: your processes number limit is 256 2020-09-12T20:36:32.949771+00:00 app[web.1]: your memory page size is 4096 bytes 2020-09-12T20:36:32.949772+00:00 app[web.1]: detected max file descriptor number: 10000 2020-09-12T20:36:32.949774+00:00 app[web.1]: lock engine: pthread robust mutexes 2020-09-12T20:36:32.949822+00:00 app[web.1]: thunder lock: disabled (you can enable it with --thunder-lock) 2020-09-12T20:36:32.950161+00:00 app[web.1]: uwsgi socket 0 bound to TCP address :24256 fd 3 2020-09-12T20:36:32.950203+00:00 app[web.1]: Python version: 3.6.12 (default, Aug 18 2020, 11:10:29) [GCC 7.5.0] 2020-09-12T20:36:32.950227+00:00 app[web.1]: Set PythonHome to /app 2020-09-12T20:36:32.954759+00:00 app[web.1]: Fatal Python error: Py_Initialize: … -
How can I write view decorator for class and non-class methods?
I've built the following decorator to extract a token from HTTP headers, and call the decorated function. Or, if no token exists, or is invalid, returns a 403 status. def extract_operator(func): @wraps(func) def func_wrapper(self, request, *args, **kwargs): try: operator = Operator.objects.get(token=request.META.get('HTTP_OPERATOR_TOKEN')) return func(self, request, operator, *args, **kwargs) except Exception as ex: return Response({}, status=status.HTTP_403_FORBIDDEN) return func_wrapper The problem I'm running into is that this only works for class methods, not for methods outside class that don't use 'self'. The only examples I could find to address this issue used something like this: def extract_operator(func): @wraps(func) def func_wrapper(*args, **kwargs): try: operator = Operator.objects.get(token=args['request'].META.get('HTTP_OPERATOR_TOKEN')) return func(*args, **kwargs) except Exception as ex: return Response({}, status=status.HTTP_403_FORBIDDEN) return func_wrapper This sorta worked but I am not able to pass the 'operator' variable correctly. Here is a non-class method using the decorator: @api_view(['POST']) @extract_operator def send_support_email(request, operator): pass here is an example of a method in a View: @extract_operator def create(self, request, operator, *args, **kwargs): pass How can I modify my decorator to work correctly with both methods? -
validate date in python
I need to validate a date that comes from the front and say that I am over 13 years and I have the code the only thing missing is what goes into the if thanks for your help import datetime class LegalAgeValidator: LEGAL_BASE_AGE = 13 def __init__(self): self.base_age = LEGAL_BASE_AGE def __call__(self, value): if message = 'age not allowed to register.' % self.base_age raise serializers.ValidationError(message) -
Django queryset getting the related field name to filter an aggregate sum
In my models.py I have the following example: **Orders** id product total_gross **Payments** id status order_ID I am creating the following queryset to get a total sum if the payment status is confirmed. So I use the following: week_order_total = Order.objects.prefetch_related('payments').filter(created__range=(week_start_date, week_end_date)).filter(payments.status='confirmed').aggregate(Sum('total_gross'))['total_gross__sum'] I receive the following error: keyword can't be an expression -
Media file not being found in production Django-Heroku: returns 404 error
I have some default images in my media folder in Djang. However, on my website, I cannot see the images being displayed and I get a 404 error. Now my project folder tree is(project name is register): register -- live-static ---- static-root ---- media-root ------ defaults and my media and static files settings are: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'live-static', 'media-root') STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' And inside my urls.py in the same folder as wsgi.py I have: urlpatterns = [ """ My other urls """ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My static files are loaded and the server can retrieve them, however, the images that I added to my folders in media-root are returning a 404 error by the server. Why is this happening as I have already also set STATICFILES_STORAGE as well? -
I am getting src(unknown) when calling an ImageField (pic) on a ForeignKey (handheld) DJANGO
I hope someone can help me out (newbie). I am getting src(unknown) when calling an ImageField (pic) on a ForeignKey (handheld) I see that I am able retrieve all the other values but not the models.ImageField via "cpu.handheld.pic.url", no errors in the python log. If I user for example "cpu.handheld.reg"_date works as you can see below: HTML/JINJA: <!-- Listing 1 --> <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ cpu.handheld.reg_date }}" alt=""> <div class="card-img-overlay"> <h2> python log: [12/Sep/2020 21:51:35] "GET /static/css/style.css HTTP/1.1" 200 61 Not Found: /cpus/Sept. 12, 2020, 8:25 p.m. **[12/Sep/2020 21:51:35] "GET /cpus/Sept.%2012,%202020,%208:25%20p.m. HTTP/1.1" 404 3474** When using "cpu.handheld.pic.url" Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [12/Sep/2020 21:57:02] "GET /cpus/ HTTP/1.1" 200 8329 [12/Sep/2020 21:57:02] "GET /static/css/style.css HTTP/1.1" 200 61 enter image description here These are the two models: =======CPU from django.db import models from datetime import datetime from django.db import models from batt_serials.models import Battery from serials.models import Serial from sites.models import Site from status.models import Status class Cpu(models.Model): cpu = models.CharField(max_length=100) **handheld = models.ForeignKey(Serial, on_delete=models.DO_NOTHING)** battery = models.ForeignKey(Battery, on_delete=models.DO_NOTHING) site = models.ForeignKey(Site, on_delete=models.DO_NOTHING) status = models.ForeignKey(Status, on_delete=models.DO_NOTHING) reg_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.cpu ===================Device from django.db import models from … -
Python server 500 error when dealing with whitenoise
So i parked up a python website project for a month and now want to start back into it. Only problem is that I forgot the fine details of the project after a month. I had uploaded the python website online using: -Heroku -Gunicorn -Github -whitenoise -pipenv No coming back to the project i want to run it locally just to test a few things out. so I cd'd into the project folder an did python3 manage.py runserver. This threw a server error (500) song with a warning in my terminal saying warnings.warn(u"No directory at: {}".format(root)). I played around to try and fix it and found that if I removed the reference to whitenoise in my settings.py the website rendered with the same warning, but was visible. however my static files weren't being used (css). STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join('static'),) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I removed STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'. how can i fix my problem of the site not loading properly locally? -
Add count next to each aggregated value
I currently aggregate a query to get a unique list of strings used in my endpoint. As of now, the fetched data looks like this: { "data": [ "Beige", "Grey", ... ] } However, I'm attempting to do something like this: { "data": [ { name: "Beige", count: 7 }, { name: "Grey", count: 3 }, ... ] } Where count is the amount of times the value occurs in the datbase. Currently, my viewset is structured like this: class ProductFiltersByCategory(APIView): """ This viewset takes the category parameter from the url and returns related product filters """ def get(self, request, *args, **kwargs): """ Gets parameter in urls and aggregated filtered result """ category = self.kwargs['category'] aggregated_result = Product.objects.filter( category__parent__name__iexact=category, status='available' ).distinct().aggregate(data=ArrayAgg('colors__name', distinct=True)) return Response(aggregated_result) How do i go about making the key-value pair structure i want, as well as do the count for each "color"? -
"The submitted data was not a file. Check the encoding type on the form." validation error, despite uploading correct file (django rest framework)
I'm trying to create endpoint for uploading images, in my api, which i'm building with django rest framework. When I try to test the endpoint with postman, i'm getting response "image": [ "The submitted data was not a file. Check the encoding type on the form." ] with status code 400. When I try to print variable with image to console I get [<TemporaryUploadedFile: test.jpg (image/jpeg)>] I've checked out some tutorials and I think i'm sending the file correctly. That is my post man configuration that's the view class ImageView(APIView): parser_classes = (MultiPartParser, ) permission_classes = (IsAuthenticated, IsRestaurant) def post(self, request, *args, **kwargs): data = { 'image': request.data.pop('image'), 'info': request.user.info.pk } file_serializer = RestaurantImageSerializer(data=data) if file_serializer.is_valid(): file_serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) the serializer class RestaurantImageSerializer(serializers.ModelSerializer): class Meta: model = RestaurantImage fields = '__all__' and model class RestaurantImage(models.Model): info = models.ForeignKey(RestaurantInfo, related_name='images', on_delete=models.CASCADE) image = models.ImageField() def __str__(self): return self.image.name -
raise NodeNotFoundError
Please help me , I when deploy project on herokou server migrating I encountered this error While in my system there was no such error and the project was working properly Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, i n execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, i n execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in ru n_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in ex ecute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wra pped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", lin e 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in _ _init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __i nit__ self.build_graph() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 274, in bu ild_graph raise exc File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 248, in bu ild_graph self.graph.validate_consistency() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 195, in val idate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 195, in <li stcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 58, in rais e_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0013_auto_20200828_2241') Where is the error problem? -
How to make DRF GenericViewSet async
I know one shouldn't do long lasting tasks in the main thread, nevertheless I did it... ;-) Now since Django 3.1 there is the possibility to make functions async. I was wondering if this is a way to improve my bad code. IF it is how can I make this DRF View async? class ExportViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = (IsAdminUser,) queryset = myObjects.objects.all() def list(self, request): # this takes very long return response -
display category title in django
I am trying to display the title for the category if it has a title that I want to display, but what happens is that it displays all the titles for the categories #models class category(models.Model): name = models.CharField(max_length=255) head_titel = models.CharField(max_length=255) titel = models.TextField(max_length=1000) def __str__(self): return self.name def get_absolute_url (self): return reverse('store') class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7,decimal_places=2) category = models.CharField(choices=choice_list,max_length=255) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url #view def CategoryView(request,cats): data= cartData(request) cartItems = data['cartItems'] cat_menu = category.objects.all() Category_Post = Product.objects.filter(category__iexact=cats.replace('-' ,' ')) cate = Product.objects.all() return render (request,'store/catogrise.html',{'cats':cats.title().replace('-',' ') , 'Category_Post':Category_Post,'cat_menu':cat_menu,'cat_menu':cat_menu,'cartItems':cartItems,'cate':cate}) #template {% for cate in cat_menu %} <div class="cartEmpty"> <h4>{{cate.head_titel}}</h4> <div class="CartEmpaty"> <small class="a-size-Cart"> <p>{{cate.titel}}</p></small> </div> </div> {% endfor %}