Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make choices with the columns?
class question(models.Model): q = models.CharField(max_length=500) choice1 = models.CharField(max_length=500) choice2 = models.CharField(max_length=500) choice3 = models.CharField(max_length=500) answer = models.CharField(max_length=500, choices=[choice1, choice2, choice3]) it's giving me this error: 'choices' must be an iterable containing (actual value, human readable name) tuples. but I don't know how to fix it? Thanks -
Django ModelChoiceField, label_from_instance object iteration
The method label_from_instance from CustomModelChoiceField, iterates one object at a time, but I need the method to receive all objects at once. This is due to a freight calculation call that waits for all objects at once for the calculation. Is it possible? from django import forms from django.utils.safestring import mark_safe class CustomModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("My Object custom label <strong>%i</strong>" % obj.id) class MyForm(forms.ModelForm): my_field = CustomModelChoiceField(label=_('The form label'), queryset=MyModel.objects.filter(), widget=forms.RadioSelect, empty_label=None) class Meta: model = MyModel -
Delete query fields from model instance
I have a SAP Business One model called OHEM in my Django project but this ERP allow the custom fields creation for each company. Actually I have an admin for one of this company and the other would like to use them but when run the code in the company "B" database I have the next warning: The name of column 'U_INT_EMPLOYEE_CODE' don't exists. (207) The company "A" have a lot of user fields and the company "B" have another user different fields for the same model and want to use the same code for both Shared model class Ohem(models.Model): empid = models.IntegerField(db_column='empID', primary_key=True) # Field name made lowercase. lastname = models.CharField(db_column='lastName', max_length=50, blank=True, null=True) # Field name made lowercase. firstname = models.CharField(db_column='firstName', max_length=50, blank=True, null=True) # Field name made lowercase. middlename = models.CharField(db_column='middleName', max_length=50, blank=True, null=True) # Field name made lowercase. sex = models.CharField(max_length=1, blank=True, null=True) jobtitle = models.CharField(db_column='jobTitle', max_length=20, blank=True, null=True) # Field name made lowercase. type = models.IntegerField(blank=True, null=True) dept = models.SmallIntegerField(blank=True, null=True) branch = models.SmallIntegerField(blank=True, null=True) # Company A fields u_int_cod_empleado = models.IntegerField(db_column='U_INT_COD_EMPLEADO', blank=True, null=True) # Field name made lowercase. u_hbt_contrasena = models.CharField(db_column='U_HBT_Contrasena', max_length=100, blank=True, null=True) # Field name made lowercase. u_hbt_cardcode = models.CharField(db_column='U_HBT_CardCode', max_length=15, blank=True, … -
Django extending the User model in ECommerce application
I have a django ecommerce project that works fine till I decided to improve it. User place order and every time they place an order they have to always input their details (name, emil, address etc) , I decided to upgrade the application so if user had registered before no need to enter details again . orders/models.py from django.db import models from django.contrib.auth.models import User from shop.models import Product from decimal import Decimal from django.core.validators import MinValueValidator,MaxValueValidator from coupons.models import Coupons class order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=50) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True) discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)]) class Meta: ordering = ('-created',) verbose_name = "order" verbose_name_plural = "orders" def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) def get_total_cost_after_discount(self): total_cost = sum(item.get_cost() for item in self.items.all()) return total_cost - total_cost * (self.discount / Decimal('100')) class OrderItem(models.Model): order = models.ForeignKey(order,related_name='items',on_delete=models.CASCADE) product = models.ForeignKey(Product,related_name='order_items',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10,decimal_places=2) quantity = models.PositiveIntegerField(default=1) class Meta: verbose_name = "OrderItem" verbose_name_plural = "OrderItems" def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity I create account app and extended django user so that … -
how can i add a variable that uses a view function into signals
i am trying to add a field into my Profile creation signals, this field is the ip of the user, i have a function view that when called returns the user ip, this function needs a request argument, i want this field to be added when a user registers a new account and when this happens the signals would be called and then the profile model would be created with the ip field. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() views.py def register(request): form = UserReg(request.POST or None) if form.is_valid(): user = form.save() login(request, user) return redirect('shop-home') form = UserReg() context = { 'form' : form, 'login': 'Log in' } return render(request, 'users/register.html', context) models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.CharField(max_length=45) -
django.core.exceptions.FieldError: Cannot resolve keyword 'redirect' into field. Choices are: added, edited, id, ip_address, name, notes
I am recieving a FieldError specifically the code not being able to resolve a keyword when attempting to run my server. I am currently upgrading my server from django 1.1 to django 2.2 and when trying to run the server the "django.core.exceptions.FieldError" is listed in the traceback telling me that the keyword "redirect" in line 326 cannot be resolved into a field. All other solutions online seem to be for a specific line of code and their resolutions have not worked in trying to resolve my issue. Here is the traceback: File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/urls.py", line 3, in <module> from usdpages.services.views import RedirectHostList, RedirectsFile, ImportFile File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/views.py", line 227, in <module> class ImportForm(forms.Form): File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/views.py", line 229, in ImportForm server = forms.ModelChoiceField(queryset=Host.objects.redirected(), initial=defaultHost) File "/var/www/guindev.sandiego.edu/html/Projects/usdpages/usdpages/services/models.py", line 329, in redirected return self.filter(host__isnull=False).distinct() File "/usr/local/lib64/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1190, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/usr/local/lib64/python3.6/site-packages/django/db/models/sql/query.py", line 1049, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) … -
DJANGO - How to fix "Incomplete response received from application"
I must be going crazy... If I have my views.py file with 48 or less lines, when I POST data to it, I see Incomplete response received from application However, If I have 49 lines or more I get a NameError, 'request' is not defined thrown on line 31 and 49, even if line 31/49 is empty. Could someone please explain what is happening? Also btw Django Admin - "Incomplete response received from application" does not answer my question. veiws.py: from django.shortcuts import render from django.shortcuts import render from django.shortcuts import HttpResponse from django.core.exceptions import * from datetime import datetime def remove_xss(chat, request): return chat def find_urls(chat, request): new_chat = ' '.join([('<a href="{}">{}</a>'.format(word, word) if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')]) return new_chat def format_chat(chat, username, request): chat = remove_xss(chat, request) chat = find_urls(chat, request) request = request return "hi" def chat_index(request): return render(request, 'chatroom.html') def chat(request): if request.method == 'POST': chat = request.POST.get('textfield', None) if request.user.is_authenticated(): u = request.user.username f_chat = format_chat(chat, u, request) else: return HttpResponse('You must be signed in to continue') with open('chats.txt', 'a') as chats: chats.write(f_chat) return render(request, 'chatroom.html') urls.py: (Working (i think)) from chat import views from … -
How to modify django task in external app
I need to make some changes to a 3rd party app to enable additional functionality. This app has several tasks that make RPC calls via a service proxy that need to be updated to use a different command based on whether the associated object supports the new functionality. I've managed to update one of several of these functions but I wanted to ask the community if there was a more pythonic/DRY to do this using a decorator or pattern that I'm not thinking of. More precisely, I'm trying to add support for shielded transactions to a cryptoasset wallet while maintaining backward compatibility. I've forked the django-cc library (https://github.com/limpbrains/django-cc). I've updated the currency model to include a boolean to indicate shielded transactions are supported. Within the tasks, I've put a if statement to switch between the two. It works, but before I start refactoring the rest of the code, I want to know if there's an interface or strategy pattern I can use that would be more appropriate. We're interested in the AuthServiceProxy (https://github.com/jgarzik/python-bitcoinrpc/blob/master/bitcoinrpc/authproxy.py) object coin. The object uses a call function, so getnewaddress is passed out as as param to the RPC call. The asset we're adding doesn't support this … -
How to perfrom a aggregate query with condicional filter in django
I have this data on the model: [ {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": true}, {"Field": "value1", "Flag": false}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": false} ] I try to aggregate the data with this query when the flag is True: model.objects.values('Field').order_by('Field').annotate(total=Count('Field'), Flag=Count('Flag', filter=Q(Flag=True))) And I expect this output in the result of the query: [ {"Field": "value1", "total": 4, "Flag": 2}, {"Field": "value2", "total": 3, "Flag": 1} ] try with conditional aggregation but display this error: SQLDecodeError -
How to access its object query properties I know it have 5 properties in it
I wanna access <QuerySet [<User: xyz>]> this object properties it have multiple properties but i dont know how to access each property and update its value u = User.objects.filter(username=username) u.first_name=(str(first_name)) u.save(` -
Why is this ModelForm not valid
I'm new to coding with django, and I'm trying to add comments to my blog app, but I'm having trouble with the validation of this form, it always returns False with form.is_valid(), so the object is never saved views.py def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) comments = Comment.objects.filter(blog_post=obj) initial_data = { "blog_post": obj, } form = CommentModelForm(request.POST or None, initial=initial_data) if form.is_valid(): comment_obj = form.save(commit=False) comment_obj.user = request.user comment_obj.save() form = CommentModelForm() else: print('not clean') context = { "object": obj, "comments": comments, "form": form, } template_name = 'blog/detail.html' return render(request, template_name, context) forms.py from django import forms from .models import Comment class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = ['content','blog_post'] HTML <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> models.py class Comment(models.Model): content = models.TextField(max_length=300) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=1) blog_post = models.ForeignKey(BlogPost, null=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) -
how to hide in the dropdown list the required value using ajax and jquery with django
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input. where the user will have three options to select between and based on his selection the value will show or be hidden in the dropdown list. my question is how to hide the required option based on the returning ID. until now this what i tried and it did not work as i want. views.py def getSource(request): sources = Source.objects.all() return render(request, 'create_folder.html', {'sources':sources}) create_folder.html case"1": $('#mouresaleMasdar option[data-id="40"]').hide() and i tried another solution also didn't work. $('#mouresaleMasdar option[value="{{ source.id }}== 40"]').hide() -
Django 2.2 translations not applying, LANGUAGE_CODE and i18n URL pattern correct
I'm using Django 2.2 and Python 3.7. I'm trying to set up Django translations, and everything seems to work up until the point of seeing the translations. I'm using i18n urls so the url shows up as localhost/language-locale example: localhost/en-us/ localhost/fr-fr/ url patterns: urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path('i18n/', include('django.conf.urls.i18n')), ... settings_l10_i18.py: LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en-us', _('US English')), ('en-gb', _('British English')), ('en-ca', _('Canadian English')), ('fr-fr', _('French')), ('fr-ca', _('Canadian French')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False USE_THOUSAND_SEPARATOR = True LOCALE_PATH = [ os.path.join(BASE_DIR, "locale"), ] file structure basedir/locale ├── en_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_GB │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_US │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_FR │ └── LC_MESSAGES │ ├── django.mo │ └── django.po └── README.md Language switcher in template: <li> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language" value="" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% … -
Is it possible to start using Django's migration system after years of not using it?
A project I recently joined, for various reasons, decided not to use Django migration system and uses our own system (which is similar enough to Django's that we could possibly automate translations) Primary Question Is it possible to start using Django's migration system now? More Granular Question(s) Ideally, we'd like to find some way of saying "all our tables and models are in-sync (i.e. there is no need to create and apply any migrations), Django does not need to produce any migrations for any existing model, only for changes we make. Is it possible to do this? Is it simply a case of "create the django migration table, generate migrations (necessary?), and manually update the migration table to say that they've all been ran"? Where can I find more information for how to go about doing this? Are there any examples of people doing this in the past? Regarding SO Question Rules I didn't stop to think for very long about whether or not this is an "acceptable" question to ask on SO. I assume that it isn't due to the nature of the question not having a clear, objective set of criteria for a correct answer. however, I think … -
Django Admin - Filter ManyToManyField with through model
How can I filter a queryset inside the Admin page of an object that has a ManyToManyField relation with a through model? Given models.py class Foo(models.Model): foo_field1 = models.CharField(max_length=50) class Main(models.Model): main_field1 = models.CharField(max_length=50) m2mfield = models.ManyToManyField(Foo, through="FooBar") class FooBar(models.Model): main = models.ForeignKey(Main, on_delete=models.CASCADE) foo = models.ForeignKey(Foo, on_delete=models.CASCADE) new_field = models.CharField(max_length=50) Inside admin.py class M2MInlineAdmin(admin.TabularInline): model = Main.m2mfield.through extra = 1 class MainAdmin(admin.ModelAdmin): inlines = [M2MInlineAdmin,] ... def formfield_for_manytomany(self, db_field, request, **kwargs): print('called formfield_for_manytomany') return super().formfield_for_manytomany(db_field, request, **kwargs) def get_field_queryset(self, db, db_field, request): print('called get_field_queryset') super().get_field_queryset(db, db_field, request) I try to access both of these methods, but none of them are called if I specify a through table. However, they do get called if the ManyToMany relation is simply defined as like this: class Main(models.Model): main_field1 = models.CharField(max_length=50) m2mfield = models.ManyToManyField(Foo) Is there a method to filter the queryset when a through table is specified? -
Headers are not sent in HTTP request in POST request in django
HTTP request works without gunicorn and nginx. However, when those 2 are added the headers are not sent and get an wsgi error. I've looked online with no avail. What do I need to change to read the headers? def accessWebhook(request): try: headers = request.headers #this breaks here print(headers) jsondata = request.body data = json.loads(jsondata) print(data) return HttpResponse(status=200) except: return HttpResponse(status=500) This is the error from gunicorn {'wsgi.errors': <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f577cffe4a8>, 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': True, 'wsgi.run_once': False, 'wsgi.file_wrapper': <class 'gunicorn.http.wsgi.FileWrapper'>, 'SERVER_SOFTWARE': 'gunicorn/19.9.0', 'wsgi.input': <gunicorn.http.body.Body object at 0x7f577cffe320>, 'gunicorn.socket': <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('172.20.0.2', 8000), raddr=('172.20.0.3', 40832)>, 'REQUEST_METHOD': 'POST', 'QUERY_STRING': '', 'RAW_URI': '/access/api/webhook/', 'SERVER_PROTOCOL': 'HTTP/1.0', 'HTTP_X_FORWARDED_FOR': '192.168.240.98', 'HTTP_HOST': '192.168.240.109', 'HTTP_CONNECTION': 'close', 'CONTENT_LENGTH': '34', 'HTTP_USER_AGENT': 'PostmanRuntime/7.13.0', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT': '*/*', 'CONTENT_TYPE': 'application/json', 'HTTP_AUTHORIZATION': 'fZEOMAmm8Ygpaee73dRY', 'HTTP_CACHE_CONTROL': 'no-cache', 'wsgi.url_scheme': 'http', 'REMOTE_ADDR': '172.20.0.3', 'REMOTE_PORT': '40832', 'SERVER_NAME': '0.0.0.0', 'SERVER_PORT': '8000', 'PATH_INFO': '/access/api/webhook/', 'SCRIPT_NAME': ''} The headers prints correctly when running local server but once gunicorn and nginx is added. The headers are gone. -
Get related objects in Django and how to use Prefetch with related models
models.py class Press(models.Model): created = models.DateTimeField(editable=False) title = models.CharField(max_length=500, blank=True) slug = models.SlugField(max_length=600, blank=True, unique=True) def __str__(self): return self.title class Scan(models.Model): press = models.ForeignKey(Press, related_name='scans', on_delete=models.CASCADE) created = models.DateTimeField(editable=False) title = models.CharField(max_length=300, blank=True) main_scan = models.ImageField(upload_to='press/scans', blank=True) def __str__(self): return self.title views.py class PressListView(ListView): model = Press context_object_name = "press" template_name = "press.html" def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['press'] = Press.objects.prefetch_related(Prefetch('scans', queryset=Scan.objects.select_related('press'))) return context What I would like to achieve on the front-end of the site is to list all Press and as the cover image for each would like to use 1st main_scan image from the Scan model. I know I can add models.ImageField to Press model, but I do not want to - in the admin I am using admin.TabularInline from Scan model that is attached to Press model. I know there is documentation on prefetch but probably I am using it wrong and as well doing it wrong on the front-end in the template. Question is how to make it very optimized, that the performance is best, hitting the Database just once. Previously I was doing it this way and it worked, but this is causing … -
Django REST Framework TokenAuthentication Problem
Estoy intentando implementar la autenticación de token, el cuál busco generar al momento de dar de alta un usuario. El usuario se genera correctamente pero no se genera el token. Otro problema, al margen de la no generación del token, es que al crear el usuario el password en la base de datos se guarda como texto plano. El código es el siguiente: Python 3.7 Django 2.2.3 DRF 3.10.1 PostgreSQL En settings.py ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Instaladas: 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ''' En serializer.py ''' from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password':{'write_only':True}} def create(self, validated_data): user = User( email = validated_data['email'], username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() Token.objects.create(user=user) return user ''' En apiviews.py ''' from rest_framework import generics from .serializers import UserSerializer class UserCreate(generics.CreateAPIView): authentication_classes = () permission_classes = () serializer_class = UserSerializer ''' En urls.py ''' from api.apiviews import UserCreate urlpatterns = [ path('v3/usuarios/', UserCreate.as_view(), name='usuario_crear') ] ''' Ingreso con la siquiente url: localhosts/api/v3/usuarios/ Creo un usuario y no me genera ningún error. El … -
Different fieldsets in Django Admin site depending on user group
In my django admin site I want to hide some fields to users within a group (Controllers group) What would be the best approach? Can we do something like this? This is my code, but it doesn't work: admin.py: class PriceFile(admin.ModelAdmin): if User.groups.filter(name='Controllers').exists(): fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description']})] else: fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description', 'total_sum', 'margin_percent', 'final_price']})] -
Django - Group by return only value Sum
In Django how to perform the following SQL: select sum(valor_aprovado) as vla from convenios group by ano order by ano Desired result: sum_value | -------------| 472837446.59| 163438615.51| 448397994.27| 959203234.57| 739555948.32| I'm using the following syntax, but I just want it to return the VLA field and not the ANO Convenios.objects.values_list('ano').order_by('ano').annotate(vla=Sum('valor_aprovado') Result: [(2002, Decimal('36246385105.92')), (2003, Decimal('163442260.52')), (2004, Decimal('447464292.52')), (2005, Decimal('948880015.70')), (2006, Decimal('737373593.32')), (2007, Decimal('1449818896.88')), (2008, Decimal('1812889287.82')), (2009, Decimal('2306375485.81')), (2010, Decimal('8730479758.56')), (2011, Decimal('1662088139.88')), (2012, Decimal('1886396504.43')), (2013, Decimal('535507602.69')), (2014, Decimal('4279003118.70')), (2015, Decimal('1883240765.95')), (2016, Decimal('1245291830.72')), (2017, Decimal('2161176688.18')), (2018, Decimal('1346548803.43'))] Can you help me? Thanks -
Count how many fields a model has
I am wondering if there is a way to know how many fields a model contains. Example: class Post(models.Model): title = models.TextField() body = models.TextField() sub_title = models.TextField() summary = models.TextField() I can count it but I would like to know if there is an in-built method that allows me to do so. Ideally the quesry/code would be: Post.number_of_fieds-->output--> 4 Does such a thing exist? -
I Want to create a API for a User to join Specific Group in my app
I'm trying to create a RESTApi for a user to join a specific group in my app. I have the following models: User, Groups then a ManytoMany connection of User to Groups under the field members I've tried using different view and serializers, I either Get queryset isnt iterable or null value in column "max_no_members" violates not-null constraint DETAIL: Failing row contains (11, , d85743a7-ccd9-4175-984b-86c10c75aec6, null, null, , null, 2019-07-25 18:11:34.9933+00, t, null, Monthly). views.py class GroupJoinAPIView(CreateAPIView): queryset = Groups.objects.annotate(arr=ArrayAgg('members')).values_list('id', 'arr') serializer_class = JoinGroupSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): print(sys.stderr, self.queryset) if self.request.user.id in self.queryset.all(): return 'User already in the group' else: list(self.queryset.all()).append(self.request.user.id) serializer.save() serializers.py class JoinGroupSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only = True) class Meta: model = Groups fields = ['members','users'] urls.py path('<int:pk>/join', GroupJoinAPIView.as_view(), name='members'), models.py(Groups) class Groups(models.Model): name = models.CharField(max_length = 50, unique = True) group_id = models.UUIDField(default = uuid.uuid4, editable = False) max_no_members = models.PositiveIntegerField() savings_amount = models.PositiveIntegerField() savings_type = models.CharField(max_length = 10, default = 'Monthly') description = models.TextField(blank=True) begin_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True) searchable = models.BooleanField(default = True) members = models.ManyToManyField(User, related_name='group_members') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' ) def __str__(self): return self.name I would like to be able to add an authenticated user to a … -
ApiConnectionError with Stripe Python SDK
I am developing a web app using Django and stripe payment gateway for payments. I used Ubuntu machine while integrating stripe payment(using stripe python SDK) and everything worked fine. I am running the same code again on Mac OS X system and it throws the following error: I found out different answers on StackOverFlow (found similar questions) for this but that didn't solve my issue. I tried the following things to resolve the issue: I tried connecting with a different key pair by generating it from the stripe dashboard I tried updating the OpenSSL through brew Turned off the firewall None of the above worked for me. Can someone help solve this who has faced a similar issue and resolved it? -
How to associate invited users with the inviter's Company/group?
I am using Django, django-allauth and django-invitations. I am able to successfully invite users to the platform, but I would like to associate them with the inviter's Company. I've read over the bee-keeper/django-invitations and it doesn't seem to have the information on how to do this. models.py class Company(models.Model): name = models.CharField(max_length=100, default=None) class CustomUser(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) objects = CustomUserManager() views.py @login_required def company_users(request): # Get users that are in the company's user database as well as users that have been invited company_users = CustomUser.objects.filter(company=request.user.company.id) Invitations = get_invitation_model() # I'm afraid this is going to get all invited users, not just those that belong to the company invited_users = Invitations.objects.filter() if request.method == 'POST': print(request.POST) invitees = request.POST['invitees'] invitees = re.split(',', invitees) for invitee in invitees: Invitation = get_invitation_model() try: invite = Invitation.create(invitee, inviter=request.user) invite.send_invitation(request) except IntegrityError as e: print(type(e)) print(dir(e)) return render(request, "company_users.html", { 'message': e.args, 'company_users' : company_users, 'invited_users' : invited_users, }) return render(request, 'company_users.html', { 'company_users' : company_users, 'invited_users' : invited_users, }) In the code above, users are successfully invited to the platform, but the user is not associated with the Company of the inviter. I'm also afraid that the list of invited … -
Django Code Acting Different To Code Ran Locally
When I try and run the code ' '.join([(f'<a href="{word}">{word}</a>' if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')]) in Django it throws a SyntaxError (SyntaxError at /chat invalid syntax (views.py, line 25)) however, when I run it locally there is no SyntaxError. The Python version on the webserver is 3.5, and the version I used was 3.6, but that shouldn't matter. If it does, however, what code should I use in place of what was provided?