Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer not writing individual object from queryset
I am using a ModelForm to capture some data for a model and, while I want this data saved to a db, I also want to export it to an XML file for transformation/use in an external system. Please see below for an example: def warranty(request): WarrantyFormSet = modelformset_factory(Warranty, form=WarrantyForm) if request.method == 'POST': formset = WarrantyFormSet(request.POST, request.FILES) if formset.is_valid(): new = formset.save(commit=False) out = open("file.xml", "w") XMLSerializer = serializers.get_serializer("xml") xml_serializer = XMLSerializer() for n in new: xml_serializer.serialize(Warranty.objects.all(), stream=out) #.filter(id = n.id) n.save() return HttpResponse(xml_serializer.serialize(Warranty.objects.filter(id = n.id))) else: formset = WarrantyFormSet(queryset = Warranty.objects.none()) return render(request,'warranty.html', {'formset': formset}) The object is serializing appropriately in the HttpResponse (ie I can see an acceptable XML output), but there is no output in the XML file itself. If I remove the QuerySet filter (i.e. call .all()), then the XML file will correctly have all objects related to the Warranty model. It seems strange that the behaviour is fine in one circumstance in not theother, so I can't trouble shoot any further. -
I have some problems with Django and hope it can be helped
My Django project uses native SQL instead of ORM, which means that I have not created any Models. I now need to make a permission division based on the user type, that is, the administrator can see all pages, and ordinary users can only see my website Part of the page, I don't know what I should do, I hope to get some examples, thanks! -
How to access combined table fields in Django manytomanyfield
py which looks like below class Scenes(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Tech(models.Model): tech = models.CharField(max_length=30) scenario = models.ManyToManyField('Scenes') def __str__(self): return self.tech class UserLog(models.Model): tech_id = models.ForeignKey(Tech, on_delete=models.CASCADE) ....#other fields It generates one extra table called pages_tech_scenario (pages is my app name) My populated tables in database (postgres) looks like below pages_tech_scenario id | tech_id | scenes_id ----+---------+----------- 1 | 1 | 1 4 | 2 | 1 5 | 2 | 2 6 | 2 | 3 7 | 2 | 4 8 | 2 | 5 9 | 3 | 3 10 | 4 | 1 11 | 4 | 2 12 | 4 | 3 pages_scenes id | name ----+---------- 1 | poweron 2 | poweroff 3 | sleep 4 | wakeup 5 | switch pages_tech id | tech ----+------ 2 | CDMA 3 | GSM 4 | 5G 1 | LTE pages_userlog id | data_location | pc | username | target | data_type | description | status | submission_time | upload_now | string_submission_time | tech_id_id ----+------------------------------------------------------+---------+----------+--------+-----------+-------------+-------------+-----------------------+------------+------------------------+------------ 39 | C:\My Files\testFolder | lab0128 | ananagra | SDX55 | crash | | In Progress | 2020_02_12_T_17_45_04 | f | | 2 19 | C:\My … -
pip install error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 73776
This is a Django project. Encountering error upon running pip install -r requirements.txt in a local virtualenv. Collecting https://github.com/jedestep/Zappa/archive/layer-support.zip (from -r requirements\base.txt (line 9)) Using cached https://github.com/jedestep/Zappa/archive/layer-support.zip ERROR: Command errored out with exit status 1: command: 'c:\users\user~1\desktop\project\project\venv\scripts\python.exe' -c 'import sys, setuptools, tokenize ; sys.argv[0] = '"'"'C:\\Users\\USER~1\\AppData\\Local\\Temp\\pip-req-build-6htw2gh2\\setup.py'"'"'; __file__='"'"'C:\ \Users\\USER~1\\AppData\\Local\\Temp\\pip-req-build-6htw2gh2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)( __file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' e gg_info --egg-base 'C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\pip-egg-info' cwd: C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\setup.py", line 8, in <module> long_description = readme_file.read() File "c:\users\user~1\desktop\project\project\venv\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 73776: character maps to <undefined> ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. The requirements do install as expected in the vagrant environment, however I recall that it would also work locally on my machine. Unfortunately, I'm not sure what was the change that lead to this error, it may have been the result of a pull. Versions: Python: 3.6.5 Django: 2.2 pip: 20.0.2 I have run pip install --upgrade setuptools but it does not change the error. A similar error will occur with the automatic test database … -
Django / wagtail DevOps, backups, and content migrations tatics and strategies
I supported a client with a site fully develop on Django wagtail for a third party, we manage to fix many bugs, but I come from a background of Cloud infrastructure so I trying to do things like de-coupling the Database form the application box and the files. I manage to do all this using cloud technologies like (S3/digital Ocean spaces, Digital Ocean progress SQL cluster). Of course, we also set up our git server to be able to function with the different environments, Dev, Stage, and production. And here is when everything turns a litter more complex since we have many different environment and tonnage of content to pass from one side to the next. I would like to know about the best way to do very regular things like migrations of content and backing up content, updating the DBs, and that. so far all the processes we find in the official documentation, forums, and courses do not satisfy our need for quick recovery on productions or migrating partial content from one environment to the next. My guess is this steel a very young technology for a production site. So, my question is How do you guys handle backups, … -
Can we make three different authentication for three different types of user in django and all three will login differently
In my Django web app, I want to create three different types of users. One user can create their account just by entering their credentials and when logging in he will use his username, The next user will be admin, and the third user cannot create his account directly. The third user after entering his credentials, his request to create his account will be sent to the admin and only after the admin verifies him the account will be created else not. And when logging in the third user should use his phone number. As you can see here all three users have different signup and login process and are authenticated differently. Is there any solution to this problem? I searched everywhere but failed to find a solution to this. -
why nginx shows servererror(500) and in log files shows failed (98: Address already in use)
this is my nginx.log.errors i have restarted and and stopped the running server and but the error is same 2020/02/12 15:41:19 [emerg] 10488#10488: bind() to [::]:80 failed (98: Address already in use) 2020/02/12 15:41:19 [emerg] 10488#10488: bind() to 0.0.0.0:80 failed (98: Address already in use) 2020/02/12 15:41:19 [emerg] 10488#10488: bind() to [::]:80 failed (98: Address already in use) 2020/02/12 15:41:19 [emerg] 10488#10488: bind() to 0.0.0.0:80 failed (98: Address already in use) 2020/02/12 15:41:19 [emerg] 10488#10488: bind() to [::]:80 failed (98: Address already in use) -
Django - template reloads after ajax response
I'm sort of new with Django and I ran through an issue. I'm sending a post request to django view and return the function back with HttpResponse in order to change my template's div contents to the passed value from my view. The issue is: once ajax responds and changes it's div's value; the page instantly reloads. Do you guys have any idea why? Views.py def index(request): if request.is_ajax(): print("request is ajax") details = request.POST.get('id') return HttpResponse(details) else: return HttpResponse("Failed) base.html <button id="checkres">Check result</button> <form name="testform" id="testform" method="post"> {% csrf_token %} <input type="text" id="rowfield"> <input type="submit"> </form> $("#testform").submit(function (event){ $row_num = $('#rowfield').val() $("#responseresult").text('checking'); $.ajax({ type: "POST", url: "/bot", data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num}, success: function(data){ $("#responseresult").text(data); alert(data); } }); }); -
Python: Main thread is not in main loop
I am attempting to move my python GUI onto Django so it can be a web server. I already have a .py file created for the GUI, so I simply set my views.py in Django for the web page I wanted to run my gui.py. But when I run it with Django I get the Runtime Error: Main Thread not in the main loop. I do not get this error however when I run my code using python3 in the terminal. I am brand new to Django so if there is a more efficient or suitable way to integrate an already developed python GUI into a Django web page I would be happy to hear it but from my research, I could not find anything. -
Searching function in django didnt give any response django
Im trying to make a searching function in list segment , but when i click the search button, it wont give any response . Already try to print something in the views but it didnt print anything , so i assume my code is wrong and didnt get to the search views html segment list <input id="searchword" type="text" placeholder="Search..." /><button id="searchbutton" class="btn btn-success btn-xs">Search</button> <script> $(document).ready(function() { $("#searchbutton").change(function () { var urls = "{% url 'polls:search' %}"; var table = $('#searchword').val(); $.ajax({ url: urls, data: { 'table': table, }; success: function(data) { alert("success"); }, error: function(data) { alert("data not found or invalid"); } }); }); }); </script> views for search def search(request): search_data = request.GET.get('table',1) print(searchdata) import cx_Oracle dsn_tns = cx_Oracle.makedsn('', '', sid='') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() c.execute("select asd.segment_name,asd.is_published, au.username, asd.\"Created_Date\" from arman_segment_dimension asd join auth_user au on asd.user_id = au.id where upper(asd.segment_name) like upper('%"+search_data+"%') or upper(asd.is_published) like upper('%"+search_data+"%') or upper(au.username) like upper('%"+search_data+"%') or upper(asd.\"Created_Date\") like upper('%"+search_data+"%')") c.rowfactory = makeDictFactory(c) databasetable = [] for rowDict in c: databasetable.append({ 'segmentname': rowDict['SEGMENT_NAME'], 'usercreate': rowDict['USERNAME'], 'datecreate': rowDict['Created_Date'], 'published' : rowDict['IS_PUBLISHED'] }) page = request.GET.get('page', 1) paginator = Paginator(databasetable, 5) try: segment = paginator.page(page) except PageNotAnInteger: segment = paginator.page(1) except … -
How much flexible is django admin?
I have a project where the admin can change users and roles, view users content, etc. The users can also add private and public content and are required to authenticate to use the project. Once authenticated, they will also be able to consume the data in a specific custom way. Is django a good fit for this kind of project? It is flexible enough to handle this scenario. Thanks! -
Combining 2 custom permissions in django rest framework
I have a model called Showcase that users use to showcase projects, and also a collaboration model where users can add collaborators to the showcase. I am trying to implement a case where administrators in the showcase and the user in a collaboration can delete that collaboration. To explain better, in a showcase model, there is a list of administrators that manage the showcase. they also can add collaborators (through the Collaborator model) to a showcase. The Collaborator has a user field which is the user contributed to the showcase. I want that after a collaborator has been added, that user can either delete himself (in a case he doesnt want to be part of the showcase) or the administrators can delete that collaborator (in a case thay added a wrong user and want to delete him from that showcase) models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) class Collaborator(models.Model): post = models.ForeignKey(Showcase, on_delete=models.CASCADE, related_name="collaborated_showcases") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="collaborators") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True, related_name="creative_type") role = … -
Add user to group automatically after registration in Wagtail
I made this before with django like this: signals/handlers.py from django.dispatch import receiver from django.conf import settings from django.contrib.auth.models import Group from users.models import * @receiver(post_save, sender=settings.AUTH_USER_MODEL) def save_profile(sender, instance, created, **kwargs): if created: g1 = Group.objects.get(name='Editors') instance.groups.add(g1) but I don't know how to make it with wagtail ! thanks. -
Error when passing two parameters to Django View
I'm trying to retrieve 2 parameters within a view as shown below: class BrowseJobs(ListView): model = Job template_name = 'jobs/browse_jobs_for.html' ordering = ['-published_date'] context_object_name = 'browse_jobs_for' paginate_by = 15 def get_context_data(self): widget_name = self.request.GET.get('widget') input_query = self.request.GET.get('keyword') print(widget_name) output_query = Job.objects.filter( Q(organization__name__icontains=input_query) | Q(department__name__icontains=input_query) | Q(city__name__icontains=input_query) | Q(state__name__icontains=input_query) | Q(min_qualification__icontains=input_query) | Q(desired_qualification__icontains=input_query) | Q(profession__name__icontains=input_query) ).distinct() if widget_name.lower() == 'org' or widget_name.lower() == 'dept' or widget_name.lower() == 'state' or widget_name.lower() == 'city': wg_name = "in" elif widget_name.lower() == 'edu' or widget_name.lower() == 'post': wg_name = "for" context = { 'input_keyword': input_query, 'query_results': output_query, 'concatinating_string': wg_name } return context This is how the entry looks for this view within the urls.py file: path('browse-jobs/', BrowseJobs.as_view(), name = 'browse-jobs'), And this is how I'm invoking this view from the template: <a href="{% url 'browse-jobs' %}?keyword={{state.name}}&widget=state">{{state.name|replace_and}}</a> I'm getting the following error when accessing the above link: UnboundLocalError at /browse-jobs/ local variable 'wg_name' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/browse-jobs/?keyword=Karnataka&widget=%27state%27 Django Version: 3.0.3 Exception Type: UnboundLocalError Exception Value: local variable 'wg_name' referenced before assignment Exception Location: C:\Projects\Django\SarkariNaukri-Project\jobs\views.py in get_context_data, line 197 Python Executable: C:\Users\Shahzan\.virtualenvs\SarkariNaukri-Project-2efS6LFe\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Projects\\Django\\SarkariNaukri-Project', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe\\Scripts\\python38.zip', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe\\DLLs', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe\\lib', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe\\Scripts', 'C:\\Users\\Shahzan\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib', 'C:\\Users\\Shahzan\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe', 'C:\\Users\\Shahzan\\.virtualenvs\\SarkariNaukri-Project-2efS6LFe\\lib\\site-packages', 'c:\\users\\shahzan\\.virtualenvs\\sarkarinaukri-project-2efs6lfe\\src\\django-newsletter'] I would really appreciate, if … -
Django Modelform Crispy Form generating multiple duplicate queries
Model.py class Tenancy(CreationModificationDateMixin): TENANCY_STATUS_CHOICE = ( ( 1 , "ACTIVE"), ( 2 , "LEGAL"), ( 3 , "EXPIRED"), ( 4 , "INACTIVE"), ) outlet = models.ForeignKey(Outlet, on_delete=models.PROTECT) tenant = models.ForeignKey(Company, related_name="tenant_tenancies",on_delete=models.PROTECT) landlord = models.ForeignKey(Company, related_name="landlord_tenancies", on_delete=models.PROTECT) stampdutyno = models.CharField(_("Stamp Duty No."), max_length = 13, unique=True, validators=[RegexValidator(regex='^\d{13}$', message="Stamp Duty No. has to be 13 digits", code="nomatch")]) stallno = models.ManyToManyField(OperatingStall) cuisine = models.CharField(_("Cuisine"), max_length=50) business_name = models.CharField(_("Business Name"), max_length=50, null=True, blank=True) startdate = models.DateField(_("Start Date")) enddate = models.DateField(_("End Date")) gurantorname = models.CharField(_("Gurantor's Name"), max_length=50) gurantoraddress = models.CharField(_("Gurantor's Address"), max_length=50) postal_code = models.CharField(_("Postal Code"), max_length = 6, validators=[RegexValidator(regex='^\d{6}$', message="Postal Code has to be 6 digits", code="nomatch")]) gurantorNRIC = models.CharField(_("Gurantor's NRIC"), max_length=9) status = models.PositiveIntegerField(_("Status"), choices=TENANCY_STATUS_CHOICE, default=1) yearly_insurance = models.BooleanField(_("Bill Yearly Insurance?"), default=True) class Meta: verbose_name = 'Tenancy' verbose_name_plural = 'Tenancies' def __str__(self): stall = " & ".join(str(stall) for stall in self.stallno.all()) return f"{stall} - {self.tenant.name} | ({self.startdate} to {self.enddate})" class TenancyChargeType(CreationModificationDateMixin): BILLING_CYCLE = ( ( 1 , "INITIAL"), #Have to bill once entered into system ( 2 , "MONTHLY"), #Bill Monthly ( 3 , "END OF MONTH"), #Bill End of Month ( 4 , "YEARLY"), #Bill Yearly ( 5 , "AD HOC"), #Bill AD HOC ) name = models.CharField(_("Charges Name"), max_length=50) account_no = … -
Integrating Django onto Nodejs
So I currently have a fully functional Node backend which is being used for a flutter mobile app. The only issue is I want to create the web app using Django because it's pretty powerful and also if we ever considered doing more of our backend there. Though my only confusion is that now that the node backend is pretty setup, most of the posts about integrating both frameworks keep leaning toward having django do the auth, orm/db stuff etc and then actually integrating /adding node to it. Now my question for the most part: How can you integrate a django web app to an already setup Node backend? You might say work with react for the frontend but the truth is I have zero expertise around it and I feel it would be faster for me to work in a python-esque environment since I'm super familiar with it. What are your thoughts? Is this even possible? -
Cannot reach Django Rest API with gunicorn + postgres + docker-compose
I am slowly trying to put together a production build for my API. However, I can't seem to access it when I visit localhost:8000. How I am testing this is by first running $ docker-compose run postgres to have the database up and running. Then $ docker-compose run api for the API. Here is the output of running the API Starting redribbon_postgres_1 ... done [2020-02-13 00:57:38 +0000] [1] [INFO] Starting gunicorn 20.0.4 [2020-02-13 00:57:38 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1) [2020-02-13 00:57:38 +0000] [1] [INFO] Using worker: sync [2020-02-13 00:57:38 +0000] [8] [INFO] Booting worker with pid: 8 However, when I visit localhost:8000, I am seeing Site cannot be reached. Not sure why this is the case. The only difference between my develop and production build is that I am not using gunicorn in my develop build. docker-compose.yml version: "3" services: postgres: image: postgres:latest restart: always ports: - "5432:5432" volumes: - ./pgdata_prod:/var/lib/postgresql/data/ environment: POSTGRES_DB: redribbon POSTGRES_USER: bli1 POSTGRES_PASSWORD: 021891 api: build: dockerfile: Dockerfile context: ./redribbon-api command: gunicorn --chdir api api.wsgi -b localhost:8000 volumes: - ./redribbon-api/api:/usr/src/api depends_on: - postgres ports: - "8000:8000" -
psycopg2 error while installing django: lssl library not found
I am trying to install a Django project and keep running into the same error regardless of what I try. I am pretty new to python so the error messages are quite cryptic. Any help would be appreciated: The error message is as follows: gcc -bundle -undefined dynamic_lookup -arch x86_64 -g build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o build/temp.macosx-10.9-x86_64-3.7/psycopg/green.o build/temp.macosx-10.9-x86_64-3.7/psycopg/pqpath.o build/temp.macosx-10.9-x86_64-3.7/psycopg/utils.o build/temp.macosx-10.9-x86_64-3.7/psycopg/bytes_format.o build/temp.macosx-10.9-x86_64-3.7/psycopg/libpq_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/win32_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/solaris_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/connection_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/connection_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/cursor_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/cursor_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/column_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_connection_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_cursor_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_message_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/diagnostics_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/error_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/conninfo_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/lobject_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/lobject_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/notify_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/xid_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_asis.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_binary.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_datetime.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_list.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pboolean.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pdecimal.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pint.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pfloat.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_qstring.o build/temp.macosx-10.9-x86_64-3.7/psycopg/microprotocols.o build/temp.macosx-10.9-x86_64-3.7/psycopg/microprotocols_proto.o build/temp.macosx-10.9-x86_64-3.7/psycopg/typecast.o -L/usr/local/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.9-x86_64-3.7/psycopg2/_psycopg.cpython-37m-darwin.so ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/Users/fardeemmunir/dev/dealdock/bin/python3 -u -c "import setuptools, tokenize;__file__='/private/var/folders/7y/hms24fnn4138y1t2ywz912yr0000gn/T/pip-install-vgvo5098/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/7y/hms24fnn4138y1t2ywz912yr0000gn/T/pip-record-j7nnm_8j/install-record.txt --single-version-externally-managed --compile --install-headers /Users/fardeemmunir/dev/dealdock/include/site/python3.7/psycopg2" failed with error code 1 in /private/var/folders/7y/hms24fnn4138y1t2ywz912yr0000gn/T/pip-install-vgvo5098/psycopg2/ -
How to add results from a JSON stored in POSTGRESQL?
How to add results from a JSON stored in POSTGRESQL? However, an error is returned in the query. I'm doing it this way. Transactions.objects.filter(id=id, metadata__metadata__deleted='false')\ .annotate(amount=RawSQL("metadata->>%s", ("amount", )))\ .aggregate(amountTotal=Sum('amount')) -
Django Authentication across multiple projects
I recently got a new gig and my client has a requirement to have multiple Django projects use one Authentication system. A better way to explain this is think of Google, they have several services such as Gmail, YouTube, Drive etc. Across all these products, a single User account is used. My client expects that he will have multiple products in the future but wants to maintain one single Django project "Account" for authentication across all his future products. Each product in this case will be a separate Django project. I plan to use DRF as he also wants to use Vue for frontend. The question is, how do I tie all these projects together to use a single Auth User Model? Also, each of the projects will be deployed on separate servers. How would you suggest I implement this? Any suggestions will be highly appreciated. -
Empty Django Inline saying fields are required
In django admin I'm trying to create a new entry, but fields in the inline forms are throwing errors saying they are required even if I don't want to create a new inline. models: class Attribute(models.Model): name = models.CharField(choices=ATTRIBUTE_CHOICES, max_length=max_choice_len(ATTRIBUTE_CHOICES)) amount = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return f'{self.name} {str(self.amount)}' class Item(models.Model): ... attributes = GenericRelation(Attribute) admin: class AttributeInline(GenericTabularInline): model = Attribute extra = 0 class ItemAdmin(admin.ModelAdmin): inlines = [AttributeInline] class Meta: model = Item admin.site.register(Item, ItemAdmin) -
Django's python manage.py createsuperuser gives error OperationalError: 'no such table'
I am working on my Final Year Project. I wanted to extend the default User model that Django provide in order to add some more attributes. I added following code in my models.py class User(AbstractUser): contact = models.CharField(max_length=100) Also in settings.py I added: AUTH_USER_MODEL = 'esacp.User' where as esacp is the name of my app. After doing all of this, I ran python manage.py makemigrations esacp, then I ran python manage.py migrate in my CMD. Both of these commands worked prfectly. Now, I went to create an admin role for my Django Web App, in order to manage the things as a superuser, when I ran the command python manage.py createsuperuser, it asked me for the username, after I entered username and pressed 'Enter', it gave me the error: django.db.utils.OperationalError: no such table: esacp_user The screenshot of the whole error is attached below enter image description here Kindly tell me where did I make mistake or miss anything? Thanks in advanced! -
Why does the Django message tags boxs is not working?
I have a problems with the message tags. So I have a little apps that send a sms. When I press the submit button and my webpage, if the sms is send correctly a message.success is printed on the screen.(The success messages work fine. the text and green color appear correclty) But if the message is not sent, an message.error is printed, but only the text is printed, the red color box is not printed(Which is not fine, I also want the Red box to be printed). I searched online to find a answer, but I didn't find anything.THanks for help views.py try: sms = Client.messages.create( from_="+14509001443", body=mess, to=number ) send = sms.sid print("DOne") form.instance.author = request.user form.save() messages.success(request, f'Votre message a bien été envoyé!') return redirect("sms-home") except: print("error") messages.error(request, f'Votre message na pas été envoyé!') return redirect("sms-home") home.html {% extends "sms/base.html" %} {% load crispy_forms_tags %} {% block content %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} <div> <form method="POST"> {% … -
Django Exists() / ~Exists() return if there is no matching data?
I have the DetailView below with a query/subquery that checks whether supplier_code exists within instances of a second model set up to represent purchase orders received into a live stock database. The intention is for this to function as a checklist/ticksheet that will return whether or not the order has been received for each supplier expected to send one. Getting it to return that there is a match seems to be working fine, and if there is a value it does not recognize (I have purposefully created an invalid order that won't match against the list) it will return that there is no match. However I need this to also tell me that there is simply no data, yet I don't seem to be able to achieve this. For example the below shows the template output; G001 is the 'fake' code I have set up and G002 is a valid one that exists in the suppliers list. However if there is not an order present for G002 it will not return anything. Order not received: G001 Order received: G002 I have tried writing a second query for the context that is a mirror of context['db_orders'] but using the ~Exists() and … -
Simplifying Javascript which adds an "active" class according to URL (DRY)
I usually write in Python on the back-end and am not seasoned on JS. This code looks pretty nasty to me as it repeats itself a lot. If I were writing in Python I think I would make a list of objects then loop over the list of objects to add the active class if one of the objects matches the URL. Can I do that with JS? Or what is a good way to optimize this from someone who writes on the front-end normally? var url = window.location.pathname; var overview = document.getElementById("overview"); var cats = document.getElementById("categories"); var videos = document.getElementById("videos"); var tests = document.getElementById("tests"); var memos = document.getElementById("memos"); var overviewBtm = document.getElementById("overview-btm"); var videosBtm = document.getElementById("videos-btm"); var testsBtm = document.getElementById("tests-btm"); var memosBtm = document.getElementById("memos-btm"); var profileBtm = document.getElementById("profile-btm"); var superUsersBtm = document.getElementById("super-users-btm"); var superResultsBtm = document.getElementById("super-results-btm"); var superNewBtm = document.getElementById("super-new-btm"); var superInviteBtm = document.getElementById("super-invite-btm"); var superProfileBtm = document.getElementById("super-profile-btm"); if (url == '/overview/'){ console.log(url); if (overview){ overview.classList.add('nav-active'); } else if (overviewBtm){ overviewBtm.classList.add('nav-active'); } } else if (url == '/categories/'){ console.log(url); if (cats){ cats.classList.add('nav-active'); } } else if (url == '/videos/'){ console.log(url); if (videos){ videos.classList.add('nav-active'); } else if (videosBtm){ videosBtm.classList.add('nav-active'); } } else if (url == '/tests/'){ console.log(url); if (tests){ tests.classList.add('nav-active'); …