Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get COUNT from id field of database using abstract user
how to get a count of total users in the database using an abstract user model. I want to use the id field to get the count of total users -
Wagtail ModelAdmin: Does not hide widget label
I have written an own panel that utilizes the django modeladmin. The modeladmin is connected to another model via a foreign key, but I dont want the user to be able to change the foreign key relation, only the other data on the form. I have therefor tried to hide the widget via the panels argument on the model admin: panels = [ FieldPanel("event_detail", widget=HiddenInput), FieldPanel("title"), FieldPanel("content"), FieldPanel("send_time"), ] This handles the input field correctly in the modeladmin, but sadly I still see the label in the modeladmin, which will confuse my users. How can I make sure that not only the field is removed but also the label? -
AttributeError: module 'profile' has no attribute 'run'
So I have an extended User model (extended AbstractUser) called Profile. This was in a seperate app called "profiles". I was plugging in the standard login and realised it was looking for a "profile" app name as standard, so I renamed it (directories, code, DB schema) which I thought should work. app_name was actually already set to "profile" in apps.py, so didn't need to rename url references. No dice. I get the error in the title. So I removed all migrations (I'm at the stage where I can still do this OK :) ) and deleted the sqlite DB that I'm currently working with, thinking I'd just rerun the migrations and recreate everything. Same error. The stack trace is: λ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\apps.py", line 18, in … -
Showing count of total objects in Django template
I have a Djanjo project where I add code snippets to a database, I would like to show display, in my template, a count of total snippets. Here is my model file: import datetime from django.utils import timezone from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Snippet(models.Model): snippet_name = models.CharField(max_length=200) description = models.TextField(max_length=600) code = models.TextField(default="null") approval_stage = models.CharField(max_length=200) updated = models.DateField('updated date') is_automated = models.BooleanField(default=False) def __str__(self): return self.snippet_name def total_snippets(self): return snippet_name.count() And here is the section of my template file where I want to display the number of snippets: <h5>{{ total_snippets }} total snippets</h5> This is rendering blank, with by value, on the final template. I've copied this code from another model, where I show a similar count of objects, and this works as expected, what am i missing here? -
Programing error: relation "api_role does not exist while makemigrations
Setting up a new brand new virtual environment and postgres db and can't even makemigrations. The system is running well on 2 other pc's python3.5 is installed virtual env created apps "requirements.txt" is sucessfully installed manage.py recognize the postgres server with the config created dev_henrique_desktop.py from .base import * DEBUG = True # Allow specific host headers only ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.proregatta.com','10.0.2.2'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'proregatta', 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432', } } both py and postgres are on PATH virtual env activated checked pgAdmin III for the super user created "postgres" when installing psql then beggins the problem already forced drop db searched for the "api_role" related problem in the migrations in every answer i get my eyes on. every one says makemigrations. what about when you can't make the inicial makemigrations delete all migrations and fresh "makemigrations" unnistall and install formatted the pc when problem persisted I expected to at the very least to make the inicial makemigrations noticed that the other machines probably have this missing relation in the db but not in migrations. Traceback (most recent call last): File "C:\Users\henri\Documents\Projects\backend-django\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) … -
All urls are not mapped by django rest framework swagger
I implement Django-rest-swagger for documentation my API but swagger UI not showing all URLs. When ı add permission_classes = [AllowAny] in my View than show the URL on swagger UI but this time all user will connect my DB ı don't want to do this. I want when the user login then gets the JWT token, after that click the Authorize button on swagger than will access my APIs. How can ı implement correctly JWT Bearer auth on my swagger UI? django-rest-swagger-2.1.1 djangorestframework Version: 3.9.0 Django Version: 2.2.3 Settings: SWAGGER_SETTINGS = { 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', 'USE_SESSION_AUTH': False, 'DOC_EXPANSION': 'list', 'APIS_SORTER': 'alpha', 'JSON_EDITOR': False, 'api_version': '0.1', 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', ], 'SECURITY_DEFINITIONS': { "api_key": { "type": "apiKey", "name": "Authorization", "in": "header", "description": "JWT authorization" }, },} Urls.py: schema_view = get_swagger_view(title='Unite.Ad Api') router = routers.SimpleRouter() router.register(r'company', CompanyViewSet, basename="company") router.register(r'brands', BrandsViewSet, basename="company_brands") router.register(r'brand-categories', BrandCategoriesViewSet, basename="company_brand_categories") router.register(r'customer-representative', CustomerRepresentativeViewSet, basename="customer_representative") router.register(r'sectors', SectorViewSet, basename="company_sectors") router.register(r'brief', BriefViewSet, basename="briefs") router.register(r'brief-categories', BriefCategoriesViewSet, basename="briefs-categories") router.register(r'country', CountryViewSet, basename="country") router.register(r'province', ProvinceViewSet, basename="province") urlpatterns = [ path('', schema_view), path('', include(router.urls)), path('admin/', admin.site.urls), path('user/register/', RegistrationView.as_view()), path('user/login/', AuthTokenViewSet.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api-token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), ] CompanyViewSet.py: class CompanyViewSet(ModelViewSet): """ retrieve: Return the given company. list: Return a list of logged user company and … -
How to hyperlink data from database on django
I am trying to build a simple search function on django that leads me to the link when I click on it. (I know api links are json links so clicking on them gives you no output of value but the point is to be able to click on them) i tried using but it doesnt work from my results.html: {% for dataset in datasets %} <br/> {{ dataset.datasets_available }} <br/> {{ dataset.data_source }} <br/> {{ dataset.brief_description_of_datasets }} <br/> {{ dataset.country }} <br/> <a href='https://www.google.com'>{{ dataset.api_documentation }}<a> <br/> #^ is the part i wanna fix <br/> {% endfor %} {% else %} <p style="font-family:Cambria">No search results for this query</p> {% endif %}` from views.py: def results(request): query = request.GET.get('q') if query: datasets = api_data.objects.filter(Q(datasets_available__icontains=query)) context = { 'datasets': datasets, } return render(request, 'Search/results.html', context) from models.py: class api_data(models.Model): data_source = models.TextField() brief_description_of_data = models.TextField() datasets_available = models.TextField() brief_description_of_datasets = models.TextField() country = models.TextField() api_documentation = models.TextField() class Meta: verbose_name_plural = "api_data" api_documentation is currently urls in strings. i want to be able to click on the output in html and view the actual website -
Send AJAX request to Django view with vanilla JS
I'm trying to send a GET AJAX request to a Django view using vanilla JS. is_ajax() passes but I could not retrieve the request object properly. Here is my JS code. With/out JSON.stringify(data) doesn't work. document.querySelector('#testForm').onsubmit = () => { let data = {category : 'music'}; const request = new XMLHttpRequest(); request.open('GET', 'test/', true); request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); request.onload = () => { const data = JSON.parse(request.responseText); console.log(data); } request.send(data); return false; }); And here is my Django view: def test(request): if request.is_ajax(): print('Yes!') data = {'category': request.GET.get('category', None)} return JsonResponse(data) else: raise Http404 It prints Yes! to the terminal but I get back a {category: null} in the console. This JQuery code works and I get the expected {category: "music"} response: $.ajax({ url: 'cart/', type: 'GET', data: data, dataType: 'json', success: function (data) { console.log(data); } }); I'm wondering what I'm missing in the vanilla JS code or in my Django view. -
Iterate through a string array in JSON
I'm looking to import data from a local JSON file into my DB Django. However, I have a problem because my JSON file contains a String array for each element and I can't iterate it. Example of the JSON file: [ { "key": "sword", "name": "Sword", "tier": 1, "tab": [ "damages", "cac" ] }, { "key": "bow", "name": "Bow", "tier": 1, "tab": [ "damages", "distance" ] }, ... ] I import this data using a script as follows: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('json_file', type=str) def handle(self, *args, **options): with open(options['json_file']) as f: data_list = json.load(f) for data in data_list: Item.objects.get_or_create( key=data['key'], name=data['name'], tier=data['tier'], ) for build in data['tab']: Build.objects.get_or_create( key = build ) The above script does not work and I have the following error in the console: KeyError: 'tab' -
Django: reset password of user as the Django administration
I have a section for website's staff, where they can manage users (register, update users info, deactivate...) like in the Django administration. Is there a way to reset user's password like in /admin/auth/user/<int:id>/password/ ? Here what I have done so far: forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'group_name', 'is_active', 'password',) views.py # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): if request.method == 'POST': form = UpdateForm(request.POST, instance=User.objects.get(id=id)) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=User.objects.get(id=id)) return render(request, 'accounts/update_user.html', {'form': form}) -
can't connect to mongodb through url in ubuntu18.04
I'm trying to connect mongodb with my django application. Help me with this situation. This is for Ubuntu-18.04 users running mongodb. I tried to run mongodb through command mongo and it worked where i created a db and user but when i use command mongod, it seemed good but when i entered localhost:27017 in firefox i get the error "The connection was reset" and it showed this error in terminal. I don't know what to do. 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] MongoDB starting : pid=2737 port=27017 dbpath=/data/db 64-bit host=django 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] db version v3.6.3 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] git version: 9586e557d54ef70f9ca4b43c26892cd55257e1a5 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.1.1 11 Sep 2018 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] allocator: tcmalloc 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] modules: none 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] build environment: 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] distarch: x86_64 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] target_arch: x86_64 2019-08-02T13:50:45.825+0530 I CONTROL [initandlisten] options: {} 2019-08-02T13:50:45.825+0530 I - [initandlisten] Detected data files in /data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'. 2019-08-02T13:50:45.825+0530 I STORAGE [initandlisten] 2019-08-02T13:50:45.825+0530 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine 2019-08-02T13:50:45.825+0530 I STORAGE [initandlisten] ** See … -
Atom text editor terminal is not working properly
I am practicing Django in atom text editor and install Platformio-ide-terminal package but after installation when I click to the + sign on the bottom left it is showing me blank console my expected result is console with some directories but it is showing me blank space with a blinking cursor -
ImportError: cannot import name 'get_core_apps' in Django Oscar Module
I am getting error when I am installing Django Oscar Module in my Project, it's giving me this error from oscar import get_core_apps ImportError: cannot import name 'get_core_apps' Here are my settings.py file... from oscar import get_core_apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', 'south', ] + get_core_apps() -
Why doesn't CreateView pass the argument to the form?
Override form field queryset by passing additional argument (employee_pk) from get_form_kwargs method to __init__ form method. I try 2 ways, both do not work. First: class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillGroupCreateForm template_name = 'skill_create.html' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['employee_pk'] = self.kwargs['pk'] return kwargs def get_context_data(self, **kwargs): print(self.kwargs['pk']) ---> just for test print 4 context = super(SkillTestCreateView, self).get_context_data(**kwargs) forms.py class SkillGroupCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.employee_pk = kwargs.pop('employee_pk', None) # super(SkillGroupCreateForm, self).__init__(*args, **kwargs) self.fields['technology'].required = False if self.employee_pk: self.fields['technology'].queryset = Technology.objects.exclude(skill__employee_id=self.employee_pk) Second: class SkillCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'employee_info_create.html' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(employee_pk=self.kwargs['pk']) return kwargs forms.py class SkillCreateForm(forms.ModelForm): def __init__(self, *args, employee_pk=None, **kwargs): super().__init__(*args, **kwargs) if employee_pk is not None: self.fields['technology'].queryset = Technology.objects.exclude( skill__employee_id=employee_pk ) Both return None -
Unable to receive push notification after web push
I am trying to implement push notification in react and django. Followed push notification documentation as per https://developers.google.com/web/fundamentals/push-notifications/. Able to generate subscription key and storing it into database. In backend, i am using django, so for that i have used pywebpush library. After creating subscription i am saving it into database. After storing the data successfully, i am same data with message and called function webpush. I am getting the response 201 OK but i am not receiving any notification. Note: For react, i have used creact-react-app and trying to implement push notification in development environment. I have created my separate sw.js file in public/sw.js. From dev tool, i can trigger push notification but from code i am not able to trigger it. Thanks in advance for any help. Django: class trigger_notification (generics.CreateAPIView): """ API Endpoint to trigger the notification """ serializer_class = UserSubscriptionSerializer def post(self, request): try: data = request.data print('Came to trigger push service') # Get the subscription and data to be send trigger_notification = webpush( subscription_info={ 'endpoint': data['endpoint'], 'keys': { 'p256dh': data['p256dh'], 'auth': data['auth'] } }, data=data['message'], vapid_private_key=config('PRIVATE_KEY'), vapid_claims={ "sub" : "mailto:admin@xyz.com" } ) print('Trigger Notification -------') print(trigger_notification) print('end---------------- ') return Response({'message' : 'trigger push notification'}, status=201) … -
Create Model for newly created Database durring runtime
To my current project: We create durring runtime new databases and fill them with table and informations. Now we need to create a model file that looks like that: class Attributes(models.Model): fk_pset = models.CharField(max_length=255, blank=True, null=True) attribute_name = models.CharField(max_length=255, blank=True, null=True) attribute_name_readable = models.CharField(max_length=255, blank=True, null=True) ifc_class = models.CharField(max_length=255, blank=True, null=True) data_type = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'attributes' class Ifcbeam(models.Model): globalid = models.CharField(max_length=255, blank=True, null=True) entitylabel = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) parent = models.CharField(max_length=255, blank=True, null=True) isexternal = models.CharField(max_length=255, blank=True, null=True) loadbearing = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'ifcbeam' This file we can create when the server isnt running with inspectdb but now we need to create them durring runtime. Is there a way to create such a file with python code? -
How to integrate Neo4J with GraphQL in Django?
Recently I wanted to try something else besides API and DB for backend. I'd say a graph stack for Django. I choose GraphQL because of its popularity and as database I wanted to try something else that is not working with tables, rows and columns. I choose Neo4j for this task and its Django OGM neomodel. I started reading documentation of both technologies. Struggling with them a little bit I wanted to integrate them and I found out that there is no such opportunity. Articles that I found were written about either Neo4j and DRF or GraphQL with ordinary RDB. I created some nodes, for now I've got one app that is a user profile (I'm doing a clone of social network) and mapped them to a GraphQL schema. Then I've got errors like Country doesn't have attribute _meta and etc. My nodes # Node is AbstractNode with __abstract_node__ attribute set to True class Country(Node): name = StringProperty() class City(Node): name = StringProperty() And schema class Query(graphene.ObjectType): countries = graphene.List(Country) cities = graphene.List(City) country = graphene.Field(Country) city = graphene.Field(City) def resolve_countries(self, info, **kwargs): return Country.nodes.all() def resolve_cities(self, info, **kwargs): return City.nodes.all() def resolve_country(self, info, **kwargs): pass def resolve_city(self, info, **kwargs): … -
Django: Refactoring the "right" way
My DetailView currently gets longer and longer. And therefore I am trying to learn more about some better practices to shorten it again. Right now, I am looking into the def post() part. The full code is even longer. My best idea currently is to create a utils.py in the same folder and take out the code snippets inside the if else statements. Is that best practice or would you do it in a different way? class EventDetail(DetailView): [...] @transaction.atomic def post(self, request, *args, **kwargs): # Discount code POST if self.discount_form.is_valid(): discount_code = self.discount_form.cleaned_data['code'] request.session[discount_cookie_name(request.event)] = discount_code return redirect(reverse_obj(self.request.event, 'events:detail')) # Consent form POST elif self.consent_form.is_valid(): # Check if email entry exists contact = request.event.organizer.contacts.filter( email=self.consent_form.cleaned_data['email'] ).first() success_message = _("You successfully signed up to receive event updates.") if contact: # Check if current event is allocated to entered email. event_entry = contact.contact_relation.filter( event=request.event ).first() if event_entry: event_entry.lead = True event_entry.save(update_fields=['lead']) messages.success(request, success_message) else: # Email entry exists, but event allocation must be added. ContactRelation.objects.create( lead=True, contact=contact, event=request.event ) messages.success(request, success_message) # Create new email entry and allocate event. else: instance = self.consent_form.save(commit=False) instance.organizer = request.event.organizer instance.save() instance.contact_relations.add( request.event, through_defaults={'lead': True} ) messages.success(request, success_message) return redirect(reverse_obj(self.request.event, 'events:detail')) elif self.formset.is_valid(): # Check … -
Fix Celery Issue 'can't pickle <class 'module'>: attribute lookup module on builtins failed
I am running celery 4.1.1 on windows and sending requests to redis(on ubuntu), Redis is properly connected and tested from windows side. But when i run this command celery -A acmetelbi worker --loglevel=info i get this long error: [tasks] . accounts.tasks.myprinting . acmetelbi.celery.debug_task [2019-08-02 11:46:44,515: CRITICAL/MainProcess] Unrecoverable error: PicklingErr or("Can't pickle <class 'module'>: attribute lookup module on builtins failed",) Traceback (most recent call last): File "c:\acmedata\virtualenv\bi\lib\site- packages\celery\worker\worker.py", line 205, in start self.blueprint.start(self) File "c:\acmedata\virtualenv\bi\lib\site-packages\celery\bootsteps.py", line 119, in start step.start(parent) File "c:\acmedata\virtualenv\bi\lib\site-packages\celery\bootsteps.py", line 370, in start return self.obj.start() File "c:\acmedata\virtualenv\bi\lib\site- packages\celery\concurrency\base.py", line 131, in start self.on_start() File "c:\acmedata\virtualenv\bi\lib\site- packages\celery\concurrency\prefork.p y", line 112, in on_start **self.options) File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\pool.py", line 1007 , in __init__ self._create_worker_process(i) File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\pool.py", line 1116, in _create_worker_process w.start() File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\process.py", line 124, in start self._popen = self._Popen(self) File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\context.py", line 383, in _Popen return Popen(process_obj) File "c:\acmedata\virtualenv\bi\lib\site- packages\billiard\popen_spawn_win32.py", line 79, in __init__ reduction.dump(process_obj, to_child) File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\reduction.py", line 99, in dump ForkingPickler(file, protocol).dump(obj) _pickle.PicklingError: Can't pickle <class 'module'>: attribute lookup module on builtins failed (bi) C:\acmedata\bi_solution\acmetelbi>Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\spawn.py", line 165, in spawn_main exitcode = _main(fd) File "c:\acmedata\virtualenv\bi\lib\site-packages\billiard\spawn.py", line 207, in _main self = pickle.load(from_parent) EOFError: Ran out of input i … -
Django Rest Framework using nested serializer for posting data two models
I've been using the Django rest framework to create API. In this API there are two models Question and Option. Question is Foreign Key in Option. I have been trying to get all the fields in a single form and add data to the corresponding models. For a question, options can be as many as provided from a form. I tried to create options for the already existed question (ie. first question will be added in the database and then the question is selected and the options for that question will be added) and I don't think it will be the practical approach so I had an idea that the options need to be added in the database at the time of question creation. models.py class Question(models.Model): body = RichTextField() class Option(models.Model): question = models.ForeignKey(Question, on_delete=CASCADE) number = models.IntegerField() option = RichTextField() is_correct = models.SmallIntegerField() serializers.py class QuestionSerializers(serializers.ModelSerializer): class Meta: model = Questions fields = ('id', 'body', 'explanation') class QuestionReadSerializer(serializers.ModelSerializer): question = QuestionSerializers() class Meta: model = Options fields = ('question', 'number', 'option', 'is_correct') class QuestionWriteSerializers(serializers.ModelSerializer): question = QuestionSerializers() class Meta: model = Options fields = ('question', 'number', 'option', 'is_correct') @transaction.atomic def create(self, validated_data): question_data = validated_data.pop('question') question = Questions.objects.update_or_create(**question_data) … -
Django vs Kivy comparison
I just found out about kivy and I also started developing with Django recently. I'd please like to extensively compare Kivy with Django. What are the major differences? Which one is relevant now, and will be relevant in the next five years? What are their advantages and disadvantages? What kind of apps can I build with Kivy? What's the best or most recommended JavaScript framework to mix with either of the two? -
I have a REST api on Django. Which UI technology should I use - Nodejs or Angular?
I have a couple of REST apis built using django rest framework. I want to build a UI using those APIs. I am not sure which UI technologies should I be using - Nodejs or Angularjs ? I plan to have few animations in UI to give a good feel while using the UI. What will be the pros and cons? Please suggest. -
AssertionError at /graphql/ Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping
I am new to django and graphql, I am trying use graphql in django using the the instructions given in this site. https://docs.graphene-python.org/projects/django/en/latest/installation/ I followed the instructions carefully but when I enter the url http://127.0.0.1:8000/graphql/ I am getting the error following error. AssertionError at /graphql/ Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping. I just have a single app called demo. The code in the models.py of demo app is as follows... from django.db import models # Create your models here. class UserProfile(models.Model): userId = models.IntegerField(primary_key=True) userName = models.CharField(max_length=15) password = models.CharField(max_length=15) address = models.CharField(max_length=30) phoneNumber = models.IntegerField() class Meta: db_table = 'UserProfile' Here are the relevant parts of the settings.py file in the project folder. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'corsheaders', 'demo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True GRAPHENE = { 'SCHEMA': 'abc.schema.schema' } abc is the name of the main project folder which contains manage.py. Please help,thanks in advance. -
Avoid duplication in Django when having to format a message both in a template and as a response from an ajax call
I have a chat board where people can post messages that can include attachments and some other additional things. When I retrieve all messages I loop over them and display each message in this way (simplified): <p>Message posted by: <strong>{{ details.name }}</strong></p> <p>{{ details.message }}</p> <ul> {% foreach attachment in attachments %} <li>{{ attachment }}</li> </ul> {% endforeach %} So far, so good. Now, my difficulty is that I use AJAX to allow people to post new message. Upon adding a new message, I struggle to find the best way to show this message to the user. The problem is that the new message needs to be formatted in a particular way (the above is a simplification; there are various conditions and additional formats). I can think of three ways: I use javascript to parse the message. That means I basically have the same code twice, in two different languages (once in Django's template language for all existing message, and then again in js for newly added messages) I craft the exact same HTML code in the view, so when I return a response through AJAX it already includes properly formatted code. However, this will also be a duplication of … -
How to Redirect to a POST url and pass data in django
I'm trying to integrate payfort payment gateway using the redirection method. it requires redirecting to a POST url and submitting some data. the data contains confidential values like access code and merchant code, so i don't want to expose them in HTML. Is it possible to redirect to a POST URL from a django view and submit the data? or should I use ajax to perform the signature calculations and submit the form using jquery. I'm kind of lost. any help is appreciated.