Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Related model 'auth_app.User' cannot be resolved
after runnig these commands, i found this problem python manage.py makemigrations python manage.py migrate valueError: Related model 'auth_app.User' cannot be resolved. what is auth_app? -
How to execute my code in RunPython Django?
I wrote this code in the new file, I want to run it. How to do it? I read and follow the documentation, but did not really understand... Thanks. def forwards_func(apps, schema_editor): product = apps.get_model("landings", "Product") merchant = apps.get_model("landings", "Merchant") partner = apps.get_model("landings", "Partner") operator = apps.get_model("landings", "Operator") db_alias = schema_editor.connection.alias partner = partner.objects.using(db_alias).filter(name="binding") merchant = merchant.objects.using(db_alias).filter(name="dc") operator = operator.objects.using(db_alias).bulk_create([ operator(name="megafon") ]) product.objects.using(db_alias).bulk_create([ product(name="mirrorcheck", merchant=merchant, mnp_service_name_card="tg_247_mirrorcheck_refund", partner=partner, operator=operator, has_many_subs=True, category='retail', definition={"sms": { "text": "" ]) def reverse_func(apps, schema_editor): operator = apps.get_model("landings", "Operator") product = apps.get_model("landings", "Product") db_alias = schema_editor.connection.alias operator.objects.using(db_alias).filter(name="megafon") product.objects.using(db_alias).filter(name="mirrorcheck", operator=operator).delete() operator.delete() class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(forwards_func, reverse_func), ] -
Django serializer not showing child model fields
I am having an issue with my serializer not returning the fields from a child model when using the model serializer inside another serializer (foreign key relation). I am not looking for a solution to this, but rather why it is not working. models.py class LinkedinAccount(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField(auto_now_add=True) is_prospect = models.BooleanField(default=False) class LinkedinProspectAccount(LinkedinAccount): title = models.CharField(max_length=255, blank=True) company = models.CharField(max_length=100, blank=True) country = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) serializers.py class LinkedinAccountSerializer(serializers.ModelSerializer): class Meta: model = user_account.models.LinkedinAccount fields = ('id', 'name') read_only_fields = ('date_created',) class LinkedinProspectAccountSerializer(serializers.ModelSerializer): class Meta: model = user_account.models.LinkedinProspectAccount fields = ('title', 'company', 'country', 'city') read_only_fields = ('date_created',) class ConversationSerializer(serializers.ModelSerializer): linkedin_account = user_account.serializers.LinkedinAccountSerializer() last_message = MessageSerializer() prospect = user_account.serializers.LinkedinProspectAccountSerializer() class Meta: model = conversation.models.Conversation fields = ('id', 'linkedin_account', 'prospect', 'conversation_id', 'archived', 'last_message') lookup_field = None read_only_fields = ('created_at', 'updated_at',) What I am getting back from a normal GET request using generics.ListCreateAPIView is: [OrderedDict([('id', 1), ('linkedin_account', OrderedDict([('id', 1), ('name', 'Test LinkedIn account')])), ('prospect', OrderedDict()), ('conversation_id', '100'), ('archived', False), ('last_message', None)])] The prospect object has no fields, if I add the base model fields in the serializer they are returned, but still none of the child model fields. When using the LinkedinProspectAccountSerializer … -
Django Model Meta changes throws error on changing Meta attributes
I had the below Django model, with managed = False, now I needed to change it to managed = True and also add a char field of attribute choice Version 1 class TblHoldings(models.Model): item_code = models.CharField(unique=True, max_length=5) product_name = models.CharField(max_length=45) service_provider = models.ForeignKey(TblHoldingsServiceProviders,on_delete=models.CASCADE, related_name='service_provider',db_column='service_provider') account_details = models.CharField(max_length=100) purchase_cost = models.IntegerField() current_value = models.IntegerField() power_of = models.CharField(max_length=45, blank=True, null=True) purchase_date = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) def __str__(self): return self.product_name + ' at ' + self.service_provider.provider_name class Meta: verbose_name = 'Holding' verbose_name_plural = 'Holdings' managed = False db_table = 'tbl_holdings' Version 2 FIN_GOAL_TERM =( ('L', 'Long Term 7+ years'), ('M', 'Medium Term 3-7 years'), ('S', 'Short Term <2 years'), ) class TblHoldings(models.Model): item_code = models.CharField(unique=True, max_length=5) product_name = models.CharField(max_length=45) service_provider = models.ForeignKey(TblHoldingsServiceProviders,on_delete=models.CASCADE, related_name='service_provider',db_column='service_provider') account_details = models.CharField(max_length=100) purchase_cost = models.IntegerField() current_value = models.IntegerField() power_of = models.CharField(max_length=45, blank=True, null=True) purchase_date = models.DateTimeField(blank=True, null=True) goal_term = models.CharField(max_length=40, choices=FIN_GOAL_TERM) updated_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) def __str__(self): return self.product_name + ' at ' + self.service_provider.provider_name class Meta: verbose_name = 'Holding' verbose_name_plural = 'Holdings' managed = True db_table = 'tbl_holdings' Now I get the below error, can anyone suggest how to solve this ?? OperationalError at /admin/app_fin/tblholdings/ (1054, "Unknown … -
Django render() not passing variable to template?
def get_queryset(self): ... #days = {day1 : [[FreetimeStart, FreetimeEnd], [[Meeting1Start, Meeting1End], ...]], ...} days = {} for i in range(len(compilation)): days[daylist[i]] = compilation[i] print(days) return render(self.request, 'calendar.html', {"days":days}) Above (with nonrelevant code omitted) is a function from a Django view I've been writing. It's supposed to send the days dictionary over to the template calendar.html (shown below), but it's not- I've confirmed via the print(days) statement that days is being generated properly and that the function is being called. I'm not getting any errors, either. {{ days }} <table> <tr> {% for key in days %} <th> {{ key }} </th> {% endfor %} </tr> <tr> {% for value in days.values %} <td> {% if value.0 %} Free time: {{ value.0.0 }} to {{ value.0.1 }} {% else %} Free time: None {% endif %} </td> {% endfor %} </tr> <tr> {% for value in days.values %} <td> {% for meeting in value.1 %} Meeting from {{ meeting.0 }} to {{ meeting.1 }}</br> {% endfor %} </td> {% endfor %} </tr> </table> -
Can anyone suggest me how to use websocket to receive data from android client?
I tried it using python socket programming but it doesn't work. -
Django Ajax CSRF verification failed
Here is my class, extending from from django.views.generic import View: class ClassView(ProtectedView, View): def __init__(self): self.client = get_default_client() def get(self, request, item_remove, item_replacement): ... code ... return JsonResponse(data) def post(self, request, item_remove, item_replacement): ... code ... return JsonResponse({}) ProtectedView mixin: @method_decorator(login_required, name='dispatch') @method_decorator(superuser_required, name='dispatch') class ProtectedView(object): def dispatch(self, *args, **kwargs): return super(ProtectedView, self).dispatch(*args, **kwargs) Ajax call : this.utils._ajax({ method: 'post', url: `/api/shortage/${this.item_remove}/${this.item_replacement}`, data: { item_type: 'product_bundle', delivery: productBundles, } }) Ajax object : _ajax(req) { const csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } this.$.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); const ajax$ = this.$.ajax({ url: req.url, dataType: 'json', method: req.method, data: req.data, xhrFields: { withCredentials: true }, }); return ajax$; } Headers in request { 'Content-Length':'50', 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'Host':'localhost:8000', 'Connection':'keep-alive', 'Accept':'application/json, text/javascript, */*; q=0.01', 'Origin':'http://localhost:8000', 'X-Csrftoken':'QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9', 'X-Requested-With':'XMLHttpRequest', 'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Mobile Safari/537.36', 'Sec-Fetch-Site':'same-origin', 'Sec-Fetch-Mode':'cors', 'Referer':'http://localhost:8000/admin/shortage', 'Accept-Encoding':'gzip, deflate, br', 'Accept-Language':'en-US,en;q=0.9', 'Cookie':'csrftoken=QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9; pnctest=1; logglytrackingsession=37c9453d-1b2c-443d-9a8e-167c8576cb8b; sessionId=68a017ab-a1d5-43a3-93c3-4df44b3851c3; sessionid=zl2k7hwechu0uprq4tqw66znc91op5ua' } CSRF Token is clearly contained in headers, but still, the method always return (403) CSRF verification failed Any idea to fix this issue? Thanks. -
Django Client.get() in TestCase returns TypeError from django.utils.cache
I'm attempting to write a unit test for a url in my application. I used django's Client class to simulate a get() request and compare the response's status code. Here's the test i'm running: from unittest.mock import patch from django.shortcuts import reverse class DashboardViewTest(TestCase): @patch("ordering.mixins.OrderingAppPermissionRequired.handle_not_logged_in") @patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_profile") @patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_id") def test_order_list_view(self, *mocks): client = Client() response = client.get(reverse('ordering:list')) self.assertEqual(response.status_code, 200) I'm facing the following error (path redacted for privacy): Traceback (most recent call last): File "[python_root]\python\python37\Lib\unittest\mock.py", line 1191, in patched return func(*args, **keywargs) File "[project_root]\ordering\tests\test_dashboard.py", line 20, in test_order_list_view response = client.get(reverse('ordering:list')) File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 527, in get response = super().get(path, data=data, secure=secure, **extra) File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 339, in get **extra, File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 414, in generic return self.request(**r) File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 495, in request raise exc_value File "[virtual_env_root]\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "[virtual_env_root]\lib\site-packages\django\utils\deprecation.py", line 93, in __call__ response = self.process_response(request, response) File "[virtual_env_root]\lib\site-packages\django\contrib\sessions\middleware.py", line 45, in process_response patch_vary_headers(response, ('Cookie',)) File "[virtual_env_root]\lib\site-packages\django\utils\cache.py", line 266, in patch_vary_headers vary_headers = cc_delim_re.split(response['Vary']) TypeError: expected string or bytes-like object Help is appreciated. Thank you. -
How to get relative url of ImageField when using ModelViewSet in django rest framework?
I am getting an absolute URL of an ImageField when using ModelViewSet in the Django rest framework. When I am using a development server, its returning http://localhost:8000/media/abc.png and this is fine for me. But when I am using the nginx server, its returning http://localhost/media/abc.png which is incorrect. As you can see that the port is missing in the imagepath. How would I return the relative url or absolute URL with the port for the Nginx server for that ImageField? /models.py class BlogPost(models.Model): title_image = models.ImageField(upload_to='blog/title_images/%Y/%m/%d', blank=True, null=True) /serializers.py class BlogListSerializer(serializers.ModelSerializer): class Meta: model = BlogPost exclude = ('id',) /views.py class BlogViewSet(ModelViewSet): parser_classes = (FormParser, JSONParser, MultiPartParser, ) permission_classes = (AllowAny, ) authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication, ) queryset = BlogPost.objects.all() serializer_class = BlogListSerializer -
I want to display a list of categories on my HTML page from a Django 2.2 model but having trouble
I am creating an e-commerce website with Django, and on the products page I have a sidebar with category selections. I would liek to dynamically display the category selections according to the category choices given in the product model. Here is an image of the HTML (please don't judge the content or store type;-): Here is the model for toy products: Here are the category choices, defined within a tuple on the models.py file: Here is the HTML file thus far: As you can see I have tried a for loop but this isn't outputting anything. I have tried several things, and various ways of typing out the for loop and referring to the choices object within the ToyProducts Class, however nothing seems to be working. There will be hundreds of pages with a sidebar and various choices within the models and so hard coding each and every page is not what I would like to do. I would like to be able to loop through the catrgory options and display them as a list down the left hand side Many thanks! -
Django - Send data to online users on database update
I have a notification table where I store notifications for users. Currently I check the number of notifications that are not seen by the user with an AJAX call every 90 seconds. There is a specific url and view for that which returns a JsonResponse. {'notification_count':Notification.objects.filter(user=request.user, seen=0).count()} But now I want to send the notification count in real time if the user is online using websocket i.e. the server will automatically send the notification count to the user if the user is online whenever there is a change in the database. I saw some tutorials of django-channels but I found methods like connect, receive and disconnect. Note that the Notifications are saved from regular django views. How do I trigger socket methods whenever I make changes from django views? -
Django - how to get full url without hardcoding it
So I am trying to make a money tracker app. I've got two buttons on one page, one 'Add income' another 'Add expense', both of them take user to different urls but I want to use the same form. In my form I have a 'category' field, so I want to display user categories for income, or categories for expense. One way to know what user is trying to add is to check url of the page, and I can get it with request.get_full_path() but I don't want to hard code it like: if request.get_full_path() == '/newincome' I would like to use the name from 'urls' for this if statement, but I don't really know how. How can I accomplish that? Or maybe there is a better solution to this problem? -
How change urlpatterns path in urls.py in function of argument passed to manage.py?
i want change in urls.py: urlpatterns = [path('rmt/{}'.format(url), view)] from argument passed to manage.py class InitializeService(): def __init__(self): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RMT_Django.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc flag_env = sys.argv[6] if flag_env == "DEV": url = "/rmt/push_dev" elif flag_env == "TEST": url = "/rmt/push_test" elif flag_env == "PROD": url = "/rmt/push" execute_from_command_line(sys.argv[0:3]) InitializeService() how pass url to urlpattern? thanks -
comparing the foreign key of 1 table to the primary of another
As the title says im trying to compare the foreign key of one table to the primary of another if they match print out an editable version of the view and if they dont mak it read-only Models: class Ticket(models.Model): id = models.AutoField(primary_key=True, unique=True, auto_created=True) staffmember = models.ForeignKey('users.Users', verbose_name='Users',on_delete=models.CASCADE, default=True, related_name='ticket') ticketId = models.UUIDField(default=uuid.uuid4, editable=False) ticketName = models.CharField(max_length=200) ticketDescription = models.TextField(max_length=10000) ticketTime = models.DateTimeField(default=timezone.now) role = models.CharField(max_length=40, choices=Roles, default=developer) condition = models.CharField(max_length=40, choices=Condition, default=Opened) priority = models.CharField(max_length=40, choices=priority, default=low) class Users(AbstractUser): pass id = models.AutoField(primary_key=True, unique=True, auto_created=True) username = models.CharField(blank=False, max_length=25, unique=True) email = models.EmailField(blank=False, unique=True) objects = Manager() def __str__(self): return self.username View class EditTicketView(UpdateView, LoginRequiredMixin): model = Ticket template_name = 'editTicket.html' fields = ['ticketName', 'ticketDescription', 'condition', 'priority', 'role'] success_url = reverse_lazy('dashboard') Form class EditTicketForms(forms.ModelForm): class Meta: model=Ticket fields = ['ticketName', 'ticketDescription', 'condition', 'priority'] HTML {% extends 'base.html' %} {% block title %}Edit Ticket{% endblock %} {% block content %} <h1>Package Details</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success" type="submit" value="Add Comment"> </form> {% endblock %} im trying to compare the user ID with the foreign key in tickets called staffmember any help would be great -
Django managing the icons and images
This is a Best practice question about how to manage my media in my django site. I know this is not an "confusion with a code snippet" question like the most of the questions, but seriously i could imagine that this is a dilemma of some of the web developers. Instead of managing all of my media content by a model with a key of ImageField key like this: class myLogos(models.Model): foo = models.ImageField(upload_to = 'media/') I was thinking its more "manageable" to store all of my media content in a kind of separated server, and to call a specific image everytime from my template, like this: <img src="https://www.mysitepictures.com/app1/foo1.png" alt="Smiley face" height="42" width="42"> <img src="https://www.mysitepictures.com/app2/foo2.png" alt="Smiley face" height="42" width="42"> The reason is, i found it way too complicated to display images in an django project with multiple applications on it. Is that a great idea to have kind of an third party server just for calling the images from it? If not, then how should i manage a huge django project with a hundreds of images on the whole site? Thanks! -
Django-session-timeout: how to get time since deconnexion to se in a JS script?
I am using the django-session-timeout middleware app in my project but have an unexpectable behavior I am using JS script (JQuery) that display a popup on a click my problem is that, my popup display even if time is out (unexpected behavior) and just after user is disconnect (normal behavior) I would like to test time until disconnexion and if time is out, prevent popup display but looking at the django-session-timeout middleware, did not find any possibilities to get the time until disconnect hope my question is quite clear is anyone already face this problem? -
Setting CSRF cookie for react app, from django/drf
I am using Django with DRF, with a React frontend. I am trying to use session authentication. According to the DRF docs, if you intend to use session auth, you should use the standard django login/logout views. In order to use these, react (specifically axios inside react), needs to provide a CSRF header, obtaining the value from the CSRF cookie. From the point of view of my react app, the first interaction it needs to make with the server is a POST to the login view, but obviously at this point it has no CSRF cookie. I tried to get around this by doing a GET to the login view before the POST. This was not setting the cookie (according to the chrome dev tools), so I then tried overriding the login view's get method like this: class CustomLoginView(LoginView): template_name = "login.html" form = AuthenticationForm @method_decorator(ensure_csrf_cookie) def get(self, request): return super().get(request) In order to force the GET request to furnish the react app with a CSRF cookie, but this did not work either (did not set the cookie). It did occur to me to just make the login view CSRF exempt, but the DRF docs don't seem to like the … -
Is there any way to host django app in github hosting
Is there any way to run a django project in github hosting? I am very new to this..also suggest me any alternative way host my project -
How to paginate over data requested from form in template?
I have template with form for selecting from database: <form style="margin-top:15px" action="{% url 'search' %}" method="GET"> {% csrf_token %} <div class="row"> <input placeholder="Word" style="border-radius:20px;width:30%;height:15px;border:1px solid #de272b" type="text" value="" name="textbox1" size="1"/> </div> <div class="row"> <input placeholder="Phone" style="border-radius:20px;width:30%;height:15px;border:1px solid #de272b" type="text" value="" name="textbox2" size="1"/> </div> <input style="border-radius:40px;margin-top:10px; margin-bottom:15px;width:200px;height:35px;font-size:13px" type="submit" class="btn btn-primary" value="Request" name="button"> </form> view for searched url: def search_engine(request): db = MySQLdb.connect(host="local", user="pc", passwd="123456", db="test", charset="utf8") cur = db.cursor() q = request.GET.get("button", None) f = request.GET.get("page", None) print(request.GET.get) if q or f: word = request.GET.get('textbox1') phone = request.GET.get('textbox2') full_word = str(word) full_phone = str(phone) cur.callproc('full_search', (full_word,full_phone)) data = cur.fetchall() paginator = Paginator(data, 22) page = request.GET.get('page') data = paginator.get_page(page) return render(request, 'search.html', {'result': data}) It displays correct, but I can't paginate over it. I receive empty value on every page. But number of pages and lines is correct. Is something wrong with url in browser? -
Cannot load and print JSON file with data django framework and URLs does not showing while runtime
1) I have problem with URLs. I wrote piece of code, which should work correctly(i supposed). When i running my code, i do not see my another link, i have 2 pathes: register_user, and get_json, and i cannot reach this page with link get_json here is my code urls.py from django.urls import path from backend import views urlpatterns = [ path(r'get', views.get_json), path(r'register', views.register_user), ] 2) When i'm truing to run my code, i got another problem, such as raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I'm trying to get json from frontend and make an answer for it. json_data = get_json(request.body) and json_object = json.loads(request.body) I guess it could not be loaded and i don't know why. Here is my views.py import json from backend.models import RegistrationForm, AuthenticationForm from backend.responses import Responses def get_json(request): json_object = json.loads(request.body) if json_object and request.POST: return Responses.json_response("OK") else: return Responses.error_response(406, "Request was not a json or POST type") def register_user(request): json_data = get_json(request.body) print("here" + json_data) if request.POST: model = RegistrationForm(request.POST) By the way here is my class Responses, for not confusing with views.py from django.http import JsonResponse class Responses: def error_response(self, error, text): … -
Please help to get model object with certain key
Instead of posting entire Server json, I want to post only ip field and get the object from it's model. But if I post the data, it complains; If I posting with other key than Server by creating ServerIP = serializers.CharField(), it shows AttributeError. Can you please guide me how to achieve this? curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' -d ' \ { \ "Destination": "destination information", \ "Server": "165.213.100.100" \ } \ ' 'http://localhost:8001/api/server/registration' { "Server": { "non_field_errors": [ "Invalid data. Received str instead of dictionary." ] } } class Server(models.Model): class Meta: unique_together = ('ip',) hostname = models.CharField(default=None, null=True, blank=True, max_length=100) ip = models.GenericIPAddressField(default=None, null=True, blank=True) class Registration(models.Model): class Meta: unique_together = ('Server', 'Destination') Server = models.ForeignKey(Server, default=None, blank=True, \ null=True, on_delete=models.SET_NULL, related_name='firewall_server') Destination = models.CharField(default=None, blank=True, null=True, max_length=100) class RegistrationView(ListCreateAPIView): serializer_class = RegistrationSerializer queryset = Registration.objects.all() def get_serializer(self, *args, **kwargs): if self.request.method.lower() == 'post': data = kwargs.get('data') kwargs['many'] = isinstance(data, list) return super(RegistrationView, self).get_serializer(*args, **kwargs) def perform_create(self, serializer): return serializer.save() class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Registration fields = '__all__' validators = [] Server = ServerSerializer(read_only=False, many=False, required=False) def create(self, validated_data): destination = validated_data.pop('Destination') server_ip = validated_data.pop('Server') # <<= Here. It can't parse string. … -
django model multiple primary keys
I have 4 models: company, store, product and stock. The stock model has 3 ForeignKey to the other models and I need that the same product can only be inserted once in a company's store Models: class Company(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='company') name = models.CharField(max_length=150, unique=True, null=False) type_choices = [('Retailer', 'Retailer'), ('Provider', 'Provider')] type = models.CharField(choices=type_choices, max_length=12, null=False) dropshipping = models.BooleanField(default=False) city = models.CharField(max_length=24, null=False) postal_code = models.IntegerField(null=False) address = models.CharField(max_length=256, null=False) phone = models.CharField(max_length=24, null=False) is_active = models.BooleanField(default=False) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Store(models.Model): location = models.CharField(max_length=100, null=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='store_owner') def __str__(self): return self.location class Product(models.Model): name = models.CharField(max_length=256, unique=True, null=False) brand = models.CharField(max_length=128, null=False) date_added = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to = 'static/img/') def __str__(self): return self.name class Stock(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2, null=False) quantity = models.IntegerField(null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_stock') company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_stock') store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name='store_stock') Como puedo lograr esto? -
Is it possible to use GraphQL query the mptt tree with single request?
I can query the MPTT whole tree with Django REST using serializer. Now I am upgrading my service to support GraphQL as well. But the only single way I can do with iGraphQL is supply the deep down at most to get the last child node of tree Here is my DRF and my common technique to query tree models.py from mptt.models import MPTTModel class Question(MPTTModel): answer = models.TextField(null=True, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') serializers.py from rest_framework import serializers from questions.models import Question class QuestionTreeSerializer(serializers.ModelSerializer): class Meta: model = Question fields = [ 'id', 'parent', 'children', ] def get_fields(self): fields = super().get_fields() fields['children'] = QuestionTreeSerializer(many=True) return fields And here is my current GraphQL implementation from graphene import relay from graphene_django import DjangoObjectType from questions.models import Question class QuestionType(DjangoObjectType): class Meta: model = Question interfaces = (relay.Node,) fields = [ 'id', 'name', 'children', 'parent', ] class QuestionConnection(relay.Connection): class Meta: node = QuestionType class Query: questions = relay.ConnectionField(QuestionConnection) @staticmethod def resolve_questions(root, info, **kwargs): return Question.objects.all() Here is my current query query{ questions{ edges{ node{ id name children { edges { node { id name children { edges { node { id children { edges { node { id } … -
Keycloak integration with Django
I need help on keycloak integration with django. Here i am trying to achieve whenever user login i want to check keycloak authentication. please any one help me on that scenario Thankyou -
How to connect React with Django?
In team project, our team decided to use React and Django, and I decided to take the backend through Django. As I known, Django associates a view with a template html file that shows the view, and today I know that React returns a js not html. Does it work if I put the set of files that React returns into the Django template folder? Or is there another way?