Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the word 'profile' an in build feature in Django?
I am a newbie to Django. Below code is to create a user profile when new user signup for my Blog application. Doubt : - Why do we use profile instead of Profile in the last code line ? please note the capitalized word 'Profile' 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, *args,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, *args,**kwargs): instance.profile.save()''' #last code line -
Permission error with Classview extending ViewSet, how can I add permissions to non model viewset?
I am trying to create a set of endpoints that are not related to models in Django. I am using Oauth2 for authentification and I am getting all the time 403 error asking for missing permissions. How can I know which permission I am missing for this endpoint? I have tried with permission_classes = [IsAuthenticated] but it didn't work class RealTimeMonitoringViewSet(viewsets.ViewSet, NoModelBaseViewSet): extra_serializers = { "transcoding": serializers.RealTimeTranscodeSerializer, } @list_route(methods=["get"]) def transcoding(self, request): if request.user.is_anonymous(): return Response(status=status.HTTP_401_UNAUTHORIZED) if request.user.userprofile.isKmhAdmin: data = get_queue() else: data = get_queue(request.user.userprofile.selectedClientId) for jobqueue in data: try: if jobqueue['state'] != 'finished': jobqueue['start_time'] = datetime.now() jobqueue['end_time'] = datetime.now() jobqueue['run_time'] = '0 min 0 sec' jobqueue['file_name'] = Object.objects.get(pk=jobqueue.get('object_id')).name except Object.DoesNotExist: Log.exception("Transcode is returning an Object with {pk} that doesn't exist ".format(pk=jobqueue.get('object_id'))) serializer = serializers.RealTimeTranscodeSerializer(data=data, many=True) if not serializer.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) return Response(data=serializer.data) class NoModelBaseViewSet(viewsets.GenericViewSet): authentication_classes = [OAuth2Authentication, SessionAuthentication] pagination_class = pagination.PageNumberPagination filter_backends = ( filters.OrderingFilter, DjangoFilterBackend, filters.SearchFilter, ) extra_serializers = None """ Look for serializer class in self.extra_serializers, which should be a dict mapping action name (key) to serializer class (value), i.e.: class MyViewSet(BaseViewSet, ViewSet): serializer_class = MyDefaultSerializer extra_serializers = { 'list': MyListSerializer, 'my_action': MyActionSerializer, } @action def my_action: ... If there's no entry for that action then just … -
Django queryset.filter() does not work on intersection() result
given the following minex/models.py file: from uuid import uuid4 from django.db import models class Channel(models.Model): name = models.CharField(max_length=255) class Release(models.Model): version = models.CharField(max_length=255) uuid = models.CharField(max_length=100, default="") channels = models.ManyToManyField(to=Channel, related_name='releases') def save(self, *args, **kwargs): if not self.uuid: self.uuid = str(uuid4()) super(Release, self).save(*args, **kwargs) class Serial(models.Model): name = models.CharField(max_length=255) releases = models.ManyToManyField(to=Release, related_name='serials', blank=True) I found that the queryset.filter() does simply not filter returns the same results as the queryset itself). Proof: dbtest.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'minexample.settings') from minexample.wsgi import application from minex.models import Serial, Release, Channel channel = Channel.objects.create(name="stable") r1 = Release.objects.create(version="1.0") r1.channels.add(channel) r06 = Release.objects.create(version="0.6.2") r06.channels.add(channel) serial = Serial.objects.create(name="Some Serial") serial.releases.add(r06) releases = serial.releases.all().intersection(channel.releases.all()) assert r1 not in releases # works as expected assert not releases.filter(uuid=r1.uuid).exists() # assertion failed... why? Note: the last assertion does not fail if we instead did releases = serial.releases. The problem seems to be that I'm calling intersection(). I also stepped into Django's code and the WHERE statement does not contain the uuid=r1.uuid at all... Is this a bug or am I doing something wrong? -
How to determine the list of choices in a django form?
When I try to run the server I get an error that says unexpected keyword argument 'choices' COMMUNE_CHOICES=[ ('GOMBE','GOMBE'), ('BARUMBU','BARUMBU'), ('KINSHASA','KINSHASA'), ('LINGWALA','LINGWALA'), ('BANDALUNGUA','BANDALUNGUA'), ('MAKALA','MAKALA'), ('NGIRI NGIRI','NGIRI NGIRI'), ('KASA VUBU','KASA VUBU'), ('KALAMU','KALAMU'), ('LEMBA','LEMBA'), ('MATETE','MATETE'), ('NGABA','NGABA'), ('LIMETE','LIMETE'), ('MALUKU','MALUKU'), ('NSELE','NSELE'), ('MASINA','MASINA'), ('NDJILI','NDJILI'), ('KIMBANSEKE','KIMBANSEKE'), ('KISENSO','KISENSO'), ('NGALIEMA','NGALIEMA'), ('MONT NGAFULA','MONT NGAFULA'), ('KITAMBO','KITAMBO'), ('SELEMBAO','SELEMBAO'), ('BUMBU','BUMBU'), ] TYPE_SERVICE=[ ('Transport de fonds','Transport de fonds'), ('Comptage et conditionnement de fonds','Comptage et conditionnement de fonds'), ('Conditionnement comptage et transport de fonds','Conditionnement - comptage et transport de fonds') ] TYPE_SERVICE_MENSUEL=[ ('Conditionnement comptage et transport de fonds','Conditionnement - comptage et transport de fonds') ] TYPE_FACTURATION=[ ('Offre ponctuelle','Offre ponctuelle'), ('Offre mensuelle','Offre mensuelle') ] ANNEES_EXPERIENCE = ( ('1 À 5 ANS','1 À 5 ANS'), ('6 À 10 ANS','6 À 10 ANS'), ('11 À 15 ANS','11 À 15 ANS'), ('16 À 20 ANS','16 À 20 ANS'), ('PLUS DE 20 ANS','PLUS DE 20 ANS'), ) MULTINATIONAL = ( ('OUI','OUI'), ('NON','NON'), ) class EscorteForm(forms.Form): montant_dollars = forms.IntegerField(label='Montant en dollars', min_value=0) montant_franc = forms.IntegerField(label='Montant en franc congolais', min_value=0) taux_jour = forms.IntegerField(label='Taux du jour', min_value=920) zone = forms.MultipleChoiceField(choices=COMMUNE_CHOICES, widget=forms.SelectMultiple()) type_service = forms.ChoiceField(choices=TYPE_SERVICE, widget=forms.RadioSelect(attrs={'class': 'check_type_service',})) multinational = forms.ChoiceField(choices=MULTINATIONAL, widget=forms.RadioSelect(attrs={'class': 'check_type_service',})) annees_experience = forms.CharField(choices=ANNEES_EXPERIENCE ) TypeError: init() got an unexpected keyword argument 'choices' -
how can use custom permission djangorestframework
I have a project and now i want add a my new endpoint to this project that response a json . this json is very simple and not need to any serializer or queryset.but i dont know how i can use permision_class in this endpoint?second question is what is "obj" in def has_object_permission(self, request, view, obj): is?where is come from?tnx. view.py: class TeacherPostStatistic(generics.RetrieveAPIView): permission_classes = (ClassCoTeacherPermission, ClassOwnerPermission) def get_klass(self): class_id = self.kwargs['class_id'] return Class.objects.get(id=class_id) def get(self, request, *arg, **kwargs): klass = self.get_klass() response = Post.post_count_last7days(klass) return JsonResponse(response, safe=False) model.py: class Post(models.Model): # some field @classmethod def post_count_last7days(cls, klass): post_per_day_chart = {} for past_day in range(0, 7): count_post_in_past_day = cls.objects.filter(klass__exact=klass, create_date__date=date.today()-timedelta(days=past_day)).count() post_per_day_chart[past_day] = count_post_in_past_day return post_per_day_chart permission.py: # TODO: using raise inside permission class should be revised class ClassCoTeacherPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): print("in coteachers: ",obj) return self.has_perm(user=request.user, klass=obj) @classmethod def has_perm(cls, user, klass): co_teacher = ClassCoTeacherMembership.objects.filter(klass=klass, co_teacher=user) if not co_teacher.exists(): raise exc.UserIsNotCoTeacherOfTheClass return True class ClassOwnerPermission(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ @classmethod def has_perm(cls, user, klass): return klass.owner == user def has_object_permission(self, request, view, obj): print("im in ",obj) return self.has_perm(request.user, obj) if … -
How to use template tag to populate 'placeholder' on django form
I have an update form which updates a 'set' of content - I'd like for the 'set' to render almost exactly as the user expects to see it in the front end. So to render the title of the 'set' I'm trying to render it from the update form, placing the title in the 'update title' form as a placeholder. forms.py class SetEdit(forms.ModelForm): class Meta(): model = Set fields = ('title','tags',) widgets = { "title":forms.TextInput(attrs={'class':'borderless textinputclass editable', 'placeholder':'TITLE SHOULD GO HERE'}), "tags":forms.TextInput(attrs={'class':'textinputclass editable', 'placeholder':'add tags here',}), } labels = { "title":None, "tags":None, } help_texts = { 'title':None, 'tags':None, } Where it says 'title should go here' I would like to add context - {{set.title}} however, when I add that, it renders literally as {{set.title}} {{set.title}} is available in my template when I render the form, but I can't get it to render as the placeholder text - I can only get it to render outside of the form and this isn't the behaviour that I want. template.html <form class="post-action" method="POST"> {% csrf_token %} <h1 data-placeholder=' ' class='mb-3 editable'>{{set_edit.title}}{{set.title}}</h1> -
Django migrations not applied to the connected database
So i'm working on adapting an existing django (v1.11.5) project and I migrated my modifications: $ python2 manage.py makemigrations Migrations for 'genetics_ark': genetics_ark/migrations/0002_analysis_analysisvariant_annotation_cnv_decon_deconcnv_decongene_decongenecnv_deconsample_gene_genep.py - Create model Analysis - Create model AnalysisVariant - Create model Annotation - Create model Gene - Create model GenePanel - Create model Meta - Create model Model - Create model ModelRegion - Create model Panel - Create model Reference - Create model Region - Create model SamplePanel - Create model Transcript - Create model TranscriptRegion - Create model CNV - Create model Decon - Create model DeconCNV - Create model Decongene - Create model DecongeneCNV - Create model DeconSample $ python2 manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'genetics_ark_db' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode Operations … -
How to populate the Django Model with the data fetched from the external site?
From the external site thru API, the dictionary data is fetched. And I want to know how to save the set of dictionary data to the Django Model. I have tried to save the fetched data to the Django Model at the models.py but failed. In the models.py, I wrote the "def get_save(self, request)" like the following. class AirData(models.Model): co = models.DecimalField(max_digits=5, decimal_places=2) no2 = models.DecimalField(max_digits=5, decimal_places=2) so2 = models.DecimalField(max_digits=5, decimal_places=2) pm10 = models.DecimalField(max_digits=5, decimal_places=2) pm25 = models.DecimalField(max_digits=5, decimal_places=2) datatime = models.DateTimeField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) station = models.CharField(max_length=80) def get_save(self, request): url = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty" params = {'stationName': '강남구', 'dataTerm': 'month', 'pageNo': '1', 'numOfRows': '10', '_returnType': 'json', 'ServiceKey': service_key, 'ver': '1.3'} airdata_dict = get_airdata(url, service_key, params) print('airdata_dict: ', airdata_dict) self.co = airdata_dict['coValue'] self.save() But it does not save the airdata_dict, fetched from the url to the Model. I want to save the fetched data to the Model and eventually list it on the HTML. But for now, I was not able to save the fetched data. -
Django - edit html table rows and update database
I created an html table, it contains some informations. However I want to add the possibility to edit table rows text and by clicking save the database would be updated. Can someone help me ? Do I need to use Ajax ? if so how can I do that ? <table style="width:100%"> <tr> <th>Questions</th> <th>Answers</th> <th>Action</th> </tr> {% for q in questions%} <tr> <td contenteditable='true'>{{q.question}}</td> <td contenteditable='true'>{{q.answer}}</td> <td><center><a href="">Save Edit --- </a><a href="{% url 'delete_question' q.id %}">Delete</a></center></td> </tr> {%endfor%} </table> -
Using a list of classes as a model for table class in django_tables2
I tried to create a table using a class that is not related to my database in django and this class is stored in models.py as shown below (InfoServer is the class). What I wanted to do is to use this class to populate my table using django_tables2. Add models.Model as a parameter is not an option because I don't want to save this class in the database. Whenever I define the model = InfoServer in tables.py I got this error and I suppose it's because InfoServer did not take models.Model as a parameter. TypeError: descriptor 'repr' of 'object' object needs an argument Any help is appreciated. models.py class TestServeur(models.Model): nom = models.CharField(max_length=200) pid = models.CharField(max_length=200) memoire = models.IntegerField(null=True) class InfoServer: # "This is a class to test my knowledge of python" def __init__(self,p = '',c = 0,m = 0): self.pid = p self.cpu = c self.memoire = m def getData(self): return ("A server with %s memory and %s cpu" % (self.cpu,self.memoire)) views.py def index(request): return HttpResponse("Hello, world. You're at the index.") def cpu_view(request): liste = [] proc1 = Popen(['ps','-eo','pid,%cpu,%mem,comm'], stdout=PIPE, stderr=PIPE) proc2 = Popen(['grep','java'], stdin=proc1.stdout, stdout=PIPE) proc1.stdout.close() for line in iter(proc2.stdout.readlines()): clean_line = line.decode("utf-8") info_utiles = clean_line.split() pid,cpu,mem,*rest = … -
AttributeError: 'CombinedExpression' object has no attribute 'default_alias'
When I trying to subtract two different columns I got this error: >>> Product.objects.annotate(Sum('producttransactiondetails__purchase_quantity') - Sum('producttransactiondetails__sales_quantity')) Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/prism/Desktop/code/Hiren-Inventory/.env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/prism/Desktop/code/Hiren-Inventory/.env/lib/python3.6/site-packages/django/db/models/query.py", line 1032, in annotate if arg.default_alias in kwargs: AttributeError: 'CombinedExpression' object has no attribute 'default_alias' here is the models: class ProductTransactionDetails(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) product_purchase = models.ForeignKey(ProductTransaction, on_delete=models.PROTECT) purchase_quantity = models.PositiveIntegerField(default=0) sales_quantity = models.PositiveIntegerField(default=0) discount = models.DecimalField(max_digits=20, decimal_places=2) product_price = models.DecimalField(max_digits=20, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=1000, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Change field in one model while adding an entry in another model automatically in admin
I have two models in my django webapp. One is Detector which has a detector_id and current_location and the other is LocationTransfer which stores the changes to the location of each detector (one-to-many relationship with a timestamp). Thus LocationTransfer has detector_id (fk), new_location and a timestamp. The django-admin site provides me with a form to add another field in the LocationTransfer, however, while filling this form I also want to automatically change the current_location in Detector model of that detector_id. This I have to ensure because the person using the admin interface might forget to edit both the models. How do I enable this feature? No foreign link would work, obviously. Also it's fairly straightforward to do it in the normal website, but I do not know how to enable this in case of an admin. class Detector(models.Model): id = models.CharField('Detector name or ID', max_length=256, primary_key=True) class LocationTransfer(models.Model): detector_id = models.ForeignKey('Detector', on_delete=models.CASCADE) transfer_datetime = models.DateTimeField('Date and time', default=datetime.now) destination_location = models.CharField('To', max_length=256) I want the current_location of an object models.Detector change as a person adds a an entry for LocationTransfer in the admin-forms. -
Django timezone doesn't perform the right conversion
I'm struggling to figure out how timezone works in Django. On my systems I have all datetimes in UTC+00 even with a UTC+02 TIME_ZONE setting. timezone.get_default_timezone() <DstTzInfo 'Europe/Rome' RMT+0:50:00 STD> timezone.get_current_timezone() <DstTzInfo 'Europe/Rome' RMT+0:50:00 STD> I'm using PostgreSQL as backend database and I'm using the following settings: TIME_ZONE = 'Europe/Rome' USE_TZ = True The documentations about PostgreSQL say: ... if you’re using PostgreSQL, you can switch between USE_TZ = False and USE_TZ = True freely. The database connection’s time zone will be set to TIME_ZONE or UTC respectively, so that Django obtains correct datetimes in all cases. You don’t need to perform any data conversions. If from shell I try to get the date_joined field of an User, this one is UTC+00 and not converted to UTC+02 (as expected since I'm using TIME_ZONE) admin.date_joined datetime.datetime(2017, 7, 12, 15, 22, 58, tzinfo=<UTC>) str(admin.date_joined) '2017-07-12 15:22:58+00:00' Django also offer the possibility to set the favorite TIME_ZONE to end user 's with activate() method, but this is a different thing. By default when I retrieve data from the database all datetimes should be converted to the relative TIME_ZONE settings right? What I'm missing? where I get wrong? -
Remove White spaces in Django
I am trying to show a table which gets its information from SQL database using models. I can see the table however, the problem is my database has too many trailing white spaces. I need to strip these out. However, I don't know where to apply the strip function which is included in Django. Should I apply it directly in the Model or in the View or in the Table? My table file: import django_tables2 as tables from pareto.models import UutResult class OrderTable(tables.Table): step_type = tables.Column(verbose_name='Failure reason') class Meta: model = UutResult template_name = 'django_tables2/bootstrap.html' fields = ('uut_serial_number', 'uut_status', 'step_type') My view: class OrderDetail(ExportMixin, SingleTableView): template_name = 'order.html' queryset = UutResult.objects.all() context_object_name = 'uut_res' table_class = OrderTable def get_queryset(self): ordernumber = self.kwargs.get('ordernumber') return self.queryset.filter(ordernumber=ordernumber)[:40] def get_context_data(self, **kwargs): context = super(OrderDetail, self).get_context_data(**kwargs) table = OrderTable(self.get_queryset()) RequestConfig(self.request, paginate={'per_page': 30}).configure(table) context['table'] = table return context My Model: class UutResult(models.Model): ordernumber = models.CharField(db_column='OrderNumber', max_length=255, blank=True, null=True) # Field name made lowercase. uut_status = models.CharField(db_column='UUT_STATUS', max_length=32, blank=True, null=True, verbose_name='Status') # Field name made lowercase. uut_serial_number = models.CharField(db_column='UUT_SERIAL_NUMBER', max_length=255, blank=True, null=True, verbose_name='Serial Number') # Field name made lowercase. Thanks for any hint. -
django.core.exceptions.FieldError: Unsupported lookup 'quarter' for DateTimeField or join on the field not permitted
I am trying to filter objects by date of creation and sort them quarterly. I have a sample model like this class Asset(models.Model): created = models.DateTimeField(auto_now_add=True) then I have another model that connects with the Assets model this way, class Portfolio(models.Model): assets = models.ManyToManyField(Asset) // i want to find all assets created by quarter and here is what I tried def assets_total_quarterly(self): q1= self.assets.filter(created_at__quarter=1) return q1 I get this error django.core.exceptions.FieldError: Unsupported lookup 'quarter' for DateTimeField or join on the field not permitted. I followed the example here and have looked up similar questions but none solves my problem https://docs.djangoproject.com/en/2.2/ref/models/querysets/#quarter -
What is wrong with the revere function?
Django is throwing me a NoReverseMatch function but I cannot find the reason. I did check whether I use the reverse function correctly and it seems it does. I also think it is not the custom converters I created because it throws a NoReverseMatch exception. my forms.py: #some link creation function link = reverse("activate", kwargs={"key":key, "usermail":self.cleaned_data['email']} ) #sending the link to a user urls.py path('activate/<key:user_key>/<mail:usermail>', views.activate, name="activate" ), ] I just expect it to create this wonderful piece of a link and I cannot find what I am doing wrong. Maybe I am looking at the wrong place, maybe it is an integration error, I don't know. Any help is much appreciated. -
Django import-export display manytomany as a name instead of ids when exporting to csv
How do I display a manytomany column as a list of names instead of ids using Django import-export? Currently my models and resources.py looks like this and returns a csv with a list of ids for the country column: models.py class Country(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) def __str__(self): return self.name class Species(models.Model): name = models.CharField(max_length=50, null=False, blank=False) country = models.ManyToManyField(Country) def __str__(self): return self.name resources.py from import_export import resources,fields from import_export.widgets import ManyToManyWidget from .models import Species, Country class SpeciesResource(resources.ModelResource): country=fields.Field(attribute='country', widget=ManyToManyWidget(Country), column_name='Country') name = fields.Field(attribute='name', column_name='Name') class Meta: model = Species fields =('name','country') export_order = fields -
How to convert function-based views to class based views
I have a function-based view I'm trying to convert to a class-based view(DetailView). The function-based view is the equivalent of DetailView in CBV. How do I go about this? This is the function based-view def show_post(request, post): """A View to display a single post. The post variable here is the slug to a post. The slug to a post may possibly be a duplicate. So we filter all posts by the slug (which is the 1st variable here) And then select the first post returned by the filter queryset. The first post returned is, of course, the post we are trying to view. """ post = Post.objects.filter(slug=post) if post.exists(): post = post[0] else: return HttpResponseRedirect('/blog/') count_visits = None unique_views = set() if request.user.is_authenticated: post_views = PostView.objects.filter(post=post) count_visits = post_views.count() for post_view in post_views: unique_views.add(post_view.ip) else: post_view = PostView(post=post, ip=request.META.get('REMOTE_ADDR',''), http_host=request.META.get('HTTP_HOST', ''), http_referrer=request.META.get('HTTP_REFERER',''), http_user_agent=request.META.get('HTTP_USER_AGENT', ''), remote_host=request.META.get('REMOTE_HOST', '')) post_view.save() c = { 'post': post, 'comments': comments, 'new_comment': new_comment, 'similar_posts': similar_posts, 'count_visits': count_visits, 'unique_views': unique_views, 'comments_count': comments_count, 'message': message, } return render(request, 'blog/posts/post.html', c) Then I tried to convert it to a class-based view using this: class PostDetailView(DetailView): model = Post template_name = 'blog/post.html' context_object_name = 'post' def get_context_data(self, **kwargs): self.slug = get_object_or_404(Post, … -
Instance in create form has a uuid pk though shouldn't
I've come across a problem in a create form of my app which uses a model with UUID as pk. The problem is that form.instance.pk has already a UUID applied in form's __init__ method though it shouldn't. When I switch model's id to standard implementation it is indeed None. Is there a way to postpone creation of UUID till when it is truely created. This is how my model looks like: class FAQ(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) question = models.CharField(max_length=255, null=False) answer = models.CharField(max_length=1000, null=False) One solution I think I've found is to delete default kwarg from UUIDField and move creation of uuid to save(), but I wonder if there is a better one? -
Inconsistent url construction in src attribute of img tags
I'd like to understand a web programming concept. I use an AWS S3 bucket to serve some static images on a Django forum for discussions. Each user who visits the forum has an avatar, and they can upload other images too. I feed src urls into <img> tags in this format: //<aws_s3_bucket_url>/e6509592-7863-419c-bca1-75be9e1b26eb.jpg Here's what confuses me. If I do curl -i https://my_forum.com/home/ >> output.txt and view the HTML source code, I find that all avatar urls within <img> tags start with //. However, all non-avatar urls, sourced from the same s3 bucket, start with https:// in the src. An example: avatar img: <img src="//s3.ap-southeast-1.amazonaws.com/myapp/thumb/avatar/e6509592-7863-419c-bca1-75be9e1b26eb.jpg" alt="some_avatar" width="22" height="22"> non-avatar img: <img src="https://s3.ap-southeast-1.amazonaws.com/myapp/public/78e72803-29c7-4cb9-86ae-537a02c3738b.jpg" alt="some_img" itemprop="image"> Any reason why one has https:// concatenated to it, whereas the other simply starts with // (even though - to the best of my knowledge - precisely the same server side code generated both and both images appear on the same page)? I fear some kind of misconfiguration is afoot, which is why it'd be great if industry experts can chime in. I have a case of spiked-up GET requests to this same S3 bucket. This symptom might be a clue. Note: this website is configured to … -
How to append html after each action from views in django but not reload the page?
i have a question with django, in my view, when form is submited, i have for loop with my action, how can i append html in template after each action in for loop but not reload the page, i have the code below: This is my view def test_ajax(request): if request.method == 'POST': for i in range(10): # action return render(request, 'test_ajax.html') This is my template: {% extends 'base.html' %} {% block content %} <div class="container"> <h1>Hello World</h1> <form id="test"> <input type="text" id="id_username"> <button type="Submit" class="btn btn-secondary">Check Token Live</button> </form> <div id="people"> </div> </div> {% endblock content %} I want to append in people div after each action in for loop in view but not reload page, anyone can help me or have solution about this. Thanks -
How to perform search in django
i'm having issues searching the articles on a blog post i'm currently working on it keeps giving me errors this is my views.py def search(request): template = 'articles/search.html' query = request.GET.get('q') results = Article.objects.filter(Q(title__icontains=query) | Q(movie_name__icontains=query)) context = {'results': results} return render(request, template, context) and this my url.py url(r'^results/$', views.search, name="search"), and this is the error it keeps giving me http://dpaste.com/2DZQDZ3 -
After login using google (oauth) how to redirect to the home page (desired page)?
I want to redirect the user to the desired page after he logins using the Google Login. I am successfully able to goto the signin page where user enter his/her account. But after I select the gmail account it shows, error relation "social_auth_usersocialauth" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "social_au... -
Object of type 'TYPE' is not JSON serializable Django
I'm using ReactJS and Graphql as frontend and django and graphene as backend. In django I have code as follows: company = Company.objects.get(pk=input.company.id) ###### Result is <Company: Company object (14)> UserByManagerCreated.delay(company=company) And in UserByManagerCreated I have : @task def UserByManagerCreated(company): #Send emails, .... pass But I'm getting an error Object of type 'Company' is not JSON serializable Any idea? -
Android - Communication between Android devices via an app
I am working on an Android app project where users of the app can communicate with each other. The communication should be done in audio (with their voices). So, what I mean is the following scenario: When UserA speaks then its voice should be delivered to UserB in real-time. I can imagine that this must be something like a client/server model. But how exactly. What I did so far: I know how to send files like an image to a Django server by using the Django Rest Framework. Now I wanted to extend the functionality of my home project (which is an android app) by adding a kind of real-time audio chat app. Can someone tell me which sources/topics I need to learn to be able to implement such functionality ? I have 0 knowledge about the whole server technologies out there and everything seems to be very complicated when you search in Google. I just worked with Django a little bit to learn how file upload is done because I could code in Python. These posts android communication between devices and Communication between Android devices were not what I looked for. So, I would thankful for any advice in …