Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to have a hosted Django site use the client's interfaces to create a SSH session with a local privately addressed device
I am trying to learn programming to expand my horizons a bit. I have been creating a Django app that automates several aspects of my day to day job. It would be nice if that Django app could be on a public server for accessibility but also have a view that can initiate an SSH session with various privately addressed devices, mostly to verify network changes were successful. In my mind the script would almost need to run on the client side to use their IP address within the private network but from my understanding, Django is server side. Any advice on how to work around this? -
AssertionError: You need to pass a valid Django Model in UserProfile.Meta, received "None"
I'm adding Django Model to a graphql api using the AbstractBaseUser custom user model. The Admin works fine except that I get an error when trying to access the graphql api, 'You need to pass a valid Django Model in UserProfile.Meta, received "None"' I've tried adding AUTH_USER_MODEL = 'noxer_app.MyUser' to settings, yet it doesn't work In models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password): user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') company = models.CharField(max_length=255, default='') company_reg_no = models.CharField(max_length=255, default='') address = models.CharField(max_length=400, default='') phone = models.CharField(max_length=13, default='') image = models.ImageField(default='noimage.jpg', upload_to = 'profile_pics') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'company', 'company_reg_no', 'address', 'phone', 'image'] def __str__(self): … -
Is it recommended to manually redirect sub-domains to an application from the project itself?
We have different types of users whom we'd like to redirect to different views based on the sub-domain in the URL. In our project directory, we examine each and every request for the sub-domain keywords, viz. ut1.domain or ut2.domain. Is this a good solution? If not, please suggest something better. User Type 1 ut1.domain.com/login/ User Type 2 ut2.domain.com/login/ This is how the sub-domains are being planned to be handled. def handle_urls(request): if "ut1.domain." in request.build_absolute_uri(): return HttpResponseRedirect('login/') context = {} return render(request, "home.html", context) The purpose of the sub-domains is to point to different applications in the same project. We expect to add more than a dozen sub-domains in the next few months for various new applications. Thank you for your time reading this. -
how to perform count for a secod foreign key in django?
i have three models Category,Post,Comment class Category(models.Model): class Meta: verbose_name_plural = "Categories" COLOR_CHOICES = ( ('primary', 'Blue'), ('success', 'Green'), ('info', 'Sky Blue'), ('warning', 'Yellow'), ('danger', 'Red') ) title = models.CharField(max_length=250, unique=True) description = models.CharField(max_length=250) slug = models.SlugField(max_length=200,) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) color = models.CharField( max_length=20, default='primary', choices=COLOR_CHOICES) class Post(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) title = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) slug = models.SlugField(max_length=200,) status = models.BooleanField(default=False, choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) class Comment(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True, choices=STATUS_CHOICES) i want to perform a query set to get categories and number of comments of each category, i cant find a good way. i already know how to count posts for each category using annotate. i tried : categories = Category.objects.annotate(nb_comments=Count('post__comment')) -
Django apache2 KeyError for SECRET_KEY with environment variable
I try to deploy django on a debian server. To protect the secret key i store them in a environment variable. I edit /etc/profile an add: SECRET_KEY="123456789...."; export SECRET_KEY I tested if the variable is set with printenv | grep SECRET_KEY and echo $SECRET_KEY. It works fine but if i open the website i get Forbidden You don't have permission to access / on this server. and in the error.log from apache: .... raise KeyError(key) from None [Tue Sep 17 14:11:20.062194 2019] [wsgi:error] [pid 13523:tid 140622223152896] [client 123.456.78.910:50361] KeyError: 'SECRET_KEY' .... Why django can't read the environment variable? -
why am I getting a none value in my method inside of my model with nested if?
I'm new in django trying to do a project of management of a small restaurant, in my consummation model,I have attributes that are foreign keys, and the date of consummation, now I try to calculate the sum of those attributes in a method inside the model by returning the total. I tried class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) class Facture(models.Model): consommation = models.OneToOneField(Consommation, models.CASCADE, null=True, blank=True, verbose_name='Facture') fait_le = models.DateField(default=timezone.now, editable=False) is_regle = models.BooleanField(default=False, verbose_name='Est regle') initials_caissier = models.CharField(max_length=5, verbose_name='Initiales du Caissier') def __str__(self): return 'Facture du :' + ' ' + str(self.fait_le) def get_absolute_url(self): return reverse('clients:facture_detail', kwargs={'pk': self.pk}) def net_a_payer(self): if self.consommation: if not self.consommation.entree: self.consommation.entree.price = int(0) if not self.consommation.food: self.consommation.food.price = int(0) if not self.consommation.dessert: self.consommation.dessert.price = int(0) if not self.consommation.boisson: self.consommation.boisson.price = int(0) if not self.consommation.autres: self.consommation.autres.price = int(0) return self.consommation.entree.price + self.consommation.food.price + self.consommation.dessert.price + self.consommation.boisson.price + self.consommation.autres.price net_a_payer: means the total sum to pay I expect the result to be the sum of the attibutes instead of … -
Creating a generic search view in Django
I am struggling to create my custom generic view in django to easily create search pages for certain models. I'd like to use it like this: class MyModelSearchView(SearchView): template_name = 'path/to/template.html' model = MyModel fields = ['name', 'email', 'whatever'] which will result in a view that returns a search form on GET and both form and results on POST. The fields specifies which fields of MyModel will be available for a user to search. class SearchView(FormView): def get_form(self, form_class=None): # what I'v already tried: class SearchForm(ModelForm): class Meta: model = self.model fields = self.fields return SearchForm() def post(self, request, *args, **kwargs): # perform searching and return results The problem with the code above is that form will not be submitted if certain fields are not be properly filled. User should be allowed to provide only part of fields to search but with the code I provided the form generated with ModelForm prevents that (for example because a field in a model cannot be blank). My questions are: Is it possible to generate a form based on a model to omit this behaviour? Or is there any simpler way to create SearchView class? I don't want to manually write forms if … -
How to redirect to previous page after language changing?
When I am trying to use next it doesn't work because in next-url there are old language code so language doesn't change. my template: <a href="{% url "set_language_from_url" user_language="en" %}?next={{request.path}}">en</a> <a href="{% url "set_language_from_url" user_language="ru" %}?next={{request.path}}">ru</a> my url: path('language-change/<user_language>/', views.set_language_from_url, name="set_language_from_url"), my view: def set_language_from_url(request, user_language): translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language redirect_to = request.POST.get('next', request.GET.get('next', '/')) return redirect(redirect_to) -
Run multiple Django application on mutilple subdomains with nginx and Gunicorn
I want to run multiple sites on the same instance of EC2. I configured my site as per this doc. I have two projects: 1. project_1 2. project_2 project_1 on beta.example.com project_2 on api.example2.com I am running project_1 successfully with Nginx and gunicorn and want to add project_2. I have tried this answer but is not working. -
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?