Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to get admin full name
I have a model named Post, and want to save the full name of the admin automatically who created(or edited) that post. I read about get_full_name() in django documentation, but I cannot understand how to call this method. Here is my Post model class Post(models.Model): post_id = models.AutoField postname = models.CharField(max_length=50) description = models.CharField(max_length=1000) location = models.CharField(max_length=30) user = // I want to store the logged in admin full name here -
Unable to create the django_migrations table (ORA-00907: missing right parenthesis)
I have used oracle database with django. I am new with integrating oracle with django. This is my models.py: models.py : from django.db import models # Create your models here. class Users(models.Model): id = models.AutoField(primary_key=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) contact_no = models.CharField(max_length=100) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.CharField(max_length=2000) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed_likes(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) class feed_comments(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) comment = models.CharField(max_length=500) I have also migrated the models py manage.py makemigrations api py manage.py sqlmigrate api 0001 But when executing this command py manage.py migrate It give this error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-00907: missing right parenthesis) Please help me to solve this problem -
Django - Display success messages for 10 or 20 seconds in Django Admin Panel
I was working in Django admin. So while saving a modal there is an automatic success message that appears after saving. I was wondering if it is possible to set the time limit for the message to appear. So that after few seconds it deletes automatically!! In the picture below after creating a project and saving it there is a success message which says "The project 'xyzproject' was added successfully". But this message remains on the page until I refresh the page. so can anyone tell me if its possible to add a time limit for the message to appear and disappear without refreshing the page. -
decoding a list from a channels.http.AsgiRequest
I have a docker container which sends data_dict, a dictionary {'dome_temp": 15.5C, 'humidity":71%} using the requests library https://requests.readthedocs.io/en/latest/user/quickstart/ with the following code response = requests.post(dome_control_target, data=data_dict) It is received in another container running django via a daphne server. It is received in a channels consumer with this code: def receive_temperhum_data(request): logger.info(f"message received from temperhum {request.data}") return HttpResponse("temperhum data received") request.data returns the error 'AsgiRequest' object has no attribute 'data' So does request.message Request is type: 'channels.http.AsgiRequest' and has the plain text of <AsgiRequest: GET '/dome_control/temperhum/?dome_temp=15.5C&humidity=71%25'> I want to process this data in the consumer. I suppose I could just parse the text, but does anyone know how I can extract the data as a dictionary ? Thank you -
Context not showing Context variable in Template
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} -
RuntimeError: Never call result.get() within a task
My task (check payment status in Sberbank. If no capture - retry check): from ....celeryconf import app from . import client as sberbank from ...models import Payment, Transaction @app.task(bind=True, default_retry_delay=60, time_limit=1200) def check_status_sberbank_task(self, order_id, connection_params): sberbank_client = sberbank.Client(auth=(connection_params['login'], connection_params['password']), sandbox=connection_params['sandbox_mode']) response = sberbank_client.payment.get_status(order_id=order_id) txn = Transaction.objects.get(token=order_id) if response['actionCode'] == 0: txn.is_success = True txn.save() payment = Payment.objects.get(pk=txn.payment_id) payment.charge_status = 'fully-charged' payment.captured_amount = payment.total payment.save() return 'Success pay on Sberbank for ' + str(order_id) else: self.retry(countdown=60) in log file I have: ERROR celery.app.trace Task saleor.payment.gateways.sberbank.tasks.check_status_sberbank_task[bb384815-4a5b-49d7-bc29-114707f072b1] raised unexpected: RuntimeError('Never call result.get() within a task!\nSee http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks\n',) [PID:26869:Thread-825] Traceback (most recent call last): File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/home/korolev/saleor/saleor/payment/gateways/sberbank/tasks.py", line 26, in check_status_sberbank_task self.retry(countdown=60) File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/task.py", line 715, in retry S.apply().get() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 1015, in get assert_will_not_block() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 41, in assert_will_not_block raise RuntimeError(E_WOULDBLOCK) RuntimeError: Never call result.get() within a task! See http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks How do I fix this error? -
add permission to model
I have two models, abstract user and admin, linked onetoonefield. I want to add permissions for admin. I registered in meta permissions, but they are not saved or created in the database. What do I need to do? When I call admin.has_perm ('MoveOnApp.register_partner') I get the error 'Admin' object has no attribute 'has_perm' class AbstractUser(AbstractBaseUser, PermissionsMixin): """Создал абстрактоного юзера от которого будут унаследованны остальные юзеры""" phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True, unique=True) created = models.DateTimeField(_('date joined'), default=datetime.datetime.now()) USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] objects = BaseManager() is_superuser = None class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Admin(models.Model): """Создаю модель администратора, наследованную от AbstractUser""" user = models.OneToOneField(AbstractUser, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField( _('company name'), max_length=150, ) logo_url = models.ImageField( upload_to='img/logo' ) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) # Флажок, такие права доступа рекомендует делать документация. Есть еще варианты но этот мне кажется самым удобным is_admin = models.BooleanField( _('admin status'), default=True ) objects = BaseManager() class Meta: permissions = ( ("register_partner", "Can register partner"), ) -
AJAX request and csrf token
So from my cart page I want to rend an AJAX request to Django server. It is made to update the number of items in my cart and the checkout price. Here is my AJAX request $('.plus').click(function() { var productId = $(this).find('#productId').val(); req = $.ajax({ headers: { "X-CSRFToken": csrftoken }, url: 'updateit/', type: 'post', data: {'productId' : productId, 'action' : 'plus'} }); req.done(function(data) { $('#total').text(data.total); $('#total_with_delivey').text(data.total_with_delivery); $('#summary').text(data.subtotal); }); }); Here is django view: @require_http_methods(["POST"]) def updateit(request): product = Product.objects.get(id = request.POST['productId']) action = request.POST['action'] if action == 'plus': try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() elif action == 'minus': if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() else: cart_item.delete() item_count = 0 total = 0 cart = Cart.objects.filter(cart_id=_cart_id(request)) cart_items = CartItem.objects.all().filter(cart=cart[:1]) cart_item = CartItem.objects.get(id=request.POST['productId']) subtotal = cart_item.quantity*cart_item.price for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) item_count += cart_item.quantity total_with_delivery = total + 50 return JsonResponse({'result' : 'success', 'item_count' : item_count, 'total' : total, 'total_with_delivery' : total_with_delivery, 'subtotal' : subtotal}) Every time I press … -
Django Python: How to store python code in a textinput form
I have a requirement where user can save some python code in the form which will be run later when needed. How best we can do this using django and save in database. The user will be shown a form and the he can type the code. and save it in the database. -
How to deploy django project on heroku?
I want to deploy django project on heroku i need list of things that i should take care about project and what are the basic requirements. -
ModuleNotFoundError: No module named 'post_project' Heroku and Django
I was going through a tutorial about creation of user accounts and by its end I tried to deploy my website, but I got this error ModuleNotFoundError: No module named 'post_project' My working directory looks like this And this is settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' Most of the time I've adhered to the tutorial section about accounts in "Django For Beginners" by W.Vincent. Yet still I do get this particular error every time I try to deploy. I attempted to change django version, it didnt help either. Help will be much appreciated -
Why am I seeing localhost:8000 empty path does not match Django?
I keep running into 'Page not found' when trying to load http://localhost:8000/ . I have an empty path set to direct the page to my project_index page, but this is all I get: I have checked and re-checked all of my urlpatters, but cannot figure out where the problem is. Here are all my urls.py scripts that correspond to this project: personal_portfolio/: projects/: blog/: -
create Django form class with dynamic number of CharFields
I'm having problem of creating a dynamic class form that contains a list of CharFields. I'm able to create a normal class with dynamic keys values as below. but when I change the values to be a CharFields. it doesn't work. What's wrong with the form? =========Normal class=========== class DynamicClass(forms.Form): def __init__ (self, data): self.data =data for key in self.data.keys(): self.__setattr__(key, self.data[key]) my_class = DynamicClass({"HOSTNAME": 'Router_Hostname: ', "IP": 'IP_ADDRESS:'}) print (my_class.HOSTNAME) output --> Router_Hostname: print (my_class.IP) output--> IP_ADDRESS: =========Form class=========== class DynamicForm(forms.Form): def __init__ (self, data): self.data =data for key in self.data.keys(): self.__setattr__(key, forms.CharField(label = self.data[key])) my_form = DynamicForm ({"HOSTNAME": 'Router_Hostname: ', "IP": 'IP_ADDRESS:'}) print (my_form.as_table) error output--> Traceback (most recent call last): File "", line 1, in File "~/automation/lib/python3.8/site-packages/django/forms/forms.py", line 137, in repr if self._errors is None: AttributeError: 'DynamicForm' object has no attribute '_errors' -
PYTHON: I'm trying to read different values from XML files and send to Django Html template
I have already read the xml values but i think that the way which i'm using to store the data is wrong. I'need to store a list, or a dict or list of dict some values and then send to the HTML Template and render an HTML Table with all the values: this should be the result and the following code is how i'm actual reading the values from XML for files in file_in_path: fileP = os.path.join(path,files) tree = ET.parse(fileP) roots = tree.getroot() for x in roots.findall('DatiGeneraliDocumento'): //node of xml file that i need to read tipdoc = x.find('TipoDocumento').text //all the data numdoc = x.find('Numero').text datadoc = x.find('Data').text mydict = {"tipdoc":item,"numdoc":numdoc,"datadoc":datadoc} //then i'm trying to save in dict liste.append(mydict)//and append all to a list context = {"data":liste} return(response, "page.html", context) when i'm in my html page and trying to print the result with django format language "{{ data }}" he print out one value and not all of of them, but if in python file i print out my list he print out all list. which is the best way to store all the values in all the xml files and then print out in a html table? -
I have uploaded my 1st django application to AWS but it is not working [closed]
I Followed this document https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html i am using Windows there wan no error in my powershell but when i launch website in browser it shows. i tried checking logs but cant understand the problem. -
WebSocket connection to 'ws:/' failed: Error during WebSocket handshake: Unexpected response code: 200
I am using Django-channels to connect to the server, but it always show the error like this: reconnectwebsockets.js WebSocket connection to 'ws:xxx' failed: Error during WebSocket handshake: Unexpected response code: 200 Any ideas what could be possibly wrong? -
Error creating A Django Timetable Generator
I am trying to create an app that generates a timetable for each class in a school. The timetable is supposed to prevent classes and teachers clashing with a specific number of periods in a week. The problem is it keeps generating a different number of timetables every time. My View where the timetable is generated: def GenerateTimetable(request): if request.method == 'POST': idf = request.POST["timetable_class_id"] classs = ClassRegistration.objects.get(id=idf) subjects = list(Class_Subjects.objects.filter(subject__select_class=classs)) class_periods = list(Period.objects.filter(section=classs.section).order_by('start_time')) break_time = Breaks.objects.get(section=classs.section) before_break = Period.objects.filter(start_time__lte=break_time.start_time).count() if Timetable.objects.filter(school_class__id=idf).count() != 0: Timetable.objects.filter(school_class__id=idf).delete() for subject in subjects: DupNum = 0 y = 0 m = 0 j = 0 if DupNum > len(class_periods): messages.info(request, "Couldn't create Timetable") redirect('home') while y < subject.no_of_times_a_week: if DupNum > len(class_periods)+ 3: break if DupNum < 3: if subject.is_morning and m < 3: i = random.randint(0, before_break) else: i = random.randint(0, len(class_periods)-1) else: if j < len(class_periods): i = j j += 1 start_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__range=(class_periods[i].start_time, class_periods[i].end_time)) end_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__end_time__range=(class_periods[i].start_time, class_periods[i].end_time)) during_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__gte=class_periods[i].start_time, period__end_time__lte=class_periods[i].end_time) teacher_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__gte=class_periods[i].start_time, period__end_time__lte=class_periods[i].end_time) subject_conflict = Timetable.objects.filter(period__day=class_periods[i].day, subject=subject) if start_conflict.count() == 0 and end_conflict.count() == 0 and during_conflict.count() == 0 and teacher_conflict.count() == 0 and subject_conflict.count() == 0: Timetable.objects.create(school_class=classs, subject=subject, period=class_periods[i]) DupNum = 0 … -
from django.db import models in models.py but in command prompt i got NameError: name 'model' is not defined
i got an this error: File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 15, in class Product(models.Model): File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 16, in Product name = model.CharField(max_length=200, null=True) NameError: name 'model' is not defined But in my "models.py" in the first line i have imported the model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name Any clue what i should look for please? Thank you -
pip install weasyprint on windows
I get this error when i use pip install WeasyPrint pip install WeasyPrint Collecting WeasyPrint Using cached WeasyPrint-51-py3-none-any.whl (359 kB) Collecting Pyphen>=0.9.1 Using cached Pyphen-0.9.5-py2.py3-none-any.whl (3.0 MB) Collecting tinycss2>=1.0.0 Using cached tinycss2-1.0.2-py3-none-any.whl (61 kB) Collecting cssselect2>=0.1 Downloading cssselect2-0.3.0-py3-none-any.whl (31 kB) Collecting cairocffi>=0.9.0 Using cached cairocffi-1.1.0.tar.gz (68 kB) ERROR: Command errored out with exit status 1: command: 'd:\myshop\virtual\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-qwm3sa11\\cairocffi\\setup.py'"'"'; __file__='"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-qwm3sa11\\cairocffi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\USER\AppData\Local\Temp\pip-pip-egg-info-tqlmdfuq' cwd: C:\Users\USER\AppData\Local\Temp\pip-install-qwm3sa11\cairocffi\ Complete output (107 lines): Traceback (most recent call last): File "d:\myshop\virtual\lib\site-packages\setuptools\msvc.py", line 489, in _find_latest_available_vc_ver return self.find_available_vc_vers()[-1] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 154, in save_modules yield saved File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 195, in setup_context yield File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 250, in run_setup _execfile(setup_script, ns) File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 45, in _execfile exec(code, globals, locals) File "C:\Users\USER\AppData\Local\Temp\easy_install-_u06tvni\cffi-1.14.3\setup.py", line 131, in <module> File "C:\Users\USER\AppData\Local\Temp\easy_install-_u06tvni\cffi-1.14.3\setup.py", line 109, in uses_msvc File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\command\config.py", line 225, in try_compile self._compile(body, headers, include_dirs, lang) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\command\config.py", line 132, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\_msvccompiler.py", line 360, in compile self.initialize() File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) File "d:\myshop\virtual\lib\site-packages\setuptools\msvc.py", line 185, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() … -
How to "pip install" latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT?
I am working in Django. I want to install all the python modules which are the latest. What should in HAVE to do to update all the latest versions of modules? How to "pip install" the latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT? Let's say, Inside requirements.txt is: asn1crypto==1.0.1 astroid==2.3.1 so I want to install the latest version of: asn1crypto and asn1crypto -
How to iterate over a list in django template
I want to iterate over a list which is passed in template in a tuple. I want to show some descriptions in their relative places. I have all the descriptions(7-8) in a list. Here is views.py file looks like: from django.shortcuts import render import requests from bs4 import BeautifulSoup from .functions import get_descriptions def index(request): url = requests.get('https://thehackernews.com/') soup = BeautifulSoup(url.content, 'html.parser') post_container = soup.find(class_='blog-posts') post_body = post_container.find_all(class_='body-post') total_news = range(0, len(post_body)) descs = get_descriptions(post_body=post_body) # a list of descriptions final_postings = [] for link in post_body: post_link = link.find(class_='story-link').attrs lnk_lst = str(post_link['href']) # print(lst) images = link.find(class_='home-img-src').attrs src_lst = str(images['data-src']) # print(src_lst) titles = link.find(class_='home-title').get_text() post_dates = link.find(class_='item-label').get_text() final_postings.append((lnk_lst, src_lst, titles, descs)) front_end_stuff = {'final_postings': final_postings, 'news': total_news} return render(request, 'mainapp/index.html', context=front_end_stuff) And the template mainapp/index.html looks like: {% extends 'mainapp/main.html' %} {% block content %} {% for post in final_postings %} <div class="card hoverable"> <div class="card-content"> <div class="row"> <div class="col s12 l4"> <div class="card-image"> <img src="{{ post.1 }}" alt="news" class="responsive-img"> </div> </div> <div class="col s12 l7 offset-l1"> <a href="{{ post.0 }}" class="black-text"><div class="title">{{ post.2 }}</div></a> <p class="truncate">{{ post.3 }}</p> </div> </div> </div> </div> {% endfor %} {% endblock content %} I want to show the relative description to … -
STATIC(CSS AND JS) FILES ARE NOT WORKING AFTER UPLOADING WEBSITE ON HEROKU
I have just uploaded my website on heroku, the css and javascript files works perfectly on localhost but doesn't work after deploying. I also made sure to run this command python manage.py collectstatic which i did both in the production and development environment but doesn't still solve the problem. I have included the necessary codes that would be useful, i have also included the images of both instances and my project directory Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the image on localhost This is the image on heroku And this is the the project directory structure -
Django TypeError: expected string or bytes-like object
I don't know why am receiving this error in the first place check the whole code thrice I am calling out a signal from Django View to create an object in the model for analytical purpose. models.py RECEIVER_REQUEST_TYPE = ( ('ABOX', 'Android Bounding Box'), ('ENTR', 'Web Bounding Box'), ) class BaseAnalytics(models.Model): """Common filds for all the tables""" ip_address = models.CharField(max_length=220, blank=True, null=True) content_type = models.ForeignKey( "contenttypes.ContentType", on_delete=models.CASCADE, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) # status = models.IntegerField(blank=True, null=True) execution_time = models.TimeField(verbose_name='Time Taken for each qeury to execute') class ReceiverAnalytics(BaseAnalytics): """reciever analytics""" longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) request_type = models.CharField(max_length=4, choices = RECEIVER_REQUEST_TYPE) def __str__(self): return str(self.id) class Meta: verbose_name = 'Receiver Analytics' verbose_name_plural = 'Receiver Analytics' # SIGNAL def receiverAnalyticsSignal(sender, request, request_type, time, longitude, latitude ,*args, **kwargs): pdb.set_trace() c_type = ContentType.objects.get_for_model(sender) new_call_obj = ReceiverAnalytics.objects.create( ip_address = get_client_ip(request), content_type = c_type, request_type = request_type, longitude = longitude, latitude = latitude, execution_time = time, ) print(new_call_obj) object_viewed_signal.connect(receiverAnalyticsSignal) Signal.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['request']) Views.py object_viewed_signal.send( Receive, request_type='NRBY', longitude=longitude, latitude=latitude, time=total_time, request=request ) Here are types of fields --------------- Receive > model_name mark NRBY > String enum longitude, latitude, time > … -
Django 2.2 - how to express a constraint between two fields
I have a couple of models that look like this: class AlarmStatus(Enum): UNDEFINED = "Undefined" PENDING = "Pending" CUSTOMER_PENDING = "Customer Pending" @classmethod def choices(cls): return tuple((i.name, i.value) for i in cls) class Alarm(models.Model): managed = models.BooleanField(default=False, blank=False, verbose_name="Managed ?") status = models.CharField( max_length=20, default=AlarmStatus.UNDEFINED.name, choices=AlarmStatus.choices() ) class Meta: constraints = [ models.CheckConstraint( check=Q(managed=False) & Q(status=AlarmStatus.UNDEFINED.name), name="if_managed_is_False_status_must_be_UNDEFINED") ] I would like to enforce at the db level the following invariant: if an alarm managed field is False, then its status field MUST be "UNDEFINED". I.e. I want to declare illegal the following state/combination: managed == False AND status == (PENDING | CUSTOMER_PENDING) How can I enforce this? I tried with the above constraint but it is clearly wrong, because it is enforcing that every row managed field must be False AND every row status must be UNDEFINED. Thanks -
How can I prerun my APIs from my Django Restful API dashboard
I currently have this Django Swagger API dashboard and I want to run the APIs that I've already ran, I want to try loading the APIs into a text file and run the text file.