Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
build client to client to client chat through server
I'm going to build a Chat with Django (i need this for user profile) that i can access with android and iOS and web platforms. this tutorial could help me a little to understand Socket server, but this is just for a room and uses multi-threading (i have no idea if it makes trouble for many users because when i'm buying VPS, they say that, it handles just one thread! i have no idea what does it mean!) and he doesn't explain how to make client to client chat! actually i had an idea (send user destination id for the server and server can find the socket on the clients dict and sends the message to him) but i think its not safe! i need the best practice -
Ean-128 python barcode generator
Is there any python library to generate ean128 barcode. I tried 'python-barcode' , but in that library there is no option for ean128. -
Getting 502 error when I try to send email, server setup by django, postgres, nginx, gunicorn
I am following this tutorial from digital ocean How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04 Everything is working fine except when I try to send email using gmail it throws 502 bad gateway. nginx log file shows 94 upstream prematurely closed connection while reading response header from upstream Any help will be appreciated. -
How to change LetsEncrypt certbot domain?
I'm running my Django application on Digital Ocean with Ubuntu 16.04/Nginx/Gunicorn. I issued a (SSL?) certificate by running the following command: sudo certbot --authenticator webroot --webroot-path /home/user/app --installer nginx -d aaa.com -d www.aaa.com however I now want to change my domain from aaa.com to bbb.com. How do I keep my certificate for my new domain? When I ran the command to issue the certificate, I assume it created various files such as the directory .well-known - and also added code in my Nginx conf. So do I simply run the same command again, with the new domain in? sudo certbot --authenticator webroot --webroot-path /home/user/app --installer nginx -d bbb.com -d www.bbb.com or do I just change the current code and replace it with the new domain? E.g. my Nginx conf looks like this: ssl_certificate /etc/letsencrypt/live/aaa.com/fullchain.pem; # managed by Ce$ ssl_certificate_key /etc/letsencrypt/live/aaa.com/privkey.pem; # managed by $ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot I've already changed: server { listen 80; server_name 172.128.67.232 bbb.com www.bbb.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/app; } to my new domain bbb.com. Advice appreciated. -
Django: Foreign key related list
class Client(models.Model): Name = models.CharField(max_length=100,blank=False,null=False) class Expense(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) title = models.CharField(max_length=100,blank=False,null=False) amount= models.DecimalField(max_digits=8,decimal_places=2) #currency = models.CharField(max_length = 5) from_date = models.DateField(auto_now=False) to_date = models.DateField(auto_now=False) Description = models.TextField() def __unicode__(self): return self.title I have two models above where Expense should be the object of Client . how to write templating part: 1.To get list of clients . 2.If we click on the client , should get list of expenses list related to the client..... -
Hierarchical search in Mezzanine CMS
I’m new to mezzanine but I tried searching everywhere and reading the documents to no success so if there is something I missed in the documentation feel free to point me in the right direction and move on. I have a heirarchical page design with many custom page models like so: |-TopTreePage(banana) |—ChildPage(banana) |——GrandChildPage(banana) |-TopTreePage(apple) |—ChildPage(apple) |——GrandChildPage(apple) I would like to leverage the search box and drop down on the mezzanine main page to query only within the selected heirarchy. For example, user selects “banana” from the drop down and only gets pages from banana and not from apple. The hierarchies include a variety of model types so asset subclassing from the documents doesn’t seem to apply. Any help would be much appreciated. -
How to change dataframe to html table in django ?
I am sending this dataframe from django views to template html file Forecast Date 2018-01-22 05:30:00 147.01 2018-01-23 05:30:00 139.67 2018-01-24 05:30:00 140.51 2018-01-25 05:30:00 144.68 2018-01-26 05:30:00 142.97 2018-01-27 05:30:00 151.83 2018-01-28 05:30:00 151.93 2018-01-29 05:30:00 142.88 2018-01-30 05:30:00 157.31 2018-01-31 05:30:00 145.67 In this above data frame the forecast is the column and date and the values are rows , but i want the the date to be in a column and the forecast values to be in another column. This is the HTML file where i am trying to change the dataframe to html table. `<html> <body> <table> <table> {% for r in table %} {% cycle '<tr>' '' '' '' %}tr> <td>{{r.content}}</td> <{% cycle '' '' '' '</tr>' %} {% endfor %} </table> {{accuracy}} </html>` -
custom login with own model oauth2 in django
I am using Django1.11.10 with exiting database Mysql. I want to implement own oauth2 with exisitng user model without changing colums name and password algorithm.Is it possibile ? -
Django ORM conditional filter LIKE CASE WHEN THEN
I'm using Django 1.11, Postgresql 9.2, python 3.4 I want to select data based on table's column named event_type if event type is single then compare date that should be of same date (today's) date else select all dates of given (today's) date that type would be of recurring. But can't we manage this using single query? Like we do CASE and WHEN, THEN in Aggregation? I tried using Q object but no luck. I want to check when value is 'single' then add condition, else another condition. I could not find any good solution, currently I've achieved using this today = datetime.date.today().strftime('%Y-%m-%d') single_events = crm_models.EventsMeta.objects.filter( event.event_type == "single", repeat_start=today ) recurring_events = crm_models.EventsMeta.objects.filter( event.event_type == "recurring" repeat_start__lte=today ) all_events = single_events | recurring_events -
How do i migrate my wordpress site into Python Django with current data
I am new in Django, I want to convert my wordpress site into Django without loosing current data. is it possible to use with Django-CMS or Do i need to re-create site. Please help. -
How to deserialize POST request using a different Serializer
I'm trying to handle POST requests in my API endpoint using a different serializer than the one derived from Model and used for GET or PUT requests. The format of the POSTed messages is different from the Model and from GET/PUT and must be pre-processed before storing to the database. As a demo of my problem I made a very simple model and the corresponding API view and serializer: class Message(models.Model): message = models.CharField(max_length = 500) class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ('message',) class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all().order_by('-pk') serializer_class = MessageSerializer That works well. Then I tried to override the MessageViewSet.create() to handle POST requests differently. class MessageSerializer_FromTo(serializers.Serializer): sender = serializers.EmailField() recipient = serializers.EmailField() def create(self, validated_data): message = "Message from <{sender}> to <{recipient}>".format(**validated_data) return Message(message) class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all().order_by('-pk') serializer_class = MessageSerializer # Handle POST requests differently def create(self, request, format=None): message = MessageSerializer_FromTo(data = request.data) if message.is_valid(): message.save() return Response(message.data, status=status.HTTP_201_CREATED) return Response(message.errors, status=status.HTTP_400_BAD_REQUEST) Essentially I want to pass this JSON to POST /api/messages/ {"sender": "some@one.com", "recipient": "someone@else.org"} GET /api/messages/1/ should return {"message": "Message from <some@one.com> to <someone@else.org>"} However the POST fails with this message: Internal Server Error: /api/messages/ Traceback (most recent call last): … -
Cannot do axios PUT request in Django REST+React framework - Error 403
I can do GET requests via the following: axios.get('/by/f') .then(function (data) { this.setState({list: data.data}); }.bind(this)) .catch(function (error) { console.log(error); }); However, when I try a PUT request to update my django database, I get a 403 error: axios({ method: 'put', url: '/by/f', data: { item: item, frequency: frequency } }).then(function (response) { console.log(response); }); My view: class FrequencyList(APIView): def get(self, request, format=None): frequency = Frequency.objects.all() serializer = FrequencySerializer(frequency, many=True) return Response(serializer.data) def put(self, request, pk, format=None): frequency = self.get_object(pk) serializer = FrequencySerializer(frequency, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my url pattern: urlpatterns = [ path('f', views.FrequencyList.as_view()), ] my headers: headers: { 'Access-Control-Allow-Origin': '*' }, -
Django calling API using view and checking if user exist before posting
I have a view to call an api to another project. Where it will sent the user information IF user doesnt exist. Right now is user will sent/POST their information whenever they try to create an appointment. How to do and IF statement on checking if user exist on the API ? Do i do a request.get on http://127.0.0.1:8000/api/Patients/ with if else ? Here is the code: @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', params=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) # Have to post the user profile information into Patient table in another project. user_profile_attrs = { "clinicId": data["clinicId"], "immuneMeId": request.POST.get('userId'), "first_name": request.POST.get('first_name'), "last_name": request.POST.get('last_name'), "gender": request.POST.get('gender'), "mobileNo": request.POST.get('mobileNo'), "nric": request.POST.get('nric'), } # save into patient table of another project save_profile = requests.post('http://127.0.0.1:8000/api/Patients/', data=request.POST) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse(r.json()) -
how to make domain name of Vps to be working on VDS server
i have purchased a domain name robotofest.org and a hosting VPS, due to my site is made on python django, i moved to VDS(Virtual server ubuntu 16). but domain name still shows VPS server, how can i make that, when typet robotofest.org my VDS server to be working. -
video is not getting rendered on safari browser and ios devices from web service api
software configuration django : web api services angular2 : web app [frontend] Ionic1 : mobile [ ios and android ] MongoDB : database Azure blob storage : for storing images and videos Environment configuration : Django web services deployed on Ubuntu VM [ on azure platform behind loadbalancer ] Application server : gunicorn version 19.7.1 Proxy web server : Nginx version 1.12.2 details I am working on web application kind of blogs. Blog contents are displayed from web api services for single Blog, contents are retrieved by calling single service which returns Json data, Which contains urls of web api video rendering service. for ex: {data :[{"description ":"this is video1","url":"domain/videorender/v1.mp4"},{"description ":"this is video2","url":"domain/videorender/v2.mp4"}]} So when blog is accessed, respective web service will called as defined in "url" field When url is accessed, django web service method internally retrieve video from azure blob and return HttpStreaming response. Videos are getting rendered on on webapp on all browsers[ except safari], android [all devices], ios [None] Troubleshooting Tried different video formats : Not working Tried accessing video files directly stored on VM instead of accessing from azure blob [ Just to verify problem in blob to streaming reponse ] : Not working Tried … -
In Django 2.0 How do I handle a ProtectedError in generic.DeleteView
I have a generic view declared as follows: class CustomerDelete(LoginRequiredMixin,DeleteView): model = models.Customer success_url = reverse_lazy('customer-list') And a model declared as follows: class Order(models.Model): Customer = models.ForeignKey(Customer, on_delete=models.PROTECT, default=None) Shop = models.ForeignKey(Shop, on_delete=models.PROTECT, default=None) Status = models.IntegerField(choices=STATUS); Reference = models.CharField(max_length=50) Date = models.DateTimeField(default=None) LastAuthorizationDate = models.DateTimeField(default=None, null=True) LastUpdated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse_lazy('order-view', None, [self.id]) def type(self): return 'Order' def Name(self): return self.Customer.Name + ' - ' + self.Shop.Name + ' - ' + self.Reference Upon delete I get the following exception: ProtectedError at /customer/2/delete/ ("Cannot delete some instances of model 'Customer' because they are referenced through a protected foreign key: 'Order.Customer'", , , , , ]>) What would be the best class method to override and catch the exception that would allow me to redirect to the referrer with an error attached? Thanks in advance. -
Django and AWS Simple Email Service
I'm attempting to get a django site up and running and I'm trying to enable django's standard password reset service. My site is hosted by AWS EC2, so I figured I would use AWS SES for my email service. However, I can't get the smtp connection to work. Any idea on how to solve for the following error: Exception Type: SMTPSenderRefused Exception Value: (530, b'Authentication required', 'example@example.com') I've looked at the following, but I'd prefer to stay with django's built-in email back-ends if possible: https://github.com/django-ses/django-ses https://github.com/azavea/django-amazon-ses Amazon SES SMTP with Django Email Settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_PORT = 587 # (I've also tried 25, 465, & 2587) EMAIL_HOST_USER = '' EMAIL_PASSWORD = '' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'example@example.com' # but my real email address My EMAIL_HOST_USER and EMAIL_PASSWORD are set to my SMTP credentials I obtained by following the instructions at: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html Also, I was sure to verify my DEFAULT_FROM_EMAIL and my domain following these instructions: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html And DKIM is enabled and my nameservers have been updated. Any help would really be appreciated. -
Get models as variable from URL to Views django
I make Api for my database by django REST framework , i get model nickname from url.py as a variable var then use it in views.py to determine which models will use with any function i want. So i make dictionary collection of models value, use var as a key and put result model in data variable to use model as i need . The problem : when i make initial value to data it not change in function call, or i don't what's happen but when i use invalid nickname it return error also i can't make data as None value , i try a lot of things like getattr but all is failed , i think it can solved by OOP python but my knowledge about it doesn't help me . Not : i use django 2.0, database mysql, python 3.6 url.py from .views import data_detail, data_name urlpatterns = [ url(r'^(?P<var>[\w-]+)/$', data_list, name='list'), ] views.py from .models import Authors, Users, Categories value = {'user': Users, 'author': Authors, 'cate': Categories, } data = value['user'] def data_list(request, var): global data data = value[var] return DataList.as_view()(request) class DataList(ListAPIView): queryset = data.objects.all() AllDataSerializer.Meta.model = data serializer_class = AllDataSerializer -
Django -Deployment - Can't redirect from "/"
I'm new to coding, Django and deployment. I've been trying to deploy a project and I finally got the "/" page, which has a user login. The problem I have now is that it's not redirecting to the app. It's supposed to use the method "process" from my users app to redirect to the "main" page in my programs app. Not Found The requested URL /Project/process/ was not found on this server. Apache httpd.conf WSGIPythonHome C:/Python27 WSGIPythonPath C:/Python27/Lib/site-packages <VirtualHost *> ServerName pystolv WSGIScriptAlias /Project/ C:\Apache24\htdocs\Project\Project\wsgi.py <Directory C:\Apache24\htdocs\Project> Require all granted </Directory> </VirtualHost> wsgi.py import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings") sys.path.append("C:/Apache24/htdocs/Project") application = get_wsgi_application() settings.py DEBUG = False ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'apps.programs', 'apps.users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', ] LOGIN_REDIRECT_URL = 'log/index.html' ROOT_URLCONF = 'Project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is how the project/app structure looks like: > Project Project apps Program users What am I missing? Why is my app not redirecting? Any help is most appreciated. -
Django drf serializer can't get multiple instances in to_representation
My view class looks like, views.py class UserHierarchyOfOrganizations(viewsets.GenericViewSet, mixins.ListModelMixin): serializer_class = UserListOrganizationHierarchySerializer def get_queryset(self): user_ids = map(int, self.request.query_params['users'].split(',')) return User.objects.filter(id__in=list(user_ids)).select_related('organization') serializers.py class UserListOrganizationHierarchySerializer(serializers.ModelSerializer): # organization_hierarchy = serializers.ReadOnlyField() #organization_hierarchy = serializers.ListField(child=UserOrganizationHierarchySerializer(read_only=True)) organization_hierarchy = serializers.SerializerMethodField('_get_org_hierarchy') def _get_org_hierarchy(self, obj): print (type(obj)) serializer = UserOrganizationHierarchySerializer(obj, many=True) return serializer.data class Meta: model = User fields = ('organization_hierarchy',) read_only_fields = ('organization_hierarchy',) def to_representation(self, instance): print(self.get_queryset()) out = super().to_representation(instance) return out But I'm getting single User instance in _get_org_hierarchy and to_representation methods instead of multiple User instances. Is there any way to get multiple instances of User class(see get_queryset method) in UserListOrganizationHierarchySerializer serializer? What I'm trying to achieve is, { "organization_hierarchy": [ {"id": 1, "organizations": "foo -> bar"}, ] } -
How to route user model in Django for multiple databases
Suppose I have a legacy Django app with database DBOLD, and I want to write a new Django app that can access its own database DBNEW as well as the legacy database DBOLD. My new Django app models use a Django user (django.contrib.auth.User) but the old Django app also uses django.contrib.auth.User. To use multiple databases in Django, we must write database router classes that have methods db_for_write(self, model, **hints) db_for_read(self, model, hints) The problem is I don't know how to differentiate between a django.contrib.auth.User from my legacy database versus a django.contrib.auth.User from my new database. For my own models I can of course specify a database tag/id in the Meta class of each model, but I don't think I can set a tag in the User Meta class. Does anyone know how to do this? -
How can I customize and use the same html table multiple times?
In one of my of my pages I have a few tables. These tables have the same structure but differ in colors and in the data displayed. An example table might look like this: <div class="container reusable-title"> <h4 class="table_title">Table Title</h4> {% for item in items %} <div class="container row"> <div class="container col"> <h4>{{ item.date }}</h4> </div> <div class="container col"> <h4>{{ item.time }}</h4> </div> <div class="container col"> <h4>{{ item.title }}</h4> </div> <div class="container col"> <h4>{{ item.description }}</h4> </div> <div class="container col"> <h4>{{ item.price }}</h4> </div> </div> {% endfor %} </div> One of my options is to repeat the html and css code for the table each time. This way I risk errors and alot of duplicated code. I am searching for a way to make this more efficient. -
Django 1.11 Form to create multiple instances of model
I am using Django 1.11 for my first Django/Python project and have been stuck for a few days trying to understand Formsets in order to create a form that will allow the creation of multiple model instances through one form. Any assistance that could be provided to help me understand and pass this issue will be greatly appreciated! The way I have been approaching it is as follows: I have the following model: class Task(models.Model): client_name = models.ForeignKey(Client,null=True,blank=True,on_delete=models.DO_NOTHING) description = models.CharField(max_length=255) due_date = models.DateField(null=True,blank=True,default=datetime.now) assigned = models.ForeignKey(User,on_delete=models.DO_NOTHING) I have the following form based on the model: class FNTaskForm(ModelForm): class Meta: model = Task exclude = () I have created the folllowing FormSet based on the above model & form: TaskFormSet = modelformset_factory(Task, form = FNTaskForm, exclude=(),extra=2) In views.py I have: class FNTaskCreate(CreateView): model = Task form_class = FNTaskForm template_name = 'fntasks.html' def get_context_data(self, **kwargs): context = super(FNTaskCreate, self).get_context_data(**kwargs) context['formset'] = TaskFormSet(queryset=Task.objects.none()) # providing none return context And finally I render it in my html template as: <form method="post"> {% csrf_token %} <table class="table link-formset"> {% for form in formset %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label }}</th> {% endfor %} </tr> </thead> … -
Django accidently added default value to PK
So i accidently set the default value for a pk. It was when i was trying to change from default id to scheduleId by adding a AutoField to it. But it ask me to add a defualt and i input 0. Now i still get the error even after the table is deleted. Please help code (before): class Schedule(models.Model): userId = models.ForeignKey(MyUser, on_delete=models.CASCADE) code (after): class Schedule(models.Model): scheduleId = models.AutoField(primary_key=True) userId = models.ForeignKey(MyUser, on_delete=models.CASCADE) error: File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: multiple default values specified for column "scheduleId" of table "customuser_schedule" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\cherngyorng\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, … -
How can I add new feeds to a user's feed while keeping a maximum of 100 feeds (ie: deleting old feeds)
I am trying to make a feeds for my django site similar to facebook's feeds. A user can like a post A user can comment on a post A user can share a post A user has a list of friends the way I approached building the feed models by making an activity_log model(Activity) for every user (which stores the user's actions, like, share, etc...). In addition, I made a user_feed model(Feed) which should store a list of the user's friends activities, ordered by chronologically. class Activity(models.Model): date = models.DateTimeField(auto_now_add = True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') Class Feed(models.Model): profile_id: (the id of user who should see the feed) actor_id: (user who generated the activity) activity_id: foreign key to the specific activity time: the time of activity description: the verb of the activity to get the feed of a user, I am currently looping through all his friends list, taking the activities and creating feed instances. Lets say that a user's feed can have a maximum of 100 instances, How can append the new feeds and delete the old ones so that the total is still 100. I would love to hear other suggestions about …