Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django error when connecting with odoo xmlrpc
I can not connect with odoo in any way, this is what I am doing view.py class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class ProxiedTransport(Transport): def set_proxy(self, host, port=None, headers=None): self.proxy = host, port self.proxy_headers = headers def make_connection(self, host): connection = http.client.HTTPConnection(*self.proxy) connection.set_tunnel(host, headers=self.proxy_headers) self._connection = host, connection return connection class ResUser(ViewSet): url = 'http://localhost' db = 'odoo8' username = 'admin' password = 'admin' def list(self,request,format=None): p = ProxiedTransport() p.set_proxy('proxy.server',8080) common = ServerProxy('{}/xmlrpc/2/common'.format(self.url),p) uid = common.authenticate(self.db,self.username,self.password,{}) return Response({}) but he throws me an error Request Method: GET Request URL: http://localhost:8000/odoo-api/res/ Django Version: 2.1 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python3.6/socket.py in getaddrinfo, line 745 that could be happening? -
How to add string to a query django
I am writing a function which will get the value of a model depending upon the input of user. How to join a query and string From models import countries Def abc(country): If country == "USA": A1= miles else: A1 = kms P1 = countries.object.get(name__exact=country). + A1 return P1 Error Type error : unsupported operand types for +: 'countries' and str -
How do you deploy a flask or django application using jwilder/nginx-proxy?
I'm looking into moving some of our web servers to docker containers. The jwilder/nginx-proxy image looks interesting, and seems to do what we want, but how would one properly deploy a flask application in a container, and have it work with the jwilder/nginx-proxy server? To be clear, the flask application would also be running in a docker container. In a separate, but related question, how would one do this for a django app? It looks like there's a popular tiangolo/uwsgi-nginx-flask image, and a similar dockerfiles/django-uwsgi-nginx image. In this setup, from what I understand, the nginx-proxy container would direct traffic to the uwsgi-nginx-flask or django-uwsgi-nginx container. Is this a common way to do this? The main thought I had was that in such a setup, we're running extra instances of nginx - one for every python/django app. Is this common? Or is it possible/beneficial/common to somehow have the nginx-proxy talk directly to uwsgi within the python app container? I see that the nginx-proxy image has a VIRTUAL_PROTO=uwsgi option that other containers can be started with. Is this something that can be used to make things more efficient? Or is it more effort than it's worth? -
Need ideas for how to created a dynamically create a CSV download of products purchased
I’m tasked with creating my first production site using Django + eCommerce with a slightly unique twist. I need some help discovering apps that can help me pull this off quickly without reinventing the wheel. Basically, the product is a dynamically created CSV file generated from the customer’s selections. Meaning, the “shop” displays a table of “products” with a checkbox beside each. No pictures or fancy layout... Just a row of cells for each item containing details... Name, sku, color, size, etc. The customer would select items from the list (or select all search results, giving them even the items on subsequent pages of results without having to click through), click “add to cart“, and then complete the transaction. However, rather than a ridiculously long email or shopping cart screen, the customer would receive either a link or email containing a CSV of the product and all of its related fields. Essentially, a CSV of the listing that would normally show up a cart page. That CSV is the product final they are purchasing. Are there existing e-commerce apps that could handle that delivery out of the box? I can build the shopping cart and product database in my sleep. … -
Docker: Django & Postgres > How to connect
I followed this tutorial here to setup Docker with Django. It works perfectly now and also my Postgres database seems to be installed. Where it fails for me is connecting with Postico (macOS) to my Postgres that's running in the container. Anyone who has experience in that, is it possible to connect 'from the outside' with eg. Postico to this container? Currently I typed in: Host localhost User postgres Password postgres But I am not sure about the password, as in the tutorial I never set any. -
Redirecting HTTP<->HTTPS inside Django project
I have a project 'Online store' based on Django. How can I make the following redirection (inside Django): HTTP -> HTTPS if registered user entered his account. HTTPS -> HTTP if user opened store catalog. -
Django REST API: run operations after put request
I am trying to find a clean way to process some task after successfully completes the PUT request for REST API. I am using post_update() function but its never being called. Here is my code class portfolio_crud(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'id' serializer_class = user_ticker_portfolio_serializer def get_queryset(self): return user_ticker_portfolio.objects.filter(user = self.request.user) def put(self, request, *args, **kwargs): print("got the put request to update portfolio") return self.update(request, *args, **kwargs) def post_update(self, serializer): print("got the post save call") #never executed -
return objects pointing to other objects in django
I have a model UserSelect class UserSelect(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bowler = models.ForeignKey(Bowlers, on_delete=models.CASCADE, related_name='bowlers', null=True, blank=True) batsman = models.ForeignKey(Batsmen, on_delete=models.CASCADE, related_name='batsman', null=True, blank=True) team = models.IntegerField(blank=True, default='1') which is pointing to my two models bowler and batsman using foreign key I am calling this model values in my view as def team(request, pk): user_sel = UserSelect.objects.filter(user=request.user, team=pk) context = { 'user_sel': user_sel, } return render(request, 'team_analysis.html', context) here I am getting all objects by giving pk but how do I access data of my other two models bowler and batsman through it in views? -
Another case of: save() prohibited to prevent data loss due to unsaved related object - on DJango 2.1
Unlike other case of "ValueError: save() prohibited to prevent data loss due to unsaved related object 'source'." my case is where I am not calling the save() function of my models directly but rather overriding admin.ModelAdmin's save_model() method. Somehow this override causes simple admin "save" to fail (with the error described above) if inline objects are added on the first creation of the "main" object (in my example: I add Feed objects, via ChannelInline to a new Source object) My Code: class Feed(models.Model): source = models.ForeignKey('Source', null=True, on_delete=models.CASCADE) title = models.CharField(max_length=256) url = models.CharField(max_length=512) enabled = models.BooleanField(default=True) class Source(models.Model): brand = models.CharField(max_length=256) domain = models.CharField(max_length=256) class ChannelInline(admin.TabularInline): model = Feed min_num = 0 class SourceAdmin(admin.ModelAdmin): list_display = ['id', 'brand', 'domain'] inlines = [ChannelInline, ] def save_model(self, request, obj, form, change): obj.brand = form.data['brand'] obj.domain = form.data['domain'] -
Countdown timer with Django Channels
I've been working on a Django application where users can play with each other some kind of a turn-based game (the gameplay itself is done via Django Channels, ie. websockets and consumers). As anticipated, the user has finite, fixed time for making their moves. I know how to get the "time left" value for the user (every move in the game is stored in a separate record in the database so it is easy to calculate such things from theirs timestamps) but how should I (or the program, or - more precisely - Django Channels' consumer) know that the user timed out? Naturally, solving this in the front-end is out of the question for obvious reasons. I saw similar posts here but firstly, not with Django Channels (and I presume that it might make a difference by offering some kind of an easier solution) and secondly, they only showed how to make a simple action (liking printing to the console or deleting a record in the database) when the time expired and not to comunicate with Django Channels' consumer. Thanks in advance. -
Why I am not seeing any tables created by django orm in aws rds postgres database?
I created aws rds postgres db-instance and connected it with my local django application in settings.py which is working fine connection wise as well as for any crud operations to the db by my application. I installed DB Navigator plugin in my PyCharm and tried to connect with my aws rds which is working fine too. But when I tried to browse the tables with names defined in models.py or django's default tables like auth_group, auth_user, etc. I am not seeing any one. I did the makemigrations and migrate also and models registered in admin.py is also showing in my admin UI and I am also able to add a value in the DB. Please refer to image. DB Navigator database browser I tried with sql console also but didn't find any tables. I am new to aws rds and I am not sure if I am missing anything aws way to do. -
Django: HTTP 301 redirect
Whenever someone visits www.example.com or https://www.example.com I want to forward visitors to https://example.com I first thought I can do this in my DNS Records, but DNSimple support said it has to be via 301 redirects. Anyone can help me how to solve this in Django? -
Saving custom form field in Django Allauth
I'm using Django Allauth SignUpForm class. Before, I had an arrangement that only included username, email, and password these fields worked as they are native to the class. However, I decided to remove username and replace it with full_name as shown with my updated model: class User(AbstractBaseUser): full_name = models.CharField(max_length=30) username = models.CharField(max_length=15, unique=True, error_messages={ 'unique': ("Username has already been taken.") }) email = models.EmailField(max_length=100, unique=True, error_messages={ 'unique': "Email has already been taken." }) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] I migrated my database to achieve the new changes. I then made a new arrangement to my form: class RegisterForm(SignupForm): full_name = forms.CharField(max_length=30) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['full_name'].widget = forms.TextInput(attrs={"placeholder": ""}) self.fields['email'].widget = forms.EmailInput(attrs={"placeholder": ""}) self.fields['email'].label = "Email" self.fields['password1'].widget = forms.PasswordInput(attrs={"placeholder": ""}) def save(self, request): user = super(RegisterForm, self).save(request) user.full_name = clean_data["full_name"] user.save() return user However, this does not create a new user whenever I try to sign up. What am I doing wrong? How can I make it so that the user is created and given a username automatically generated based on their name? -
Django MainThread and DummyThread
i am new to python/django and have limited knowledge, below is the problem i am facing. i am developing an openstack-horizon dashboard app which has multiple Class-based Views(Views, Tabs, workflows) which access data from a single class(Class M) which talks to external client API and holds data. Scenario 1: when i run app as manage.py runserver, the app runs on single thread and every thing works as expected (data shared between multiple views and class M is consistent and there is only 1 instance of class M. Scenario 2: when i run the app normally without runserver, i observe that MainThread and DummyThread are present across different Views and each thread has different instance of class M and data is not consistent. i also observer that the thread change occur after class M talks to the external client API i do not have any control of creating these threads. kindly let me know if i have not expressed the issue properly and need more information. Best Regards. -
Variable value inside a string variable in Django Template
I have saved text as text="Hey" + {{ student.name }} I am providing both text and student to my html template page. Is there a way such that it shows the name of the student instead of the string. -
Is it possible to add placeholder in model form?
This is my models.py file class Report_item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255) item_type = models.CharField(default="", max_length=100) location = models.CharField(max_length=60) city = models.CharField(max_length=60) date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True,null=True) publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image") def __str__(self): return self.title + " " + str(self.publish) def get_absolute_url(self): return reverse('feed:detail', kwargs={'pk': self.pk}) class Meta: ordering = ["-date"] I add the model form in my template. The views.py file is the following: class ReportCreate(generic.CreateView): model = Report_item fields = ['title', 'item_type', 'location', 'city', 'image', 'Description'] def form_valid(self, form): self.object = form.save(commit=False) self.object.owner = self.request.user self.object.save() return FormMixin.form_valid(self, form) I want to add a placeholder in my form. Is it possible to add the placeholder in model form? Please add one placeholder for the one field and rest I will do. -
How to map paths in django 2.1 2018
# My app path urlpatterns = [ path("", views.home, name="home"), path("show_category/<slug:category_slug>/", views.show_category, name="catalog_category"), path("<slug:product_slug>/", views.show_product, name="catalog_product") ] def show_category(request, category_slug): context={ "c" : get_object_or_404(Category, slug=category_slug), "products" : c.product_set.all(), "page_title" : c.name, } template_name="catalog/category.html" return render(request, template_name, context) # Project path urlpatterns = [ path("admin/", admin.site.urls), path("", include("catalog.urls")), path("catalog/", include("catalog.urls")), path("cart/", include("cart.urls")), ] I cant see any of my urls except my homepage and I'm new to django I see no documentation on it or anything in stackoverflow.. Any help would be great. I dont want to do regex yet trying to learn how to do urls in both ways path and repath. Thank You! -
need help ASAP, SOS. django projects html post do not redirect o process
i suppose to create a new book, review and author using models base. but for some reason, when i click on the "reviews and add book" it should validate the author, book and review and create corresponding objects instances. but it just change my url bar from "/books/add" to "/books/add/process" (which is the process link). without doing actually validate and objects creation. please help and explain in detail. much apperciated. here are my code of html, models.py, urls.py and views.py that should be all the necessary file or code to answer my question. thanks again for helping. enter code here [add_all.html][1] [add_all(part2).html][2] [models(1).py][3] [models(2).py][4] [urls.py][5] [views.py][6] [1]: https://i.stack.imgur.com/XL1ky.png [2]: https://i.stack.imgur.com/h2JbI.png [3]: https://i.stack.imgur.com/hH696.png [4]: https://i.stack.imgur.com/xlhmh.png [5]: https://i.stack.imgur.com/2SiLj.png [6]: https://i.stack.imgur.com/7ShOL.png -
Django Girls tutorial "no module found" error
I'm following the Django girls tutorial. [ https://tutorial.djangogirls.org/en/django_urls/ ]. At the URLs section of the tutorial, my server doesn't restart. Instead, I get this error: Performing system checks... Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x10f842048> Traceback (most recent call last): File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 396, in check for pattern in self.url_patterns: File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/Aaron/Desktop/dev./Django/practice/myvenv/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
How would I edit an exsisting model field entry?
I have a model with a charfield that keeps tracks of the ongoing status of a bill: from django.db import models import datetime class due(models.Model): PAYED = ( ("paid", "Paid"), ("un-paid", "Un-Paid") ) bill = models.CharField(max_length=70) amount = models.CharField(max_length=70) status = models.CharField(choices=PAYED, max_length=128) class Meta: verbose_name_plural = "Bill" def __str__(self): return "{} for {} is: {}".format(self.bill, self.amount, self.status) I'm going to render every bill I have through a django template to easily see it. The problem I'm having is I'm not sure how on the same page I can edit the status of the bill. What would I need to do on the back end to make that functionality through the use a button or a form? -
Data from view to serializer in django rest api
I am struggling with this problem for a while. Ok here is my serializer: from rest_framework import serializers from happytourist.models import PointsInterestData class PointsInterestSerializer(serializers.ModelSerializer, serializers.Serializer): distance = serializers.IntegerField(default=None) class Meta: model = PointsInterestData fields = ('name', 'latitude', 'longtitude', 'distance') read_only_fields = fields from rest_framework import generics from .serializers import PointsInterestSerializer from happytourist.models import PointsInterestData class PointsInterestList(generics.ListCreateAPIView, generics.ListAPIView): serializer_class = PointsInterestSerializer def get_queryset(self): queryset = PointsInterestData.objects.all() return queryset def create(self, request, *args, **kwargs): user_latitude = request.POST.get('latitude') user_longtitude = request.POST.get('longtitude') radius = request.POST.get('radius') usergeodata = {'latitude': user_latitude, 'longtitude': user_longtitude, 'radius': radius} return usergeodata def get_coordinates(self): latitude = PointsInterestData.objects.model.latitude longtitude = PointsInterestData.objects.model.longtitude geodata = {"latitude": latitude, "longtitude": longtitude} return geodata What I want to do is to change distance parameter in serializer according to the view. I need to write a function in view which result will be calculated distance (i know how to make this) and this result will be put into serializer (which i do not know how to make it) -
uWSGI not creating Unix socket at specified location
I've worked with Nginx and uWSGI numerous times, but I've never seen socket not being created even when specified in explicitly. My uWSGI config (/etc/uwsgi/sites/my_site.ini) is quite simple: [uwsgi] project = my_site base = /root chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chmod-socket = 664 vacuum = true As visible, uWSGI must create socket with 644 permissions. Nginx server configuration (/etc/nginx/nginx.conf) is quite simple as well: server { listen 80; server_name mysite.com www.mysite.com; location /static/ { root /root/my_site; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/my_site.sock; } } After making these configurations, I executed following commands: sudo systemctl daemon-reload sudo systemctl restart uwsgi sudo systemctl restart nginx sudo systemctl status uwsgi sudo systemctl status nginx Everything was fine according to commands above, but Nginx returned 502 bad gateway) error when visiting website. Thus I checked /var/log/nginx/error.log/: 2018/08/25 19:33:10 [crit] 14920#0: *3 connect() to unix:/run/uwsgi/my_site.sock failed (2: No such file or directory) while connecting to upstream, client: xx.xxx.xxx.xx, server: my_site.com, request: "GET / HTTP/1.1", upstream: $ Shortly uWSGI is not creating a unix socket at the specified path in the configuration above, what could be the problem? -
Django Related Object empty queryset on clean()
I'm trying access a list of related objects through the "related_set.all()" method whenever a model is saved from Django Admin. No matter what I do however the QuerySet is always empty... Here's what it looks like (I've removed a lot of (hopefully) irrelevant stuff) class Board(models.Model): group = models.OneToOneField(Group, on_delete=models.CASCADE) def clean(self): roles = self.role_set.all() # This just returns <QuerySet []> ... validation, etc.... class Role(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) members = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Funny thing is that it used to work, but after setting the User to be the AUTH_USER_MODEL (after a lot of refactoring) it suddenly stopped returning anything in the QuerySet... For what it matters I'm using a NestedStackedInline in the Admin panel, and what I hope to achieve is that whenever the "Save"-button in the admin panel is called, it should calle the clean() method on the Role-class, call the clean() method on the Board-class and upon success call the save() method on both. I've been troubleshooting this for way too long now and would really appreciate if anyone have some pointers or ideas. -
Django user authentication with custom model and mongo db
I'm not really expierenced in django and graph databases. But I need to set up user authentication with MongoDB in django. I'm using pymongo for conneection to database bypassing django db settings. But I still want to use django authentication. In order to do so, I actually should create a user model extended from AbstractBaseUser, create custom user manager extended from BaseUserManager, and register AUTH_USER_MODEL in settings. I'ce also created and registered custom backend which returns my custom user object. But the problem is that it seems like django tries to verify my User model using its database (sqlite in settings) and it can't find USERNAME_FIELD (because actually I'm not using this db. I don't know how to tell django that it don't need to care about it. Can you provide any suggestions, please? -
pre tag adds extra new lines and whitespace
I have a queryset using which I want to display values of a certain field. {% for pm in paymentmethods %} {{pm.get_payment_method_display}} {% endfor %} This works fine but it adds lots of extra space per get_payment_method_display. This is how it ends up looking like: How do i get rid of the extra white space and just show each item in a new line. This is how my pre css class looks like: pre { white-space: pre-wrap; /* Since CSS 2.1 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ }