Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set a Model Field Type based on other model fields in django
I have the model below: class Actor(T3Model): VALUE_CHOICES = ( ('int', 'Integer'), ('str', 'String'), ('float', 'Float'), ('bool', 'Boolean') ) type = models.CharField(max_length=5, choices=VALUE_CHOICES, default='str') _value = models.CharField(max_length=100, default='', db_column='value') What I am trying to do is that based on the data selected in 'type' field, the '_value' field will check the input and convert it to the desired type. I was told using django @property could do this, but I'm not sure how it works together. So far, I have tried this just to test, but to no avail: @property def value(self): return self._value @value.setter def value(self, val): print('This is self ', self, ' and val is ', val, ' and this is self ', self.request) self._value = val If anyone has an idea or can lead me in the right direction, I will appreciate it. -
How to Specify the structure of the payload and Specify headers in every request Django URLS
Below are my urls.py I need to Specify the structure of the payload and Specify headers in every request from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register("patient", views.PatientsApiView) router.register("embryo", views.EmbroApiView) urlpatterns = [ url(r'', include(router.urls)) ] -
Apache ProxyPass not working to remote host
On remote machine 150.1.131.9 installed server with Django. I can access to it with http://150.1.131.9:8000/ Want to access by kat.local I was enabled mod_proxy in Apache 2.2 Added to vhosts.conf (imported to httpd.conf): Server name kat.local ProxyPass / http://150.1.131.9:8000/ ProxyPassReverse / http://150.1.131.9:8000/ This don't work. What I'm doing wrong? -
Force look an video ads to get rewards
Firstly, I'm soo sorry for my bad English :) I want to create an app with Django. But in this app the user can get "Credits" only when he look an advertising. When he finish to watch this, he earn "Credits". I have not idea how to ask this on google... I have no rsult about this. If you know or hanve an idea how to do that directly, It's fine too naturaly :) Thanks a lot in advance, It's my first post ! Fly' -
Child model updates Parent model in Django ForeignKey relationship
Assuming the following models schema, Parent model: class Batch(models.Model): start = models.DateTimeField() end = models.DateTimeField() One of many child models: class Data(models.Model): batch = models.ForeignKey(Batch, on_delete=models.ON_CASCADE) timestamp = models.DateTimeField() My goals is the following: to have a start field of parent model that is always updated when any child model is modified. Basically, if the timestamp of a newly data instance is older than the start field I want the start field to be updated to that instance timestamp value. In the case of deletion of the data instance which is the oldest time reference point I want batch start field to be updated to the second oldest. Vice-versa for the end field. -
plot from csv using pandas with django
I'm trying to plot from csv using pandas but the image that I get it is blank any help. def graph(request): fig = matplotlib.figure.Figure() ax = fig.add_subplot(111) data_df = pd.read_csv(r"C:\Users\csvdata.csv") data_df = pd.DataFrame(data_df) data_df.plot(ax=ax) canvas = FigureCanvas(fig) buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = HttpResponse(buf.getvalue(), content_type = 'image/png') return response thanks, -
Django sitemap.xml throwing Server Error (500) in production
My app is throwing ERROR 500 while accessing example.com/sitemap.xml Additional server configurations = Nginx+Gunicorn+postgres Here are my files sitemap.py class PostSitemap(Sitemap): changefreq = 'daily' priority = 0.9 def items(self): return Post.objects.filter(status=0) def lastmod(self, obj): return obj.created_on class StatusSitemap(Sitemap): changefreq='daily' priority = 0.9 def item(self): return Status.objects.filter(status=0) def lastmod(self, obj): url.py sitemaps = { 'posts': PostSitemap, 'status': StatusSitemap } urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='sitemaps'),] Don't know why is this showing error 500 -
I can't get the selected student in widget tweaks render_field using CreateView
I am using the following code in views.py: class MatriculaCreateView(CreateView): template_name = "website/matricula.html" model = CursoPeriodoEstudante form_class = MatriculaMembroForm success_url = reverse_lazy("website:lista_estudantes") def get_context_data(self, **kwargs): context = super(MatriculaCreateView, self).get_context_data(**kwargs) context['estudante'] = Estudante.objetos.filter(id=self.kwargs['pk']) context['pk'] = self.kwargs['pk'] return context I create the following in forms.py: class MatriculaMembroForm(forms.ModelForm): class Meta: # Modelo base model = CursoPeriodoEstudante # Campos que estarão no form fields = [ 'estudante', 'cursoPeriodo' ] And finally in the template I created this page: {% extends "website/_layouts/base.html" %} {% load widget_tweaks %} {% block title %}Matricula de Membros{% endblock %} {% block conteudo %} <div class="container mt-5"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="card"> <div class="card-body"> <h5 class="card-title">Matrícula de Membros</h5> <p class="card-text"> Complete o formulário abaixo para matricular um <code>Membro</code> em um evento. </p> <p>Membro: {{ estudante }} </p> <form method="post"> <!-- Não se esqueça dessa tag --> {% csrf_token %} <!-- Estudante --> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">Estudante</span> </div> {% render_field form.estudante class+="form-control" %} </div> <hr> <!-- Curso --> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">Evento</span> </div> {% render_field form.cursoPeriodo class+="form-control" %} </div> <hr> <div class="text-right"> <a href="{% url 'website:lista_estudantes' %}" class="btn btn-outline-primary">Voltar</a> <button class="btn btn-primary">Enviar</button> </div> </form> </div> </div> </div> </div> {% endblock %} … -
How to return pdf report for requested samples in Django rest Framework views
I need to create a Report view to return pdf report for requested samples (just the list of samples as a content). How do I go about doing it Below are my models class Patient(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=35) phone = models.CharField(max_length=18) email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) class Embryo(models.Model): name = models.CharField(max_length=45) analysis_result = models.Charfield(max_length=10) created_at = models.DateTimeField(auto_now_add=True) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) Here's a sample: [ { "name": "embryo_1", "analysis_results": "46,XX" }, { "name": "embryo_2", "analysis_results": "47,XY,+21" }, { "name": "embryo_3", "analysis_results": "46,XY" }, ] -
Make a patch() call from drf
class UserProfile(viewsets.ModelViewSet): ....... ....... #some codes here ....... @csrf_exempt def change_user_password(self, request): #some actions here if(condition): UserProfile.patch(request) .......... return ... Here I've given a sample code, which may not run. But all I need is to make a patch call to UserProfile viewset class from the change_user_password function -
Handling production, development and user local timezones
I am trying to wrap my ahead around how Django handles timezones. My project's settings use US Eastern, but locally my machine is working with GMT+2. Weirdly enough, my system is saving dates as if I were in an entirely different TZ: for instance, I just saved a date at 11:55 and it is displayed as such by the template engine, however in the database it is stored as 17:55. The 6 hour difference makes sense between US Eastern and GMT+2, but it should be the other way around? I would expect dates to be saved with the system TZ, but displayed with the local one. I thought that's how it would work as far as I understand from the documentation. I am clearly not getting it right. What is happening here? This is a production vs development scenario, but how about user local timezone? What should I do to display local dates? -
How to display data at Django Admin
i am new in Django and i want you help. I have 3 model classes and and i want to connect them. 1) class Cityhall cityhallname = models.CharField(max_length=100,verbose_name='cityhall name', blank=False) 2) class Employee employeename = models.CharField(max_length=100, verbose_name='employee name', blank=False) cityhallname = models.CharField(max_length=100,verbose_name='cityhall name', blank=False) 3) class jobs At 3rd class i want when i choose a cityhall to filters me the employees. To bring me only employess who works for the chosen city hall. How can i do that? Thanks! -
How to make live chat application using React Native and Django Rest Framework?
I want to make a live chat mobile application using Django Rest Framework and React native but i don't have any idea how to create chat app. please suggest me. Thanks in advance. -
Django Decorator 'ValidationError' object has no attribute 'is_valid'
I am trying to apply the following decorator: def has_folder_access(func): def wrapper(request, *args, **kwargs): user_id = get_user_id(kwargs['context']['request']) folder_id = kwargs['data']['folder_id'] user = get_user(user_id) if user.role != 'super_admin' and not check_file_add_access(user.id, folder_id): return func(request, *args, **kwargs) else: return serializers.ValidationError({'type': 'error', 'content': 'You do not have access to that folder.'}) return wrapper to a serializer class: @has_folder_access class FileSerializer(serializers.ModelSerializer): ... but I keep getting: File "C:\Python37\lib\site-packages\rest_framework\mixins.py", line 20, in create serializer.is_valid(raise_exception=True) AttributeError: 'ValidationError' object has no attribute 'is_valid' HTTP POST /files/ 500 Any tip/idea why this might be happening? -
Use Django Oscar Signals
I want to send an email to admin if an Order is placed (currently only user who have placed an order received the email). order_paced Oscar Signal can work for me here. For this I have already forked order app and inside this app order_placed function is created in signals.py. I have also imported signals in config.py but still this order_placed not getting fired when I am placing an order from site. Can anyone share any example of oscar signal usage ? -
sending email using mailgun
def send_complex_message(): return requests.post( "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages", auth=("api", "YOUR_API_KEY"), files=[("attachment", ("test.jpg", open("files/test.jpg","rb").read())), ("attachment", ("test.txt", open("files/test.txt","rb").read()))], data={"from": "Excited User <YOU@YOUR_DOMAIN_NAME>", "to": "foo@example.com", "cc": "baz@example.com", "bcc": "bar@example.com", "subject": "Hello", "text": "Testing some Mailgun awesomness!", "html": "<html>HTML version of the body</html>"})**strong text** this is the code from mailgun documentation. i need to access the value of "text" within "html". is there a way that i could do that. -
Django with postgres backend attribute error
I currently I am working on my first django project. The DB is modeling the structure of an Abaqus input file. Here is the Code from django.db import models as m import django.contrib.postgres as pg class node(m.Model): inputfile = m.CharField(max_length = 255) source_id = m.IntegerField() source_sim = m.CharField(max_length = 255) coordinates = pg.fields.ArrayField(m.FloatField(), size = 3) When I call manage.py makemigrations (Or just python) it gives me the error message: AttributeError: module 'django.contrib.postgres' has no attribute 'fields' When I import ArrayField in a testscript, it works: from django.contrib.postgres.fields import ArrayField from django.db import models as m a = ArrayField(m.FloatField(), size=3) print(a) >>><django.contrib.postgres.fields.array.ArrayField> I was able to migrate my classes into a TestDB without the ArrayField. My Python version 3.7.1, my Django version is 2.1.3 What's my mistake? -
django Middleware to handle crossxhr requests is not working
I wrote a middleware for Django 2.1 to handle cross-domain XHR requests, but it's not working, in fact, it's not even getting called for requests or response and does n't print anything. Settings.py XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] XS_SHARING_ALLOWED_ORIGINS = "*" MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'app_name.middleware.crossdomainxhr.XsSharing', ] crossdomainxhr.py import logging from django import http from django.conf import settings try: XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS except AttributeError: XS_SHARING_ALLOWED_ORIGINS = '*' try: XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS except AttributeError: XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] try: XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS except: XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*'] try: XS_SHARING_ALLOWED_CREDENTIALS = settings.XS_SHARING_ALLOWED_CREDENTIALS except AttributeError: XS_SHARING_ALLOWED_CREDENTIALS = 'true' class XsSharing: """ This middleware allows cross-domain XHR using the html5 postMessage API. """ def process_request(self, request): print('calling request section') if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META: response = http.HttpResponse() response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS) response['Access-Control-Allow-Headers'] = ",".join(XS_SHARING_ALLOWED_HEADERS) response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS return response return None def process_response(self, request, response): print('calling response') response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS) response['Access-Control-Allow-Headers'] = ",".join(XS_SHARING_ALLOWED_HEADERS) response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS return response Problem is if I call some URL of my app from another Django app then the request get blocked, Does anyone have any idea where I'm going wrong in this? -
The inherited c 'abstract' methods to be check also on other inherited clases, not only on child
The example is from Django, but is a Python question. I have an abstract class(mixin): class AView(ABC): def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) inherited as a Mixin by another class: class BView(Base, Aron, DetailView, ABC): ... In this abstract class I call a method get_context_data The get_context_data needs to be declared at least on one of BView, Aron, AView. If I declared/decorate the method '@abstractmethod' it is mandatory to be on BView, otherwise I receive an error. It is any possibility to check also the other inherited classes ? -
object has no attribute 'save'
'EmailPostForm' object has no attribute 'save' My views def post_share( request): if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/account/') else: form = EmailPostForm() return render(request, 'accounts/home.html', {'form': form}) Forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=40) lastname = forms.CharField(max_length=50) comments = forms.CharField(required=False, widget=forms.Textarea) specialization = forms.CharField() he gives me 'EmailPostForm' object has no attribute 'save' pls help me -
Pass value of a django model to javascript file
In models.py file i have defined a django model named VisitorInfo whose one of the field is visitor_id.I want to pass the visitor_id of visitor in a javascript file kept in the static folder of my project. myproject/static/sp.js function newTab(){ var url = "https://54.161.109.227:5000/"+visitor_id.toString(); //Here i want to pass visitor_id. //e.g if visitor_id = 36, then i want url = "https://54.161.109.227:5000/36" window.open(url);} This is VisitorInfo model. class VisitorInfo(models.Model): #To maintain clarity i am not showing all the fields. visitor_id = models.CharField(max_length=120) pages_visited = models.ManyToManyField(Page,blank=True) time_zone = models.CharField(max_length=120, null= True, blank=True) ip = models.CharField(max_length=120, null= True, blank=True) device_type = models.CharField(max_length=120, null=True) Following is the view class Live_Now(LoginRequiredMixin, TemplateView): template_name = 'dashboard/live_now.html' def get_context_data(self, **kwargs): context = super(Live_Now, self).get_context_data(**kwargs) search = self.request.GET.get('q') if search: if VisitorInfo.objects.filter(Q_filter).filter(active=True).count() >0: context['list_no'] = VisitorInfo.objects.filter(Q_filter).filter(active=True) else: context['list_no'] = "N" context['visitor_id'] = VisitorInfo.objects.first().visitor_id return context -
How to reuse parent page fields in child in Django Wagtail?
I'm trying to reuse some fields in Django Wagtail. I have main, root page HomePage as follows: class HomePage(Page): # Footer section # footer_address = models.CharField(max_length=50, blank=False, null=False, default='My company address') footer_phone = models.CharField(max_length=50, blank=False, null=False, default='My company phone') footer_email = models.CharField(max_length=50, blank=False, null=False, default='My company email') footer_website = models.CharField(max_length=50, blank=False, null=False, default='My company website') # End Footer section # def get_context(self, request): context = super().get_context(request) context['logo'] = self.logo context['address'] = self.footer_address context['phone'] = self.footer_phone context['email'] = self.footer_email context['website'] = self.footer_website return context content_panels = Page.content_panels + [ FieldRowPanel([FieldPanel('footer_address', classname="col3 footer_address"), FieldPanel('footer_phone', classname="col3 footer_phone"), FieldPanel('footer_email', classname="col3 footer_email"), FieldPanel('footer_website', classname="col3 footer_website")], heading="Footer contact info", classname="full g-py-30 footer"), ] And there can I add in admin panel address, phone, email and website. That is fine. But I want to be able to edit those fields in a subpage (Vehicles) of the HomePage. In get_context I get the HomePage as HomePage.objects.parent_of(self).live().first() and I can pass the values of those fields in template of the subpage but how can I edit or add their values in parent from child page? The code is as follows: class Vehicles(Page): vehicles_list_title = models.CharField(max_length=100, blank=False, null=False, default=_('Discover vehicles that suit you'), verbose_name=_("Title")) def get_context(self, request): # Update context … -
How to set form field for arrayfield in django model
I have a field by the name related in my model related=ArrayField(models.IntegerField(),null=True) I want this field to appear as a choicefield with multiple selection. How do i set the field in my form to achieve this? -
Problem with Updating unique together constraint Django
Tried to updating unqiue_together constraint using Django-ORM While Migrating getting following error : File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1664, in <module> main() File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/arpitkoolwal/DEV/Gateway-26Oct/gateway/gateway/manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 536, in database_forwards getattr(new_model._meta, self.option_name, set()), File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 365, in alter_unique_together self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/backends/mysql/schema.py", line 88, in _delete_composed_index return super(DatabaseSchemaEditor, self)._delete_composed_index(model, fields, *args) File "/Users/arpitkoolwal/DEV/cld/pyenv3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 394, in _delete_composed_index ", ".join(columns), ValueError: Found wrong number (0) of constraints for test(a, b) … -
Django group options list
Using Django, I have the following working example to make a list with group option: self.fields["crop"].choices = [( "First", ( ('1','aaa'), ('2','bbb'), ) ), ( "Second", ( ('3','ccc'), ) ), ] First Method: I tried to make it dynamic using the hard way: sub_item ='' grouped_items='' for k in Field.objects.filter(farm=farm): print (k.field_name ) for o in Crop.objects.filter(farming_year=farming_year, field=k ): sub_item = sub_item + '('+ str(o.id) + ',"' +o.crop_name + '"),' grouped_items= grouped_items + '("' + k.field_name + '", (' + sub_item + ')),' sub_item='' full_list_items= '[' + grouped_items + ']' print (full_list_items) self.fields["crop"].choices = full_list_items print(full_list_items ) I always get the following error: not enough values to unpack (expected 2, got 1) Second method: To test my code I copied the print(full_list_items )'s results from the terminal and assigned it directly to the crop list as shown below, and it works again!!! self.fields["crop"].choices = [( "First", ( ('1','aaa'), ('2','bbb'), ) ), ( "Second", ( ('3','ccc'), ) ), ] the question here why I cannot get the required results when I use the first method and I did when I use the second one!!