Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throws a 404 error on all static files while everything seems to be correct
Recently, I added some static files to my project which for some reason threw an error (I can't remember what kind of error.) I removed these files and redeployed but now, when I push my Django project to the docker container, the static files have stopped working all together, while everything seems to be in order. These are the settings I use for the static files: STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] I am running the installation in a Docker container, taken from the django-cookiecutter project. I have only changed one thing in the Docker configuration, I removed the Postgres image, since my container connects to an external postgres server. I have tried running manage.py collectstatic, and manage.py collectstatic --clear, to no avail. Also, when I run manage.py findstatic --verbosity 2 css/custom.css, I get a message saying that the file was found, with a list of all the folders searched, which does include the static folders for all my apps inside my project. (There are no static files located outside of default folders.) At this point, I'm pretty lost as to what could be the issue. My best guess would that … -
Factory boy foreign key field with null=True
I have a foreign key field called nutrition on the Product model with null=True. How can you use factory boy randomize the field so that sometimes it's null and sometimes it's a SubFactory? class ProductFactory(factory.DjangoModelFactory): class Meta: model = Product exclude = ('has_nutrition',) has_nutrition = factory.Faker('pyint', min_value=1, max_value=10) nutrition = factory.LazyAttribute( lambda _: factory.SubFactory(NutritionFactFactory) if _.has_nutrition == 10 else None) Calling ProductFactory.create_batch(500) results in the following error ValueError: Cannot assign "factory.declarations.SubFactory object at 0x7fe91c3f8128": "Product.nutrition" must be a "NutritionFact" instance. -
how to include object into category or subcategory?
I need to make that sort of relations: └───SCOPE01 ├───PROJECT01 │ └───WORKER01 └───WORKER02 Worker can be busy on some project or be free on some scope. Have I chosen the right approach, and how can I do otherwise? #models.py from django.db import models class Scope(models.Model): title = models.CharField(max_length=30) class Project(models.Model): title = models.CharField(max_length=30) scope = models.ForeignKey( Scope, related_name='projects', on_delete=models.CASCADE ) class Worker(models.Model): title = models.CharField(max_length=30) project = models.ForeignKey( Project, related_name='workers', on_delete=models.CASCADE ) scope = models.ForeignKey( Scope, related_name='workers', on_delete=models.CASCADE ) If that is correct, how to limit the simultaneous worker addition into both scope and project? -
DataError value too long for type character varying(100)
I need to make changes to my profiles object at the admin site in Django, but when I click save, I get the error DataError at /admin/profiles/profiles/31/change/ value too long for type character varying(100). The weird thing is, it worked when I made changes to the same field locally, but when I deployed to Heroku, it gave me the 'DataError'. My image url is the only long string in my object. Currently: http://res.cloudinary.com/firslovetema/image/upload/v1568570093/ypqiiwg5eq5uyd7oie6g I have tried setting the max_length to 512. it still did not work. my models.py file: from django.db import models from cloudinary.models import CloudinaryField class profiles(models.Model): firstname = models.CharField(max_length=120, default = 'null') #max_length=120 lastname = models.CharField(max_length=120, default = 'null') gender = models.CharField(max_length=120, default = 'null') dob = models.CharField(max_length=120, default = 'null') callNumber = models.CharField(max_length=120, default = 'null') whatsappNumber = models.CharField(max_length=120, default = 'null') ministry = models.CharField(max_length=120, default = 'null') centre = models.CharField(max_length=120, default = 'null') campus = models.CharField(max_length=120, default = 'null') hostel_address = models.CharField(max_length=120, default = 'null') city = models.CharField(max_length=120, default = 'null') qualification = models.CharField(max_length=120, default = 'null') profession = models.CharField(max_length=120, default = 'null') maritalStatus = models.CharField(max_length=120, default = 'null') bacenta = models.CharField(max_length=120, default = 'null') layschool = models.CharField(max_length=120, default = 'null') imagefile = CloudinaryField('image', null=True, … -
Serializing Date field in django-rest-marshmallow results in an error
I am using django-rest-marshmallow along with django-rest-framework to build simple APIs. The following works if I dont include the created_at field in the serializer and gets the results as expected but upon inclusion, it throws and exception. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) created_at = models.DateField() serializers.py from rest_marshmallow import Schema, fields class CategorySerializer(Schema): id = fields.Integer() name = fields.String() created_at = fields.Date() # works, if I dont include this views.py from rest_framework import viewsets class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer This results in the following error Django version 2.2.5, using settings 'app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /api/v1/categories/ Traceback (most recent call last): File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, … -
Django Saleor Stripe SCA Issue
I have a Django Saleor application that handles payment through Stripe.js which is working well. I need to update the application for SCA but despite the code update, I don't get the 3D prompt. Followed the instructions here: https://teams.microsoft.com/join/7z30xkdir2ep Any help is appreciated. -
Django database design for dynamic fields with inheritance
I have a problem with my models design. I have various templates and documents that can created from a template. For example: class Templates(models.Model): name = models.CharField(max_length=255) descripton = models.TextField() content = models.TextField() class Meta: abstract = True class TemplateTest1(Templates): class Meta: verbose_name = "Test 1" class TemplateTest2(Templates): class Meta: verbose_name = "Test 2" And these are the document models: class Test1(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) template = models.ForeignKey(TemplateTest1, on_delete=models.CASCADE) class Test2(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) template = models.ForeignKey(TemplateTest2, on_delete=models.CASCADE) Now the templates should contain various variables. If a user create a document he must filled the variables. Some variables should filled from the system automatically. These variables get the data from the database itself. For example the $system_companyname in the content from TemplateTest2 should show the name from the company that the document is created for. For example the content from TemplateTest1 and TemplateTest2 looks like this: --- TemplateTest1 content --- I am from $town and live in $street. Would you like to go? $dropdown-yes-no --- TemplateTest2 content --- Hello $system_companyname, please check the right answer. $checkbox1 I am older than 16 $checkbox2 I have an apartment So the templates contain various variables and types. The document would store … -
Fetch coinmarketcap pro api results in "string indices must be integers"
i'm currently trying to fetch the exchanges rates of coinmarketcap on there free "pro" api but for some reason i get the following error: "string indices must be integers" def get_exchange_rate(): api_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'start':'1', 'limit':'1000', 'convert':'USD' } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': '7D3728e3-RANDOM-9282-1244', } session = Session() session.headers.update(headers) try: CryptoPrices.objects.all().delete() data = session.get(api_url, params=parameters) exchange_rates = data.json() for exchange_rate in exchange_rates: CryptoPrices.objects.update_or_create( key=exchange_rate['slug'], defaults={ "symbol": exchange_rate['symbol'], "rank": int(exchange_rate['cmc_rank']), "market_cap_usd": round(float(exchange_rate['market_cap']), 3), "volume_usd_24h": round(float(exchange_rate['volume_24h']), 3), "value": round(float(exchange_rate['price']), 3), }) logger.info("Exchange rate(s) updated successfully.") except Exception as e: print(e) logger.info(str("Something went wrong)) This is what the API output looks like if i fetch it with curl: curl -H "X-CMC_PRO_API_KEY: 7D3728e3-RANDOM-9282-1244" -H "Accept: application/json" -d "start=1&limit=5000" -G https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest { "status": { "timestamp": "2019-09-17T11:11:22.727Z", "error_code": 0, "error_message": null, "elapsed": 239, "credit_count": 12 }, "data": [ { "id": 1, "name": "Bitcoin", "symbol": "BTC", "slug": "bitcoin", "num_market_pairs": 8040, "date_added": "2013-04-28T00:00:00.000Z", "tags": [ "mineable" ], "max_supply": 21000000, "circulating_supply": 17940975, "total_supply": 17940975, "platform": null, "cmc_rank": 1, "last_updated": "2019-09-17T11:10:34.000Z", "quote": { "USD": { "price": 10223.8334901, "volume_24h": 15061189990.6449, "percent_change_1h": 0.14997, "percent_change_24h": -1.11433, "percent_change_7d": -0.495979, "market_cap": 183425541050.04684, "last_updated": "2019-09-17T11:10:34.000Z" } } }, ... I didn't worked a lot with JSON API parsing befor, i would be … -
Django update template data with Ajax
I have to update data on template with usage of Ajax and Django views. In template have button that shell update table context based on view response. I have read several similar responses: 1, 2, 3, 4, 5, 6, but can't find solution. template.html <button type="submit" class="btn btn-warning vindication" value="vindication">Vindication</button> <table class="table" align="center"> <thead class="black"> <tr> <th>Data</th> </tr> </thead> <tbody class="data"> {% for client in invoices_all_data %} <tr> <td>{{ client.data }}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function(){ $(".vindication").click(function(){ var vindication_type = $(this).attr("value"); $.ajax({ url: "/invoices/vindication_filter/", data: { vindication_type : vindication_type, }, type: "POST", success: function(response) { $('#data').html(response); } }); }); }); </script> After button click data is send to views.py function where is processed: def vindication_filter(request): if request.method == 'POST': vindication_type = request.POST['vindication_type'] # filter data client_data = MonitoringUsers.objects.all() invoices_all_data = MonitoringUsers.objects.none() for client in client_data: if client.get_all_invoices(): invoices_all_data = invoices_all_data | MonitoringUsers.objects.filter( user_id=client.user_id, pay_status=vindication_type) return TemplateResponse(request, "template.html", locals()) To this point code is working but i con't figure how to return processed data [invoices_all_data] back into main template.html? Thank You for any sugestions. -
How to check if foreign key exists?
Here I have a model called Staff which has OneToOne relation with django User model and ForeignKey relation to the Organization model.Here while deleting the organization I want to check if the organization exists in Staff model or not .If it exists in Staff model then i don't want to delete but if it doesn't exists in other table then only I want to delete. How can I do it ? I got this error with below code: Exception Type: TypeError Exception Value: argument of type 'bool' is not iterable models.py class Organization(models.Model): name = models.CharField(max_length=255, unique=True) slug = AutoSlugField(unique_with='id', populate_from='name') logo = models.FileField(upload_to='logo', blank=True, null=True) class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='staff') views.py def delete_organization(request, pk): organization = get_object_or_404(Organization, pk=pk) if organization in organization.staff.all().exists(): messages.error(request,"Sorry can't be deleted.") return redirect('organization:view_organizations') # also tried # if organization in get_user_model().objects.filter(staff__organization=organizatin).exists(): elif request.method == 'POST' and 'delete_single' in request.POST: organization.delete() messages.success(request, '{} deleted.'.format(organization.name)) return redirect('organization:view_organizations') -
Dokerize my Django app with PostgreSQL, db start and close unexpectedly
I am new to Docker and I want to dockerise the Django app to run as a container. Followed as below. i have OSX 10.11.16 El Capitan with Docker Toolbox 19.03.01. Here is the Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Here is docker-compose.yml conf version: '3' networks: mynetwork: driver: bridge services: db: image: postgres ports: - "5432:5432" networks: - mynetwork environment: POSTGRES_USER: xxxxx POSTGRES_PASSWORD: xxxxx web: build: . networks: - mynetwork links: - db environment: SEQ_DB: cath_local SEQ_USER: xxxxx SEQ_PW: xxxxx PORT: 5432 DATABASE_URL: postgres://xxxxx:xxxxx@db:5432/cath_local command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db well atthis point i run i run: docker-compose up but my postgreSQL db seem to start and stop without Errors, if i inspect db log in docker i get: 2019-09-17 03:29:37.296 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2019-09-17 03:29:37.301 UTC [1] LOG: listening on IPv6 address "::", port 5432 2019-09-17 03:29:37.304 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2019-09-17 03:29:37.617 UTC [21] LOG: database system was shut down at 2019-09-17 03:28:33 UTC 2019-09-17 03:29:37.795 UTC [1] LOG: database system is … -
Two of my custom user models cannot fail to login
I have created 3 custom user models. However only one user under the models Users() is able to login in into a sells dashboard that I have created. I want the two user namelly, Buyer() and Supplier() to be able to login to the dashboard but not to the admin area. The following is my code. Please help me see the error. # models.py # These are my three custom models from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser, UserManager, BaseUserManager, PermissionsMixin from django.conf import settings # Superuser model class Users(AbstractUser): username = models.CharField(max_length=25, unique=True) email = models.EmailField(unique=True, null="True") objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] # Returns username def __str__(self): return self.username # Supplier user model class Supplier(AbstractBaseUser): sname = models.CharField(max_length=255, verbose_name='Supplier Name', unique=True) phone_number = models.CharField(max_length=255, verbose_name='Phone Number') email_address = models.CharField(max_length=255, verbose_name='Email Address', null=True) physical_address = models.CharField(max_length=255, verbose_name='Physical Address') description = models.TextField(max_length=255, verbose_name='Describe yourself') is_active = models.BooleanField(default=True) objects = Users() USERNAME_FIELD = 'sname' def __str__(self): return self.sname # This model save inventory of a supplier class Inventory(models.Model): pname = models.CharField(max_length=255, verbose_name='Product Name') quantity = models.PositiveIntegerField(verbose_name='Quantity (kgs)') measurement = models.CharField(max_length=255, verbose_name='Measurement') orginal_price = models.PositiveIntegerField(verbose_name='Original Price') commission = models.PositiveIntegerField(verbose_name='Commission') selling_price = models.PositiveIntegerField(verbose_name='Selling Price (MWK)') supplier = models.ForeignKey(Supplier, … -
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed: The specified module could not be found
After running any command on my project directory i got this: Traceback (most recent call last): File "C:\Python27\Lib\site-packages\django\db\backends\postgresql\base.py", line 21, in <module> import psycopg2 as Database File "C:\Python27\Lib\site-packages\psycopg2\__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python27\Lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\Lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\Lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Ga\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Python27\Lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python27\Lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "C:\Python27\Lib\site-packages\django\db\models\base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python27\Lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\Lib\site-packages\django\db\models\options.py", line 214, in … -
how can i access url from django file using webmin/virtualmin?
I have hosting server with virtualmin panel.i uploaded a django project file inside public_html folder.But i can't access my website using domain.But i can access simple html page inside public_html folder.any help is appreciated. -
Add m2m relation in Django rest framework
I need to add multiple m2m relationship between two objects in Django rest framework class Theme(models.Model): slug = models.CharField(primary_key=True, unique=True, db_index=True) menu = models.ManyToManyField(Menu, related_name='themes') class Menu(models.Model): pass Serializer class MenuAdminSerializer(serializers.ModelSerializer): themes = serializers.SlugRelatedField(many=True, read_only=False, required=False, slug_field='slug', queryset=Theme.objects.all()) class Meta: model = Menu fields = ('themes',) def create(self, validated_data): themes = validated_data.pop('themes') menu.themes.set(*themes) I pass themes like this ["one", "another"] but the error im getting is 'Theme' object is not iterable -
Could I use graphQL in django project with react?How?
I have some React project which should be loaded by django. how could I do it? -
Django views error in importing custom python files
I am trying to import main1.py file in views.py of my django app. But unable to import it. Moreover location of my main file and sub-dependent file also lies at the view.py folder location. I have tried with following options 1 import main with this error is : No module found with name main 2 from .app_name import main using this error is : import * only allowed at module level folder structure is -
How to replace threads in Django to Celery worker
I know it's not best practice use threads in django project but I have a project that is using threads: threading.Thread(target=save_data, args=(dp, conv_handler)).start() I want to replace this code to celery - to run worker with function save_data(dispatcher, conversion) Inside save_data I have infinite loop and in this loop I save states of dispatcher and conversation to file on disk with pickle. I want to know may I use celery for such work? Does the worker can see changes of state in dispatcher and conversation? -
Django queryset : How to exclude objects with any related object satisfying a condition
I stumbled upon a weird behaviour of django querysets while making a difficult query and I'd like to know if somebody knew how to improve this query. Basically I have a model like this: class Product(models.Model): pass class Stock(models.Model): product_id = models.ForeignKey(Product) date = models.DateField() initial_stock = models.SmallIntegerField() num_ordered = models.SmallIntegerField() And I'd like to select all Product that are not available for any date (means that there are no stock object related to the product which have their initial_stock field greater than the num_ordered field). So at first, I did: Product.objects.exclude(stock__initial_stock__gt=F('stock__num_ordered')).distinct() but I checked and this query translates as: SELECT DISTINCT * FROM "product" LEFT OUTER JOIN "stock" ON ("product"."id" = "stock"."product_id") WHERE NOT ("product"."id" IN ( SELECT U1."product_id" AS Col1 FROM "product" U0 INNER JOIN "stock" U1 ON (U0."id" = U1."product_id") WHERE (U1."initial_stock" > (U1."num_ordered") AND U1."id" = ("stock"."id")) )) Which makes a left join on stocks and then filters out the lines where the initial_stock is greater than the num_ordered before sending me back the distinct lines as a result. So as you can see, it doesn't work when I have a stock object that is out of stock and another stock object that is not out … -
Publish to MQTT in django Serializer save() method
I have a really simple API that uses django with restframework that act as an endpoint for iot devices. iot Devices --HTTP POST--> REST API (django) Data is validated and saved. No need for any render or GET/PATCH/DELETE at all. The only thing is that I'm not saving to database but I'd like to push to MQTT channel (other process that listen for messages will save/postprocess) As I am not a django expert at all, My idea was to override the Serializer save() method that it actually does not save but publish. MODEL class Meas(models.Model): SENSOR_TYPES = [ ('temperature','temperature'), ('humidity','humidity') ] sensorType = models.CharField(max_length=100, default='UNKNOWN', choices = SENSOR_TYPES ) sensorId = models.CharField(max_length=100) homeId = models.CharField(max_length=100) roomId = models.CharField(max_length=150) hubId = models.CharField(max_length=100) value = models.CharField(max_length=100) last_seen = models.DateTimeField() elapsed = models.IntegerField() objects = MeasManager() SERIALIZER class MeasMQTTSerializer(serializers.ModelSerializer): client = RMQPublisher(ch_name=rmq_chname,routing_key=rmq_routingkey,host=rmq_host,user=rmq_user,password=rmq_pass,port=rmq_port) class Meta: model = Meas fields = '__all__' def save(self): logging.debug("Saving measurement") measurement = self.validated_data['sensorType'] mytags = { 'sensorId' : self.validated_data['sensorId'], 'roomId' : self.validated_data['roomId'], 'hubId' : self.validated_data['hubId'], 'homeId' : self.validated_data['homeId'], 'elapsed' : self.validated_data['elapsed'], 'last_seen' : self.validated_data['last_seen'] } for a, x in mytags.items(): mytags[a]=str(x) value = float(self.validated_data['value']) rmq_msg = mytags rmq_msg['value']=value rmq_msg['measurement'] = measurement MeasMQTTSerializer.client.pushObject(rmq_msg) logging.debug("Pushed to RMQ") and RMQPublisher use just … -
Delay in updating live status from text file in django
I want to update some live status through text file on django html template. Issue is sometimes delay comes very late, not sure if this is due to linux-server dependencies or something else. Also, what is recommended location to store live logs for reading purpose, currently I am using static directory in django server. function update() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { document.getElementById("live_status").innerHTML = this.readyState; if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); x = "{{ details.chip_name }}" + "</br>"; for ( i in myObj.users ){ for ( j in myObj.users[i].live_status ){ x += myObj.users[i].live_status[j] + "</br>"; } } document.getElementById("live_status").innerHTML = x; //document.getElementById("live_status").innerHTML = "Test"; } }; xmlhttp.open("GET", "{% static 'live_status.txt' %}", true); xmlhttp.send(); } update(); setInterval(update, 10000); -
Login system which search in database in django
I have my own model and and i want to make login system which check in that model rather than default user model . Can anybody help me with this . I have been stuck in this problem for long time. I searched alot but could not find any solution. -
How to make a view as a url in templates.? (Python 3.6, Django 2.2)
These are my code #urls urlpatterns += [ path('blog/', include('blog.urls', namespace='blog')), path('products/', include('products.urls', namespace='products')), ] This is app urls # urls app_name = 'products' urlpatterns = [ path('', ProductHomeView.as_view(), name='home'), path('details/', ProductView.as_view(), name='details'), ] This is my view #views class ProductHomeView(View): def get(self, request, *args, **kwargs): product_data = Product.objects.all() context = { 'product': product_data, } return render(request, 'product_home.html', context) class ProductView(View): def get(self, request, *args, **kwargs): product_data = Product.objects.all() context = { 'product': product_data, } return render(request, 'product.html', context) this is my template # template product_home.html {% for product in product %} <h1>{{ product.tittle }}</h1> <p>{{ product.short_description }}</p> <button type="button"><a href="{% url 'products.details' %}">Explore More</a></button><br> {% endfor %} This is the error Error django.urls.exceptions.NoReverseMatch: Reverse for 'products.details' not found. 'products.details' is not a valid view function or pattern name. How do I resolve this? -
IntegrityError at /create/ (1048, "Column 'laenge' cannot be null")
While submitting my form in Django I get an IntegrityError that I can't resolve. I found other solutions to this problem where it was sugested to set null=True and blank=True. However, I don't want this field to be null=True. I submitted the form with trailform-laenge = '44', and I also printed out the cleaned data in my view which gave me 44. The DEBUG mode shows me that internaly laenge is set to Null when storing it in the database. I already reset the database and migrated the model again, but the same error still appears. views.py def create_trail(request): if request.method == 'POST': trailform = TrailForm(request.POST, request.FILES, prefix="trailform") etappeformset = EtappeFormset(request.POST, prefix="etappeformset") bildformset = BildFormset(request.POST, prefix="bildformset") if trailform.is_valid() and etappeformset.is_valid() and bildformset.is_valid(): trail = trailform.save(commit=False) trail.autor = request.user trail.save() trail = get_object_or_404(Trail, pk=trail.id) models.py class Trail(models.Model): laenge = models.DecimalField( #in Kilommeter max_digits=7, decimal_places=2, verbose_name='Streckenlänge', help_text='in Kilometern', validators=[MinValueValidator(0)] ) IntegrityError at /create/ (1048, "Column 'laenge' cannot be null") Request Method: POST Request URL: Django Version: 2.2 Exception Type: IntegrityError Exception Value: (1048, "Column 'laenge' cannot be null") Exception Location: /home/name/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py in execute, line 76 Python Executable: /usr/bin/python Python Version: 3.6.7 Python Path: ['/home/t_puetz16/django_code/stupro', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/t_puetz16/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: … -
AUTH_USER_MODEL refers to model 'auth.User' that has not been installed , how to provide default user logged in value in models.py
im trying to provide default value from models.py class OrderManager(models.Manager): def staff_rest(self ,request): return self.staff = request.user class Order(models.Model): staff = models.CharField(max_length=20 , default='') id = models.AutoField(primary_key = True) pass objects = OrderManager() but i got this error AUTH_USER_MODEL refers to model 'auth.User' that has not been installed i also tried to override same() method def save(self , *args,**kwargs): self.staff = request.user super(Order,self).save() error :name 'request' is not defined thanks for helping