Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to categorize content in Django ? Where is the problem with my work?
I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes. #urls path('category/<slug:slug>', views.category, name="category") #views def category(request, slug): context = { "categorys": get_object_or_404(Category, slug=slug, status=True) } return render(request, "blog/category.html", context) #models class PostManager(models.Manager): def published(self): return self.filter(status='p') class Category(models.Model): title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") status = models.BooleanField( default=True, verbose_name="آیا نمایش داده شود؟") position = models.IntegerField(verbose_name="پوزیشن") class Meta: verbose_name = "دسته بندی" verbose_name_plural = "دسته بندی ها" ordering = ['position'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = [ ('d', 'پیش نویس'), ('p', 'منتشر شده'), ] title = models.CharField(max_length=100, verbose_name="عنوان") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") category = models.ManyToManyField( Category, verbose_name="دسته بندی", related_name="postcat") description = models.TextField(verbose_name="توضیحات") thumbnail = models.ImageField( upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر") publish = models.DateTimeField( default=timezone.now, verbose_name="زمان انتشار") created = models.DateTimeField( auto_now_add=True, verbose_name="زمان ایجاد") updated = models.DateTimeField( auto_now=True, verbose_name="زمان بروزرسانی") status = models.CharField( max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت") def __str__(self): return self.title class Meta: verbose_name = "پست" verbose_name_plural = "پست ها" objects = PostManager() #template {% for posts in categorys.postcat.published %} <p> posts.title </p> <p> posts.description </p> {%endfor%} The problem is that despite the filter I have set … -
Django - page not found with VueJS
I'm trying to create a SPA with Vue in my Django project, so that Django handles only authentication templates and the rest of the frontend is entirely Vue rendered by webpack-loader, so it's Django rendering the Vue app. I'm doing this in order not to lose the benefits of having authentication handled entirely by Django. So everything below /accounts/ will be handled by Django templates rendered by django views, while everything below /app/ will be handled by the Vue application. I have the following: urlpatterns = [ # Some standard django templates url here for authentication.. # ... # The Vue app: path('app/', views.vueApp, name='vueApp'), ] So when the user navigates to mysite.com/app, Vue will handle the whole frontend as a SPA with its routes: //main.js const router = new VueRouter({ base: '/app', mode: 'history', routes: [ { path: '/', component: Home }, { path: '/test1', component: testcomponent }, { path: '/test2', component: test2component } ] }) The problem with my code, is that if i click on a link to test1 or to test2 from inside the Vue app, i will get redirected to testcomponent (mysite.com/app/test1) and test2component (mysite.com/app/test2); instead, if i open my browser and i navigate directly … -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed when receiving webhook
I'm using dj-paddle for subscription payments in my django app and i'm experiencing a strange problem. After making the payment for a subscription plan, the subscription_created webhook from paddle.com isn't received in my app and i get this error on console. sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/views.py", line 60, in post signal.send(sender=self.__class__, payload=payload) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/models.py", line 214, in on_subscription_created Subscription.create_or_update_by_payload(payload) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/models.py", line 193, in create_or_update_by_payload return cls.objects.update_or_create(pk=pk, defaults=data) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 585, in update_or_create obj.save(using=self.db) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/transaction.py", line 232, in __exit__ connection.commit() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/asyncio.py", … -
django.urls.exceptions.NoReverseMatch: Reverse for 'board_topics' with arguments '('',)' not found
i am struggling with this error, please any help, i tried many solution for this error but nothing work views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,Http404 from .models import Board # Create your views here. def home(request): boards = Board.objects.all() return render(request,'home.html',{'boards':boards}) def board_topics(request,board_id): # try: # board = Board.objects.get(pk=board_id) # except: # raise Http404 board = get_object_or_404(Board,pk=board_id) return render(request,'topics.html',{'board':board}) def new_topic(request,board_id): return render(request,'new_topic.html') def about(request): return HttpResponse(request,'yes') url.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('about/',views.about,name='about'), path('boards/<int:board_id>/', views.board_topics, name='board_topics'), path('boards/<int:board_id>/new/', views.new_topic, name='new_topic') ] new_topic.html {% extends 'base.html' %} {% block title %} creat new topic {% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"> <a href="{% url 'home'%}"> Boards </a> </li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}"> {{board.name}} </a> </li> <li class="breadcrumb-item active">New Topic</li> {% endblock %} Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated. -
Get a list of all the field values from a Foreign Key Table in Django
am new to Django and currently trying the Foreign Key concept. I have three models as shown below. class Basket(models.Model): basket_name = models.CharField(max_length=5, unique=True) def __str__(self): return self.basket_name class Product(models.Model): Grams = 'GM' Kilograms = 'KG' WeightBased = 'WPG' QuantityBased = 'CPG' PRODUCT_UNIT_WT_CHOICES=[ (Grams, 'Grams'), (Kilograms, 'Kilograms') ] PRODUCT_TYPE_CHOICES =[ (WeightBased, 'Weight Based Product'), (QuantityBased, 'Quantity Based Product') ] product_name = models.CharField(max_length=30, unique=True) product_description = models.TextField(max_length=300) product_price = models.DecimalField(max_digits=5, decimal_places=2) product_unit_weight = models.DecimalField(max_digits=5, decimal_places=2) product_unit_weight_units = models.CharField(max_length=2, choices=PRODUCT_UNIT_WT_CHOICES, default=Grams) product_type = models.CharField(max_length=3, choices=PRODUCT_TYPE_CHOICES, default=QuantityBased) product_image = models.ImageField(upload_to=imageUploadPath, null=True, blank=True) def __str__(self): return self.product_name class BasketProductMapping(models.Model): basket_reference = models.ForeignKey(Basket, on_delete=models.CASCADE) product_reference = models.ForeignKey(Product, on_delete=models.CASCADE) mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) Here are my serializers: class ProductSerializer(serializers.ModelSerializer): product = serializers.CharField(read_only=True) class Meta: model = Product fields = ['id', 'product_name', 'product_description', 'product_price', 'product_unit_weight', 'product_unit_weight_units', 'product_type', 'product_image'] class BasketSerializer(serializers.ModelSerializer): basket = serializers.CharField(read_only=True) class Meta: model = Basket fields = ('id', 'basket_name') class BasketProductMappingSerializer(serializers.ModelSerializer): basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True) product_reference = serializers.CharField(source='product.product_name', read_only=True) class Meta: model = BasketProductMapping fields = ['id', 'basket_reference', 'product_reference', 'mapped_basket_name', 'mapped_product_name'] What I am trying to achieve is get a list of all the values in 'basket_name' and 'product_name' when I call the BasketProductMappingSerializer. But the output I … -
Django F() and ExpressionWrapper
I am trying to avoid DB hits on my views.py. If I used the F() and ExpressionWrapper, Am I doing a query on the database. I am trying to optimize my code and kind of confused when I read the documentation. Views.py from django.shortcuts import render from django.db.models import F, Q, Count, Sum, ExpressionWrapper, IntegerField from .models import Student, Subject, Enrollment def home(request): student = Student.objects.all() subject = Subject.objects.all() sem_score = Enrollment.objects.all().update(sem_score=ExpressionWrapper((F("prelim_score") + F("midterm_score") + F("final_score"))/3, output_field=IntegerField())) enrollment = Enrollment.objects.all() num_student = Enrollment.objects.all().count() context = {"student":student, "subject":subject, "enrollment":enrollment, "num_student":num_student} return render(request, 'core/home.html', context) -
How to categorize content in django ? Where is the problem with my work?
I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes. #urls path('category/<slug:slug>', views.category, name="category") #views def category(request, slug): context = { "categorys": get_object_or_404(Category, slug=slug, status=True) } return render(request, "blog/category.html", context) #models class PostManager(models.Manager): def published(self): return self.filter(status='p') class Category(models.Model): title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") status = models.BooleanField( default=True, verbose_name="آیا نمایش داده شود؟") position = models.IntegerField(verbose_name="پوزیشن") class Meta: verbose_name = "دسته بندی" verbose_name_plural = "دسته بندی ها" ordering = ['position'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = [ ('d', 'پیش نویس'), ('p', 'منتشر شده'), ] title = models.CharField(max_length=100, verbose_name="عنوان") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") category = models.ManyToManyField( Category, verbose_name="دسته بندی", related_name="postcat") description = models.TextField(verbose_name="توضیحات") thumbnail = models.ImageField( upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر") publish = models.DateTimeField( default=timezone.now, verbose_name="زمان انتشار") created = models.DateTimeField( auto_now_add=True, verbose_name="زمان ایجاد") updated = models.DateTimeField( auto_now=True, verbose_name="زمان بروزرسانی") status = models.CharField( max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت") def __str__(self): return self.title class Meta: verbose_name = "پست" verbose_name_plural = "پست ها" objects = PostManager() #template {% for posts in categorys.postcat.published %} <p> posts.title </p> <p> posts.description </p> {%endfor%} The problem is that despite the filter I have set … -
Django Views.py If else statement not working
This is my html page <div class="col-md-4 col-sm-12 col-xs-12"> <input type="radio" class="avg radioalign" id="DocDetails1" name="DocDetails" value="1" checked> <span class="RadioSpan">New Documents</span> <input type="radio" class="avg radioalign" id="DocDetails2" name="DocDetails" value="2"> <span class="RadioSpan">New Versions</span> <div id="AverageHours" class="col-md-12 box borderFrame make-it-slow"></div> </div> This is my ajax $(".avg").click(function() { var x = $(this).val() alert(x); $.ajax({ url : "{% url 'AverageHours' %}", data : { Id : x }, success : function(response) { alert("hy"); } }); }) This is my views.py def AverageHours(request): ID = request.GET.get('Id'); if ID == '1': AgeingCheckOutQuery = connection.cursor() AgeingCheckOutQuery.execute("""select 10,20,30,40""") Results = AgeingCheckOutQuery.fetchall() return render(request,"Dashboard/Documents/AverageHours.html",{'values': Results}) else : NewVersion = connection.cursor() NewVersion.execute("""select 10,80,20,10""") Results1 = NewVersion.fetchall() return render(request,"Dashboard/Documents/AverageHours.html",{'values': Results1}) When I Click the radio button ajax value is passed but the if condition directly goes to else part it does get the value when i return back the getting value to html page it return null value -
How to set multiple values with additional field in django models?
I have a model with represents a many to many table. class WasteFacilityMaterialType(models.Model): waste_facility = models.ForeignKey( WasteFacility, on_delete=models.CASCADE, related_name="waste_facility_material_type", ) material_type = models.ForeignKey( MaterialType, on_delete=models.CASCADE, related_name="material_type_waste_facility", ) cost_per_ton = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: db_table = "waste_facility_material_type" unique_together = [["waste_facility", "material_type"]] How can I add records to this table when inserting/updating with additional field cost_per_ton so that when a object of material_type is removed from the request the records should be also removed from the table. Basically how to achieve sync of many many to records with additional fields. My request looks something like this: { "name":"Dade Waste Facility", "email":"pritamk@gobiggi.com", "mobile":"3054014181", "street":"Street 1", "city":"Miami", "zipcode":"33161", "state":"Florida", "material_types": [{ "name": "Metal", "cost_per_ton": 20 }, { "cost_per_ton": 50, "name": "Food" }] } -
STATIC files problem during heroku deployment of Django web app
I am trying to deploy my Django web app but I'm getting some errors. I followed some tutorials but they did not help. Also, I have all the necessary files like Procfile, requirements.txt. Even I tried to change STATIC_ROOT to staticfiles and static it did not make sense FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_4dca6fca/static' Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets Push rejected, failed to compile Python app. Push failed settings.py DEBUG = False MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # added whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Procfile web: gunicorn portfolio.wsgi --log-file - -
Django Azure Active Directory Authentication
I am developing in Django and I'm trying to authenticate with Azure Active Directory. I've been trying for several days to get it to work, but have had a lot of problems. The package that I'm using is: django_microsoft_auth (https://django-microsoft-auth.readthedocs.io/en/latest/index.html). Operating system: Windows 10 64 bits. Django version: 3.1 Python version: 3.7.9 The problems that I have in this moment are: I have already done all the configuration in Azure and I think that it is correct. I looked at the audit logs in Azure and I can see that the connection was successful. The problem is that when I log into Azure Active Directory, I don't see any response in Django. When I try to execute the package test site I have the error 404, after having run: python -m tests.site runserver I saw the project and I can't see the file views.py. Could it be because it was done in an old version of Django? Anyway I tried to run it in django 2.2 I got the same problem. Can someone make a detailed explanation (Por example a video en Youtube or a good explication here) of how to use all the functionalities such as login, logout, user … -
Is there an HTML sanitizer library for django to block injection attacks?
I'm trying to find something that will return an exception upon finding anything that even remotely looks like HTML or Javascript. I've figured out how to do it for individual views, but it's not a scalable solution, and ultimately I need to prevent code from being saved to the database no matter what view gets targeted by the injection attack. Here is the functionality I'm looking for. ILLEGAL_CHARS = '<>[]{}():;,'.split() # bunch of code in between for value in [company_name, url, status, information, lt_type, company_source]: if any(char in value for char in ILLEGAL_CHARS): raise Exception(f"You passed one of several illegal characters: {ILLEGAL_CHARS}") I'm using django rest framework so I have to handle it on the backend. Thanks. -
Attribute Error when running Django DetailView
class results(DetailView): model = Location template_name = 'results.html' def get_object(self, **kwargs): context = super(results, self).get_context_data(**kwargs) query = self.request.GET.get('q') context.update({ 'location': Location.objects.filter(name__icontains=query) }) return context The above function aims at getting the user's input string and display it in DetailView after filtering. However, when I run it, the following error message is generated: AttributeError at /collector/results/ 'results' object has no attribute 'object' Request Method: GET Request URL: http://127.0.0.1:8000/collector/results/?q=Hong+Kong Django Version: 3.1.7 Exception Type: AttributeError Exception Value: 'results' object has no attribute 'object' Do anyone know what causes the error, and how to fix the code. Thanks! -
In django-rest-framework what is the best and secure auth library
I am working on a web app which needs auth. I know that django-rest-knox supports multiple devices at the same time but is it secure? If not which is the most secure library. Also: Is JWT secure? -
Serializer is displaying id instead of field names with Foreignkey
I'm building a Django app which uses django rest framework and it shows the lists of buses in between two stops given by the user. For this purpose, I wanted to produce a json output as shown below. [ { "id": 1, "start_time": "09:48:52", "end_time": "09:48:53", "start_stop": "A", "end_stop": "B", "bus_in_route": "Bus1" }, { "id": 2, "start_time": "10:00:00", "end_time": "10:10:00", "start_stop": "B", "end_stop": "C", "bus_in_route": "Bus2" } ] But I'm getting the output in the form of IDs. The field values in the child models (Bus, BusStop) are replaced with their IDs. [ { "id": 1, "start_time": "09:48:52", "end_time": "09:48:53", "start_stop": 1, "end_stop": 2, "bus_in_route": 1 }, { "id": 2, "start_time": "10:00:00", "end_time": "10:10:00", "start_stop": 2, "end_stop": 3, "bus_in_route": 1 } ] Code: models.py class BusStop(models.Model): # model to store several bus stops stop_name=models.CharField(max_length=255) def __str__(self): return str(self.stop_name) class Bus(models.Model): # model to store names of several buses bus_name=models.CharField(max_length=255) def __str__(self): return self.bus_name class Meta: verbose_name = 'Bus' verbose_name_plural = 'Buses' class BusRoute(models.Model): # lists out routes with start and end stops with the bus running between the stops start_stop = models.ForeignKey(BusStop, related_name='start_stop', on_delete=models.CASCADE) end_stop = models.ForeignKey(BusStop, related_name='end_stop', on_delete=models.CASCADE) bus_in_route = models.ForeignKey(Bus, related_name='bus_in_route', on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() … -
how to make Mutation by graphene-django when there are no input, output?
when user click button, I want to update A(Stock) DB by using data from B(Account) DB. when user click button, django get data(company_id and company_secret) From Account DB. and then web scraping with data. it makes new data. i want to just save new data to Stock DB. I don't want to give data to web. below code show error "GetStockMutation fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping." import graphene from .types import AccountType, StockType from .models import * from .crypt import AESCipher from graphql_jwt.decorators import login_required from .views import getStockNamu class GetStockMutation(graphene.Mutation): @login_required def mutate(self, info, **kwargs): if info.context.user.is_authenticated: user_id = info.context.user.id #data from Account DB account = Account.objects.get(user_id=user_id, company=1) #decrypt company_id = AESCipher().decrypt_str(account.company_id) company_secret = AESCipher().decrypt_str(account.company_secret) # web scraping code, amount = getStockNamu(company_id, company_secret) #save it to Stock DB stock = Stock.objects.create(user_id=user_id, code=code, amount=amount, company=1) stock.save() print(stock) else: raise PermissionError("로그인이 필요합니다.") class Query(object): pass class Mutation(graphene.ObjectType): get_account = GetaccountMutation.Field() get_stock = GetStockMutation.Field() -
Django Rest Framework: Use URL parameter in serializer
My goal is to use a URL parameter as a variable in a function and output it in the serializer. But the following solution doesnt work. Anybody know why? The URL looks like this: http://127.0.0.1:8000/v1/water-bodies/?from=2013-02-17&to=2013-02-18 models.py class Application(models.Model): """Database models for application information""" name = models.CharField(max_length=255) machine_name = models.SlugField(max_length=255, allow_unicode=True) description = models.TextField(blank=True, null=True) indice_to_use = models.ForeignKey('Indice', on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return self.name views.py class DetailView(APIView): def get_serializer_context(self): context = super().get_serializer_context() context["date_from"] = self.kwargs['from'] return context def get(self, request, machine_name): application = Application.objects.get(machine_name=machine_name) serializer = OsdSerializer(application) return Response({"Everything you need to analyzing "+application.name: serializer.data}) serializer.py class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer(source='indice_to_use.needed_bands', many=True) satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use') indice = IndiceSerializer(source='indice_to_use') def get_alternate_name(self, obj): date_from = self.context["date_from"] '''make some additional voodoo with the date_from''' class Meta: model = Application fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'date_from', ] -
Django - creating model instance when user is created
First of all I found some previous solutions but they are pretty outdated and not really recommended for current version of Django. What I want to do is I have a watchlist model which is bound to user by foreign key relation, what I would like to is to create a watchlist every time a user is created so it is automatically bound to the said user. I have some models and model managers but I really don't know how to connect them and would appreciate some help. I've tried a few things already but all ended up creating users but not watchlists. class UserMananger(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """create and save new user""" if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user class User(AbstractBaseUser, PermissionsMixin): """User model""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserMananger() USERNAME_FIELD = 'email' class WatchlistManager(models.Manager): """manage creating watchlists""" def create_watchlist(self, user): watchlist = self.create(user=user) watchlist.save() return watchlist class Watchlist(models.Model): """Watchlist model""" watchlist_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) products = models.ManyToManyField('Product') def __str__(self): return f'{self.watchlist_id} {self.user}' -
Django - page not found with Vue urls
I'm trying to create a SPA with Vue in my Django project, so that Django handles only authentication templates and the rest of the frontend is entirely Vue. I have the following: urlpatterns = [ # Some standard django templates url here for authentication.. # ... # The Vue app: path('app/', views.vueApp, name='vueApp'), ] So when the user navigates to mysite.com/app, Vue will handle the whole frontend as a SPA with its routes: //main.js const router = new VueRouter({ base: '/app', mode: 'history', routes: [ { path: '/', component: Home }, { path: '/test1', component: testcomponent }, { path: '/test2', component: test2component } ] }) The problem with my code, is that if i click on a link to test1 or to test2 from inside the Vue app, i will get redirected to testcomponent (mysite.com/app/test1) and test2component (mysite.com/app/test2); instead, if i open my browser and i navigate directly to mysite.com/app/test1 or mysite.com/app/test2 i will get a Page Not Found error by Django, i think because Django thinks i'm trying to reach a standard Django url, while instead i'm trying to reach an URL handled by my Vue app. Is there any way to solve this? Thanks in advance! -
join two table and show combined result in Django with pre defined tables in MySQL database
I have pre defined tables- functions and resources in MySQL database. I am able to connect to these individual tables separately in django but I want to join these tables based on function_id and show the combined result. [python functions defined under models.py in app][1] [python function defined under views.py in app][2] [html defined for GUI in app][3] I tried with foreign key but getting error as shown below. [enter image description here][4] PLEASE PROVIDE SOLUTION FOR JOINING TABLES AND VIEWING THE COMBINED TABLE RESULT [1]: https://i.stack.imgur.com/BDul4.png [2]: https://i.stack.imgur.com/jHfdA.png [3]: https://i.stack.imgur.com/z3Td0.png [4]: https://i.stack.imgur.com/mc9IZ.png -
Fetch all instances which have same foreign key (Migrating from Foreign Key to OneToOne)
I have two models as mentioned below: class ModelA: parent_type = CharField() # This tells us which parent is not Null parent_b = ForeignKey(to=ModelB, null=True, blank=True, related_name="child") parent_c = ForeignKey(to=ModelC, null=True, blank=True, related_name="child") parent_d = ForeignKey(to=ModelD, null=True, blank=True, related_name="child") class ModelB: data = CharField() class ModelC: data = CharField() class ModelD: data = CharField() So, recently what happend was I was trying to fetch ModelA instance where parent_b was equal to instance_b: ModelA.objects.get(parent_b=instance_b) But there were multiple instances present and hence the error (get returned 2!) So, I decided to make all parent field as OneToOne field but for that I would need to remove all the duplicate instances in ModelA. How can I achieve that, just give an example for a single parent, I can replicate it for others. Iterating through all instances will not be possible with amount of data I have. -
How do I create a child within a value in key value pair in pyrebase?
I want my data in the database to look like this >key -val1 -val2 -val3 > val_key - val4.1 - val4.2 I have added the values val1, val2,val3 using the set() but I cannot seem to figure out a way to create a key val_key as a child to the key. Please help. -
Custom decorator on class based views in django rest framework
I have the following models in my application class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) employee_name = models.CharField(max_length=500, default=0) employee_email = models.EmailField(max_length=500, default=0) employee_phone = models.CharField(max_length=500, default=0) employee_city = models.CharField(max_length=500, default=0) employee_role = models.CharField(max_length=100, default='View') class GroupModels(models.Model): model_coices = (('Product', 'Product'), ('Kit', 'Kit'), ('Vendor', 'Vendor'), ('Warehouse', 'Warehouse') , ('Flow', 'Flow'), ('ReceiverClient', 'ReceiverClient')) models = models.CharField(max_length=500, default=0, choices=model_coices) class Group(models.Model): name = models.CharField(max_length=500, default=0) emp = models.ForeignKey(Employee, on_delete=models.CASCADE) models = models.ManyToManyField(GroupModels) This is an attempt to create custom permissions for every Employee to do something Now I have the following View to create Product class ProductCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer def post(self, request, *args, **kwargs): owner = request.user.pk d = request.data.copy() d['owner'] = owner serializer = ProductSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) o = Product.objects.get(id=serializer.data['id']) ow = User.objects.get(id=owner) Inventory.objects.create(product=o, quantity=0, owner=ow) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How do I create a decorator to give access of this function to only those employees who have Product in the Group model? -
Django model field through linked relationship
Is there a way to create a "virtual" field in a model linked to a field in a relationship? e.g. I have: class User(models.Model): organization = models.ForeignKey( "Organization", ... ) Organization model have a field name so I want to add a virtual field in User model (e.g organization_name) to be able to do user.organization_name instead of user.organization.name is it possible? -
Disaply Django Fieldset values according to previously selected option?
I'm using Django's built-in Admin functionality to support a web app's admin users. So far I'm also using mixins and "rest_framework - viewsets" library to have automated a generic CRUD API. In my admin.py files, I've used fieldsets to easily create a nice form to add new records with automatically included dropdowns, checkboxes, dateboxes etc. Great. A recent concern is that some of these some item selections should dictate the available options of other items. For example, if a person selects a state/province, the list of available cities should be restricted to those in just that state/province, instead of all the cities in the database. Is there any way to implement this behavior within the fieldsets syntax / without having to abandon viewsets and revert to manually coding this behaviour?