Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication'
I am trying to deploy a django app on GCP but when i try to make migrations it gives me this error: ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework_simplejwt'. Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } SIMPLE_JWT = { 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=800), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), } OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 15, 'OAUTH_SINGLE_ACCESS_TOKEN': True, 'OAUTH_DELETE_EXPIRED': True } requirements.txt django-cors-headers pyjwt djangorestframework djangorestframework-jwt==1.11.0 What is it that I am missing ? -
Django-rest-framework validate JSONField still accept string
I'm currently trying to make a post request with only data field in models.py: class Filter(models.Model): class Meta: verbose_name_plural = "Filter" verbose_name = "Filter" db_table= "listing_filter" data = JSONField(default={}) user = models.ForeignKey('backend.user', on_delete=models.CASCADE) I have the following Serializer , i use JSONField following the drf document docs: class FilterSerializer(serializers.ModelSerializer): data = serializers.JSONField(required=True) user = serializers.CharField(required=False) class Meta: model = Filter fields = ('__all__') and use it in the APIView: class FilterView(APIView): def post(self, request): login_user = request.user received_json_data=json.loads(request.body) valid_ser = FilterSerializer(data=received_json_data) if valid_ser.is_valid(): post_data = received_json_data["data"] filter = Filter.objects.create(data=post_data, user=login_user) filter.save() return JsonResponse({'code':'200','data': filter.id}, status=200) else: return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400) When i send the following data in body it worked and saved the object: { "data": { "http://example.org/about": { "http://purl.org/dc/terms/title": [ { "type": "literal", "value": "Anna's Homepage" } ] } } } But when i send data as a string(which is not a json) it still save, how do i prevent this ? { "data" : "abc" } -
Is it possible to use request object outside of views or other way to get logged user information
I want to operate some filter with user based. So I need logged user information in my admin.py or other file. But I don't understand how it possible to get current loged user id or other information. Any one help me? -
How do I nest the sub-categories right under the parent category during render
I want the sub-categories of each of my category objects rendered as a drop-down menu nested inside it's parent category. I am having a hard time implementing that. How does it work? This is my view function: def home(request): categories = Category.objects.all().order_by('-date_posted') #sub_categories = I don't know how context = { 'categories': categories, #'sub_categories': sub_categories } return render(request, 'blog/home.html', context) This is inside my template: {% for category in categories %} <div class="nav-item dropdown"> <a href="#" class="py-3 nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ category.name }} </a> <div class="dropdown-menu rounded-0"> {% for sub_category in sub_categories %} <a class="dropdown-item" href="#"> {{ sub_category.name }} </a> {% endfor %} </div> </div> {% endfor %} The categories are rendering fine, my problem is with the sub-categories. -
What are Django configurations?
I'm setting up Pycharm for the first time using Pycharm, and I'm trying to figure out what the configurations do. I have looked online at the documentation, but it seems to be more focused towards people who already know what configurations do. I'm assuming it is used to set up my localhost, however I'm unsure. Any help would be greatly appreciated! -
Could it possible to change the name of folder after creating django project?
The result that I want The problem When I try to change the default folder name which is same as the django project, here comes warning from pycharm: WSGI_APPLICATION='backend_ch1_sec1.wsgi.application' in the setting.py After changing 'backend_ch1_sec1.wsgi.application' to 'backend.wsgi.application' pycharm warns: Django settings for backend_ch1_sec1 project How the could it work in the picture one? -
TypeError TypeError: retrieve_nested_resource() missing 1 required positional argument: 'nested_id'
i am receiving the following TypeError error message: TypeError TypeError: retrieve_nested_resource() missing 1 required positional argument: 'nested_id' attempting to follow follow stripe documentation but newbie to python following outdated tutorial on Udemy but really want/ need this app to work. Any idea or solutions welcome! Thank you in advance from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. @login_required def checkout(request): publishkey = settings.STRIPE_PUBLISHABLE_KEY customer_id = request.user.userstripe.stripe_id if request.method == 'POST': token = request.POST['stripeToken'] # Create a charge: this will charge the customer's card # card = stripe.Customer.create_source( # customer_id, # source=token) customer = stripe.Customer.retrieve_source( customer_id, source=token ) stripe.Charge.create( amount=499, currency='usd', description='Example charge', customer=customer, # card=card, statement_descriptor='Custom descriptor', ) context = {'publishkey': publishkey} template = 'checkout.html' return render(request, template, context) -
Why is Primary Key not being created for new form in Django?
After I submit my form the body does not include a primary key. So when I try to save in form_valid() I receive an error: Cannot force an update in save() with no primary key. See views.py below; it breaks on that final .save(). The answer from this question was very helpful in framing the problem: my first form.save(commit=False) populates the data from the POST from the form. And when I print (self.request.body) I see the other values like gallons and customer. But I don't see index (which is the primary key). I could just create a primary key in views.py like so: self.object.index = WorkOrderTable.objects.all().order_by('index').first().index +1 Note the +1; I'm just finding the last record/work_order and adding one to that pk. But I get the feeling since 'index' is an Autofield it should already be doing this. And I may regret my work-around down the road. forms.py class WorkOrderForm(ModelForm): customer = ModelChoiceField(queryset=models.CustomersTable.objects.order_by('firstname','lastname')) class Meta: model = models.WorkOrderTable exclude = [] models.py class WorkOrderTable(BasicModelFields): index = models.AutoField(primary_key=True) customer = models.ForeignKey('CustomersTable', on_delete = models.CASCADE, related_name='wo_customers') median_gallons = computed_property.ComputedIntegerField(compute_from='_get_median_gallons') def _get_median_gallons(self): "Returns the work orders' customer's median gallons pumped." median_gallons = customer_median_gallons(self.customer) return median_gallons def get_absolute_url(self): return utils.detail_reverse(self) def __str__(self): label = … -
How to save two ModelForms in views with ManytoManyRelationship
How can i possibly save the two form below in django2.1. What i want to achieve is for the current user logged in to save the two forms and become the creator of the ChatGroupUser 'group' created automatically. Terminal error TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead. Based on the terminal error, I have tried to use create_user.user.add(request.user) the line before save() but django throw another error there. models.py class ChatGroup(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_group_admins') is_active = models.BooleanField(default=True, null=True) is_current = models.BooleanField(default=False, null=True) class ChatGroupUser(models.Model): user = models.ManyToManyField(User) chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='chat_group_users') forms.py class ChatGroupForm(forms.ModelForm): class Meta: model = ChatGroup fields = ['name',] class ChatGroupUserForm(ModelForm): def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.fields['user'].queryset = self.fields['user'].queryset.filter(id=self.request.user.id) forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: model = ChatGroupUser fields = ['user'] views.py def create_group(request): if request.method == 'POST': form_group = ChatGroupForm(request.POST) form_user = ChatGroupUserForm(request, data=request.POST) if form_group.is_valid(): create_form = form_group.save(commit=False) create_form.group_admin = request.user create_form.save() create_group = form_user.save(commit=False) create_group.user= create_group create_group.save() return redirect('core:group_list') else: form_group = ChatGroupForm() form_user = ChatGroupUserForm(request) context = { 'form_group':form_group, 'form_user': form_user } return render(request, 'core/create-group.html', context) I really have tried different approaches and alternatives … -
Django 2.1 admin.py changeform_view method error with blank tables
In my admin.py i use changeform_view method for mantain some data into an add form after save Fo example one of my admin class is: class temp_mainAdmin(admin.ModelAdmin): form = TempMainForm list_filter = ('t_type',) list_display = ('descr', 't_type', 'notes', 'dt', 'active') def save_model(self, request, obj, form, change): obj.user = request.user super(temp_mainAdmin, self).save_model(request, obj, form, change) def changeform_view(self, request, obj_id, form_url, extra_context=None): try: l_mod = temp_main.objects.latest('id') extra_context = { 'lmod': l_mod, 'oId': obj_id } return super(temp_mainAdmin, self).changeform_view(request, obj_id,form_url, extra_context=extra_context) except Exception: pass admin.site.register(temp_main, temp_mainAdmin, ) The point is that if the temp_main table has at least one record all was done, but if instead the table is blank, when i try to open "add" form i receive the error DoesNotExist at /admin/backend/temp_main/add/ temp_add matching query does not exist. if i remove the entire changeform_view method from my class all was done except for the fact that after press "Save and add another" i don't have my fields already populated. Was wrong in my changeform_view method? p.s.: i use PostgreeSQL as backend db So many thanks in advance -
I need efficient Django ORM code to reduce query hitting
I am developing various statistical dashboards with Django, Python. A lot of filtered objects from each table and pass them to the template. But the result of the Debug-Toolbar is terrible. I need to change my code that is Hitting my database more efficiently. ** And this project is based on the models created by inspectDB on the server that is already developed. Django 2.2 Linux server, MariaDB Model class Consult(models.Model): consult_id = models.AutoField(primary_key=True) consult_type = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) booking_time = models.DateTimeField(blank=True, null=True) booking_time_unix = models.CharField(max_length=255, blank=True, null=True) dr_id = models.IntegerField(blank=True, null=True) uid = models.IntegerField(blank=True, null=True) session_id = models.CharField(max_length=255, blank=True, null=True) price = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) consult_action = models.IntegerField(blank=True, null=True) cancel_reason = models.CharField(max_length=1024, blank=True, null=True) comment = models.CharField(max_length=255, blank=True, null=True) notify_cnt = models.IntegerField(blank=True, null=True) consult_begin_at = models.DateTimeField(blank=True, null=True) consult_end_at = models.DateTimeField(blank=True, null=True) img_url1 = models.CharField(max_length=512, blank=True, null=True) img_name1 = models.CharField(max_length=512, blank=True, null=True) img_url2 = models.CharField(max_length=512, blank=True, null=True) img_name2 = models.CharField(max_length=512, blank=True, null=True) img_url3 = models.CharField(max_length=512, blank=True, null=True) img_name3 = models.CharField(max_length=512, blank=True, null=True) class Meta: db_table = 'consult' View @login_required def index(request): today = datetime.date.today() weekday = today.weekday() last_monday = today - datetime.timedelta(days=weekday, weeks=1) last_sunday = today - datetime.timedelta(days=weekday) - datetime.timedelta(days=1) this_monday = today - … -
Erro ao rodar docker com python
https://screenshot.net/pt/ygjv6ix celeryworker_1 | File "/usr/local/bin/celery", line 10, in celeryworker_1 | sys.exit(main()) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/main .py", line 16, in main celeryworker_1 | _main() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 322, in main celeryworker_1 | cmd.execute_from_commandline(argv) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 496, in execute_from_commandline celeryworker_1 | super(CeleryCommand, self).execute_from_commandline(argv)) ) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/base .py", line 269, in execute_from_commandline celeryworker_1 | self.on_concurrency_setup() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 539, in on_concurrency_setup celeryworker_1 | self.load_extension_commands() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 543, in load_extension_commands celeryworker_1 | self.register_command).load() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/base .py", line 138, in load celeryworker_1 | for name, cls in imports.load_extension_classes(self.names pace): celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/utils/im ports.py", line 156, in load_extension_classes celeryworker_1 | cls = symbol_by_name(class_name) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/kombu/utils/imp orts.py", line 57, in symbol_by_name celeryworker_1 | module = imp(module_name, package=package, **kwargs) celeryworker_1 | File "/usr/local/lib/python3.6/importlib/init.py", line 126, in import_module celeryworker_1 | return _bootstrap._gcd_import(name[level:], package, level ) celeryworker_1 | File "", line 994, in _gcd_impo rt celeryworker_1 | File "", line 971, in _find_and _load celeryworker_1 | File "", line 955, in _find_and _load_unlocked celeryworker_1 | File "", line 665, in _load_unl ocked celeryworker_1 | File "", line 678, in exec_module celeryworker_1 | File "", line 219, in _call_wit h_frames_removed … -
display a table within a table on a button click in angular 7
I am quite new to angular and web development and i am working with tables getting data from django PostgreSQL db to the front-end in form of tables. So, i need to have an details button in each row, clicking on which a new table is shown after that row. I am following the https://material.angular.io/components/table/examples of the expandable rows but i am not able to get desired results. I've created the buttons (expand_more mat icon)in the rows and a function(on-click event)which is getting the response from django view, what is left is to display the filtered data in details table. Is it possible to get the response in the description field as shown in the example below of angular material table, as the description is forming the expanded part of the table. Or i should follow a different approach altogether. I am very new to web development kindly ignore my mistakes. const ELEMENT_DATA: PeriodicElement[] = [ { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H', description: Hydrogen is a chemical element with symbol H and atomic number 1. With a standard atomic weight of 1.008, hydrogen is the lightest element on the periodic table. } -
How can I convert this String to an img .jpg from this Base64?
I'm working with django, and when I recived an encode image by Base64, I recive like this... enter image description here How can I decode and save on an image .jpg? I think the problem is that it start with {"imgB64":" and end with }' I been worked with Base64 before and doesn't have this begining and ending, What do you think? -
Django REST serializer queryset: access model via reverse foreign key?
I have a table that I would like to display the drawdown amounts for multiple pension funds for a proposed Investment. I have written a for loop over the 'Investment' instance in my table. However, I cannot seem to retrieve the amounts from this loop. I think that my queryset 'amountdrawdown' is incorrect as I'm trying to reverse lookup a foreign key (from the Investment model to DrawdownOnFund model). My models.py, simplified: class PensionFund(models.Model): name = models.CharField() class PensionFundDeposit(models.Model): PensionFund = models.ForeignKey(PensionFund) date = models.DateField() amount = models.DecimalField() undrawn = models.DecimalField() class Investment(models.Model): <---- Looping over this amount = models.DecimalField() date = models.DateField() class DrawdownOnFund(models.Model): Investment = models.ForeignKey(Investment) PensionFund = models.ForeignKey(PensionFund) date = models.DateField() amount = models.DecimalField() <---- I would like to retrieve this My serializer.py, simplified: class PensionFundSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'name'] class PensionFundDepositSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'fund','date','amount','undrawn', 'fundname'] class InvestmentSerializer(serializers.ModelSerializer): amountdrawdown = serializers.CharField(source='drawdown.amount') <---My attempt to write a query to retrieve the amount class Meta: fields = ['id', 'amount', 'date', 'amountdrawdown'] class DrawdownOnFundSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'call', 'commitment', 'date', 'amount', 'callid'] -
Get objects data trough txt docs
i've to recreate my project, for some data problems that i've got, them i'm trying to use some commands to import the data propperly. i'm having a problem by having to get a field from one doc.txt and other field pro other doc.txt but both fields from the same model. create_data.py from django.core.management.base import BaseCommand from c2vconfig.models import MP4, Tutorial class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'file_name', type=str, help='') def handle(self, *args, **kwargs): with open('nomes.txt') as file: for row in file: nome = row with open('urls.txt')as file: for row in file: url = row mp4 = MP4( nome=nome, url=url, ) mp4.save() self.stdout.write(self.style.SUCCESS('Data imported successfully')) models.py: class MP4 (models.Model): nome = models.CharField(max_length=100) url = models.URLField(max_length=300) preço = models.DecimalField(max_digits=5, decimal_places=2) imagem = models.ImageField(upload_to='', blank=True) artista = models.CharField(max_length=100, default='Unknown') nomes.txt Somewhere over the Rainbow people urls.txt https://www.youtube.com/watch?v=V1bFr2SWP1I&list=RDV1bFr2SWP1I&start_radio=1 https://www.youtube.com/watch?v=KDxJlW6cxRk&list=RDVHoT4N43jK8&index=19 its returning me just the last row from nomes.txt as MP4.nome and getting the MP4.url one by one as should be -
How to pass a custom model manager queryset to a template
I am trying to pass a custom query to a template but the query results are not being displayed. I had a working solution for this but I wanted to implement a custom model manager to simplify the code but I cant get the final step work - that is displaying the results on the template I have a custom manager: from django.db import models class ProfileQuerySet(models.QuerySet): def get_users_follows(self, user): print(user) return self.filter(followed_by__user__username=user) class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model, using=self._db) def get_users_follows(self, user): return self.get_queryset().get_users_follows(user) which is instantiated in the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) objects = ProfileManager() my view is as follows: class FollowsListView(LoginRequiredMixin, ListView): # Follow.follow_data = [[],[]] model = Profile template_name = 'blog/follows.html' # <app>/<model>_<viewtype>.html # paginate_by = 6 def get_queryset(self): follow_data = Profile.objects.get_users_follows(self.request.user) context = {'follow_data', follow_data} return context In the template i am calling the follow_data like so: {{ follow_data }} {% for p in follow_data %} {% if p.user %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ p.user.profile.image.url }}" alt=""> <a href="{% url 'user-posts' p.user %}">{{ p.user.profile.user }}</a> {% else %} <p>You are not following any users</p> {% endif %} </article> {% endfor … -
DataTables, serverSide and pagination on Django
I use DataTables with serverSide render. <script> $(document).ready( function () { $('#myTable').DataTable({ "processing": true, "serverSide": true, "ajax": "{% url 'core:persons_json' %}", "columns": [ {"data": "full_name"}, {"data": "email"}, ] }); }); </script> In my views.py i have: def persons_json(request): persons = Person.objects.all() data = [item.to_dict_json() for item in persons] page = 1 per_page = 10 res = { 'data': data, 'page': page, 'per_page': per_page, 'total': math.ceil(persons.count() / per_page) } return JsonResponse(res) But still he still returns all the persons. And I want to avoid loading a lot of data. But when i define, for example: def persons_json(request): length = int(request.GET.get('length')) persons = Person.objects.all()[:length] data = [item.to_dict_json() for item in persons] page = 1 per_page = 10 res = { 'data': data, 'page': page, 'per_page': per_page, 'total': math.ceil(persons.count() / per_page) } return JsonResponse(res) length = int(request.GET.get('length')) is parameter send by serverSide: http://localhost:8000/person/json/?draw=1&columns%5B0%5D%5Bdata%5D=full_name&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=email&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1568072064631 Note that we have: start=0&length=10. My question is as follows: when I use this second option. The pagination of other items does not appear in DataTables, ie I wanted it here but only one page appears. Does anyone know how I do to return all pages, and I go clicking each to advance the pages? -
404 on django pipeline staticfiles when using multiple deployments with different app versions
I have two different websites that run the same app but they may differ a bit in their versions. The problem I am encountering is when I deploy one site, if the version hash changes, the other site breaks as well. It looks to me like the hashes are stored in an external resource. How do I force each instance of the application to serve their own version of the staticfiles? Here are my configs: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', 'pipeline.finders.CachedFileFinder', #'django.contrib.staticfiles.finders.DefaultStorageFinder', ) -
mitmproxy failed with error 'no current event loop ...'
i try to start a mitmproxy instance as a thread from a django api call. Here my code: class Proxyserver(threading.Thread): def __init__(self): threading.Thread.__init__(self) opts = options.Options(listen_host='127.0.0.1', listen_port=8080) opts.add_option("body_size_limit", int, 0, "") opts.add_option("ssl_insecure", bool, True, "") config = proxy.ProxyConfig(opts) self.proxyserver = DumpMaster(opts) self.proxyserver.server = proxy.server.ProxyServer(config) self.proxyserver.addons.add(AddonProxy) def run(self): asyncio.set_event_loop(self.proxyserver.channel.loop) self.proxyserver.run() def stop_proxy(self): self.proxyserver.shutdown() proxythread = Proxyserver() proxythread.start() The error message is: Internal Server Error: /api/testcall_recrawl Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.7/dist-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/usr/bin/testcall/api/views.py", line 22, in post thread = threading.Thread(target=start_crawler()) File "/usr/bin/testcall/api/crawler.py", line 255, in start_crawler proxythread = Proxyserver() File "/usr/bin/testcall/api/crawler.py", line 152, in __init__ self.proxyserver = DumpMaster(opts) File "/usr/local/lib/python3.7/dist-packages/mitmproxy/tools/dump.py", line 24, in __init__ super().__init__(options) File "/usr/local/lib/python3.7/dist-packages/mitmproxy/master.py", line 48, in __init__ asyncio.get_event_loop(), File "/usr/lib/python3.7/asyncio/events.py", line 644, in get_event_loop … -
FOREIGNKEY Constraint failed
I'm having trouble getting my code to work. I can't seem to add second item to the database when I call this in views.py: def create_item(request): context = {} if not request.user.is_authenticated: return redirect("social:begin", "google-oauth2") if not checkrights(user=request.user, venue=request.user.currentVenue): print("Not verified") return redirect("dashboard:venues") context["venueList"] = [admin.venue for admin in request.user.administrates.all()] context["form"] = NewItemForm(currentVenue=request.user.currentVenue) context["cableForm"] = NewCableForm() context["adapterForm"] = NewAdapterForm() context["fixtureForm"] = NewFixtureForm() if request.method == "POST": itemForm = NewItemForm(data=request.POST, currentVenue=request.user.currentVenue) cableForm = NewCableForm(request.POST) adapterForm = NewAdapterForm(request.POST) fixtureForm = NewFixtureForm(request.POST) if cableForm.is_valid(): subItem = cableForm.save(commit=False) itemType = Type.objects.get(pk=3) print("Cable") elif adapterForm.is_valid(): subItem = adapterForm.save(commit=False) itemType = Type.objects.get(pk=2) print("Adapter") elif fixtureForm.is_valid(): subItem = fixtureForm.save(commit=False) itemType = Type.objects.get(pk=1) print("Fixture") if itemForm.is_valid() and subItem: item = itemForm.save(commit=False) item.itemType = itemType item.location = item.home item.out = False item.holder = None item.save() item = Item.objects.get(pk=item.id) subItem.id = item print(subItem.pk) subItem.save() return redirect("dashboard:detail", item_id=item.id) return render(request=request, template_name="dashboard/new_item.html", context=context ) This is my models.py: class Item(models.Model): id = models.AutoField(primary_key=True) itemType = models.ForeignKey(Type, on_delete=models.CASCADE, null=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="items") home = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="item_homes") out = models.BooleanField(null=True) holder = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name="holding") # owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=False, related_name="owns") class Fixture(models.Model): modelType = models.ForeignKey(Type, on_delete=models.CASCADE, default=4, related_name="fixtures") id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.ForeignKey(FixtureType, … -
django-saml2-auth: Infinite Redirects on Login
I'm completely new to django-saml2-auth (and SAML2 with Django in general) and am trying to get it working with Microsoft ADFS. When I hit my Django app it successfully redirects me to the federated login page, but after providing valid credentials, the app then goes into a loop where it's just flipping back and forth between my ENTITY_ID URL (which is https://myapp/saml2_auth/acs/) and a URL on the ADFS server with continually changing SAMLRequest values as a URL parameter. The only clue I have to go on at this point is when I check my browser history, eventually one of the page titles for all this activity in the history is "SigVer Error" but after some cursory googling I'm not sure what that might mean. I saw some references to disabling signed responses at the pysaml2 level but didn't want to go too far with that without first trying to figure out if that's even the issue given the behavior I'm seeing. Any ideas? I can share my settings if that'd be helpful but the only optional setting I'm adding is the ENTITY_ID value since that's required by ADFS. Debugging is also a bit of a challenge since at this point … -
Django download excel file results in corrupted Excel file
I am trying to export a Pandas dataframe from a Django app as an Excel file. I currently export it to CSV file and this works fine except as noted. The problem is that when the user open the csv file in Excel App, a string that looks like numbers .... for example a cell with a value of '111,1112' or '123E345' which is intended to be a string, ends up showing as error or exponent in Excel view; even if I make sure that the Pandas column is not numeric. This is how I export to CSV: response = HttpResponse(content_type='text/csv') filename = 'aFileName' response['Content-Disposition'] = 'attachment; filename="' + filename + '"' df.to_csv(response, encoding='utf-8', index=False) return response To export with content type EXCEL, I saw several references where the following approach was recommended: with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() return HttpResponse(b.getvalue(), content_type='application/vnd.ms-excel') When I try this, It appears to export something, but if I try to open the file in Excel Office 2016, I get a Excel message that the file is corrupted. Generally the size is few KB at most. Please advise what could be wrong … -
Pagination with ListView django
I want to create app with search and pagination. Pagination didn't work with ListView. When I click on the link "next" I am moving from start page http://127.0.0.1:8001/ ---> to the http://127.0.0.1:8001/?city=2 but elements of the list did not change. And next click to the "next" link did not changes the url ( http://127.0.0.1:8001/?city=2 --> http://127.0.0.1:8001/?city=2). Could you help me to find error? I think that error in *.html file, but can't find it My code: models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) class Meta: verbose_name_plural = "cities" def __str__(self): return self.name urls.py # cities/urls.py from django.urls import path from . import views from .views import HomePageView, SearchResultsView urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView from .models import City from django.db.models import Q from django.shortcuts import render, get_object_or_404 class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list home.html <!-- templates/home.html … -
The best pythonic way to include attributes in Q lookup using dictionary with the condition "OR"
When I include attributes in Qlookup using dictionary, they are used with the condition "AND". How best to set the condition "OR"? from django.db.models import Q query={'manufacturer':'1','release_date':'2019'} lookups = Q(**query) print(lookups) # (AND: ('manufacturer', '1'),('release_date', '2019')) I would like to see something like " (OR: ('manufacturer', '1'),('release_date', '2019')) " Thank you in advance.