Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django Credentials to Login to External API
I'm building an application that makes user-specific API calls to an external REST API, which uses basic Base64 authentication in the header. I've hardcoded my own for testing purposes, but am preparing to deploy and will need each user to make their own calls, using their own credentials. My initial thought was to take the user.username and user.password fields, and do a simple Base64 encoding on them to pass into the API. However, Django doesn't store the password in plain text (for obvious reasons), so this is out of the question. Is there a way to login to this external API using the logged in user's credentials? Maybe a token or a cookie of some sort? Thanks in advance! -
Django: grant temporary access to someone who is not user (with token?)
I am new to django and this confused me for a long time. I am doing a system to manage the profiles of many employees, who are not users. I want to realize the function that send a email to the employee and grant access to them so that they can upload their profile images. I read the rest-auth source code and want to do similar things but not easy. Also I think I can manually create a token, add it to the email and check permission for these tokens? Is there any efficient way to do this? -
ModuleNotFoundError: No module named 'markupsafe._comp
]2 Error message says that i don't have this model, however I could successfully install it using pip and pip freeze shows it -
Open HttpResponseRedirect in a new tab, Django
Is there any way in Django, So I can redirect to a URL via HttpResponseRedirect in a new tab from django views. return HttpResponseRedirect(url) the url value like as - https://www.google.com/maps/place/The+Reservoire/ -
Django Generic Factory
I have two questions that bother me. I'm facing an implementation where some document are related to different level of geodata and would like a factory to generate them. Let's see an example how I thought it may work: from django.contrib.gis.db import models class Country(models.Model): name = models.CharField(max_length=60) class Region(models.Model): country = models.ForeignKey(Country, on_delete=models.PROTECT) name = models.CharField(max_length=60) class Law(models.Model): text = models.CharField(max_length=60) class Meta: abstract = True class CountryLaw(Law): country = models.ForeignKey(Country, on_delete=models.CASCADE) class RegionLaw(Law): region = models.ForeignKey(Region, on_delete=models.CASCADE) # Not sure this work but the idea is here class LawManager(models.Manager): def create_law(text,geodata): if isinstance(geodata, Country): return CountryLaw(text=text, country=geodata) elif isinstance(geodata, Region) return RegionLaw(text=text, region=geodata) else: raise TypeError("Inapropriate geodata type") I would like some factory method because I have some work to fill the fields of the "Law" that is common to all law, but this example doesn't show it. My question are the following : Is there a better way to design Law objects ? Would such a manager work ? How could I access it ? I search on google and stackoverflow for answer, but don't know what keyword to use and didnt found anything that could help me.. thanks for your help ! -
The distribution Django project runs different with the local project
The distribution Django project runs different with the local project. I have a Django project, in it there is a create APIView, in my local repo, it works fine, but when I push the repo to the remote, then run it with screen -d -m python3 -m Qy.wsgi and if I access the create url, there comes the 500 Server Error error. but in my local repo, it works fine. related code are bellow: model: class Currency(models.Model): name = models.CharField(max_length=16) desc = models.CharField(max_length=128, null=True, blank=True) standard_symbol = models.CharField(max_length=8) ex_rate = models.DecimalField(decimal_places=4, default=0.0000, max_digits=10) class Meta: ordering = ['-standard_symbol'] def __str__(self): return self.name def __unicode__(self): return self.name apiview: class CurrencyCreateAPIView(CreateAPIView): serializer_class = CurrencySerializer permission_classes = [IsSuperAdminOrFinanceAdmin] queryset = Currency.objects.all() serializer: class CurrencySerializer(ModelSerializer): class Meta: model = Currency fields = "__all__" I just don't know why in the distribution it can not create with Chinese characters. I means if I write in all number, such as: name: 123, desc: 123, standard_symbol: 123, ex_rate:1233 it will create success. or if there is English Characters it will works too, but if there is Chinese Character it will report the 500 Server Error. but in the local repo it will works if it contains Chinese … -
Django REST Framework - how to implement a union-like field in ModelSerializer
I am using Django and Django REST Framework to build a RESTful API for a project. I have an abstract model class named Pet. I also created several child classes that inherit from that base class. In addition to those, I also have a House model that inherits from models.Model, and I am using the User class from django.auth module. The following is somewhat reflective of my models.py. import models from django.contrib.auth.models import User class Pet(models.Model): pass class Dog(Pet): has_tail = BooleanField() name = CharField() ... class Cat(Pet): nails_trimmed = BooleanField() name = CharField() ... class House(models.Model): pet = models.ForeignKey(Pet) owner = models.ForeignKey(User) room_quantity = models.IntegerField() Let's assume for the sake of the discussion that every House in my model structure is going to have a Pet. (i.e. not optional) I want to provide every authenticated User the capability of creating a House instance. The key thing I have in mind is that I want to make the Pet creation an implicit process. I want users to be able to create a House instance, and I want them to provide the relevant information regarding the Pet of the House as part of their request. I want to somehow infer the … -
django authenticate user from more then one template
I am using django built in login class based view for user authentication, I am also using bootstrap modals for popup login window in other pages, but the problem I am facing is when I login in popup login window, instead of authentication it just redirect me to main login page which is template_name, but I want to authenticate user with that window and redirect to same page. Here is my template. <div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Login Required</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} <input class="form-control" type="text" name="email" placeholder="Email or Phonenumber"> <input class="form-control" type="password" name="" placeholder="password"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input class="btn btn-primary" type="submit" name="" value="Login"> </form> </div> </div> Here is my url url(r'^login/$', auth_views.LoginView.as_view(template_name= 'accounts/registered/login.html', redirect_field_name='next',), name='login'), Thanks for giving me time. -
Django: time_threshold
I want to filter all the tickets which have been created within the last 15min. I use therefore the following code. I now wonder. If the people are in different timezones, will the way I wrote it here still work the way I intended (every ticket within the last 15 minutes, no matter which timezone)? For created in my models I use models.DateTimeField(auto_now_add=True). time_threshold = timezone.now() - timedelta(minutes=MINUTES_TICKET_RESERVATION) # Check ReservedItems reserved_items_qty = ReservedItem.objects.filter( ticket__id=ticket_id, created__gt=time_threshold, ).aggregate( Sum('quantity') ) -
Does django-machina come with user profiles/registration? Or does that have to be implemented on top?
I am still new to django but have created a basic blog and have installed django-machina as a forum, and everything is going well so far. I would like to have user accounts for my blog to allow for comments, as well as for the forum. What I can not find out is if django-machina already has a user accounts system (as I would think any forum would) or if I have to roll my own. If the latter that is fine I just don't want to get started when it is not necessary. The documentation is not clear on this point. -
Scrapyd jobs not starting
I integrated scrapy in my Django project following this guide Unfortunately, In any way I try, the spider jobs are not starting, even if schedule.json gives me a jobid in return. My views: @csrf_exempt @api_view(['POST']) def crawl_url(request): url = request.POST.get('url', None) # takes url from request if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc # parse the url and extract the domain unique_id = str(uuid4()) # creates a unique ID. # Custom settings for scrapy spider. # We can send anything we want to use it inside spiders and pipelines. settings = { 'unique_id': unique_id, # unique ID for each record for DB 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } # Schedule a new crawling task from scrapyd. # settings is a special argument name. # This returns an ID which belongs to this task, used to check the task status task = scrapyd.schedule('default', 'kw_spider', settings=settings, url=url, domain=domain) return JsonResponse({'task_id': task, 'unique_id': unique_id, 'status': 'started'}) @csrf_exempt @api_view(['GET']) def get_crawl_data(request): task_id = request.GET.get('task_id', None) unique_id = request.GET.get('unique_id', None) if not task_id or not unique_id: return JsonResponse({'error': 'Missing args'}) # Check status of crawling # If finished, makes query from database and get … -
How to properly handle normalization when validating fields in django
I've read the documentation when it comes to validators, form fields validation, model fields and how the entire clean and validation process works. There is one thing that I still can't grasp properly. For example if I want to allow emails that are not normalized in forms, but I dont wish to allow emails that are already in use. Would I need to normalize the email input twice? Once, inside the custom validator such as this one: def validate_unique_email(email): if Email.objects.filter(email=email).exists(): raise ValidationError( message=_("The email \"%(email)s\" is already in use."), code='duplicate_email', params={'email': email}, ) so that the database lookup is corect (all emails in database are normalized). And the again a second time before I save the email to the database. By normalizing inside a clean function (since validators dont return normalized value). It just seems very repetetive to me, so I was wondering if I missed something in the documentation? -
Django admin inline "add more item" button not working
Trying to learn stacked inlines in Django. Have a very basic setup For admin.py from django.contrib import admin from .models import Picture, Review class ReviewInline(admin.StackedInline): model = Review save_on_top = True fields = ["reviewer"] #@admin.register(Picture) class PictureAdmin(admin.ModelAdmin): save_on_top = True fields = ["painter"] inlines = [ReviewInline,] admin.site.register(Review) admin.site.register(Picture, PictureAdmin) For models.py from django.db import models class Picture(models.Model): painter = models.CharField(("painter"), max_length=255) def __str__(self): return self.painter class Review(models.Model): picture = models.ForeignKey(Picture, on_delete=models.CASCADE) reviewer = models.CharField( max_length=255) extra = 0 def __str__(self): return self.reviewer As can be seen there is no "add more item" button. I think this might be a JS issue but am not sure(I do have JS enabled in browser) Anyone has any idea? -
How to stream videos with django rest framework?
How to add video streaming feature to an API server using django rest framework. It has to serve front-end client applications(android/ios applictions, browser applications, ...). Clients have to be able to download videos for offline uses. -
How to set max task per child in Celery with Django?
I am trying to set some settings for Celery in my Django setup, but wherever I put this: CELERYD_MAX_TASKS_PER_CHILD=1 it always allows to start multiple tasks at the same time. I tried putting it in settings.py and proj.settings. My celery.py is as follows: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj', backend='redis://', broker='redis://localhost') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() -
Django ORM inner join with table sharing the same foreign key
I have three tables: order with fields: id, client_reference, price and status (status is a foreignkey linked to order_status.id) order_status with fields: id and lastupdate order_status_i18n: with fields id, order_status_id, language and label (order_status_id is also a foreignkey linked to order_status.id) what I'd like to do is to get the order_status_i18n label instead of the order_status_id based on the user language, so the SQL request would be like: SELECT o.client_reference as reference, o_s_i18n.label FROM order AS o INNER JOIN order_status_i18n AS o_s_i18n ON o.status=o_s_i18n.order_status_id WHERE o_s_i18n.language='the language'; and the Model for order contains a foreignkey attribute linked to the order_status model but not order_status_i18n, so I tried to use Order.objects.filter(some_filters).prefetch_related('status') .filter(status__in= OrderStatusI18N.objects.filter(language='the_language')) Which gives me a queryset conflict telling me that I should use the queryset for OrderStatus rather than OrderStatusI18N and I totally agree to this. But anyway, what would be the good way to manage such a request using django ORM? -
Integrate Scrapy and Django
I need to create a dynamic spider to crawl different webpages. I followed this wonderful guide until now but the proposed solution seems unofficial. It uses scrapyd and python-scrapyd-api. I wanted to know if there is a standard way to do it and, if so, if it's this one. -
django search foreign key attributes
I have a blog app using django with the following models class Category(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(unique=True,max_length=30,null=False,blank=False) class Article(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=100,null=False,blank=False) category=models.ForeignKey(Category,null=False,blank=False) summary=models.CharField(null=False,blank=False,max_length=400) content = models.TextField(null=False, blank=False) class Comment(models.Model): id=models.AutoField(primary_key=True) article=models.ForeignKey(Article,null=False,blank=False) visitor_name=models.CharField(max_length=50,null=False,blank=False) content=models.TextField(null=False,blank=False) In the admin area, I'm trying to implement a search engine that will allow the admin to search comments using multiple fields. I'm using the following code : all_queries = None keywords='' search_fields = ('visitor_name','content','article__title','article__resume','article__category__title','article__content') for keyword in keywords.split(' '): keyword_query = None for field in search_fields: each_query = Q(**{field + '__icontains': keyword}) if not keyword_query: keyword_query = each_query else: keyword_query = keyword_query | each_query if not all_queries: all_queries = keyword_query else: all_queries = all_queries & keyword_query comments = Comment.objects.filter(all_queries).distinct().order_by('-date') The problem I am having is that when I search comment by category, I get an empty queryset. Somehow article__category__title does not work. -
No update of database with UpdateView django
I know my code is not optimal as I'm only a beginner with Django so don't be too hard on me Here is my code : views.py class ComposantUpdate(UpdateView): model = configuration fields = '__all__' template_name = 'accueil/exploitation/update_composant.html' update_composant.html <form action="{% url 'composant_update' pk=composant.id %}" method="post"> {% csrf_token %} <div class="form-group"> {% for field in form %} <label class="col-md-6 offset-md-3 nom_champ"> {{field.label_tag}}</label> <input class="col-md-4 offset-md-4 contenu_champ" type="text" name="{{ field.label }}" id="{{ field.id_for_label }}" value="{{ field.value }}"/> {%endfor%} <br> <br> <button class="col-md-6 offset-md-3 btn btn-primary" type="submit" value="Update" /> Mettre à jour </button> </div> </form> urls.py path('update_composant/<int:pk>', views.ComposantUpdate.as_view(), name='composant_update'), models.py class configuration(models.Model): Num_ordre = models.CharField(max_length=15) Composant = models.CharField(max_length=15) Designation = models.CharField(max_length=15) Qte_servie = models.IntegerField() Qte_a_servir = models.IntegerField() Lot = models.CharField(max_length=15) Categorie = models.CharField(max_length=15) Famille = models.CharField(max_length=15) def __str__(self): return '%s %s %s' % (self.Num_ordre, self.Designation, self.Lot) when I go to the url of the form, all the fields get the content of the database which is what I expect but if I modify the "Lot" field and click to submit, my database is not updated at all with the new value of "Lot". DO you have any idea of why ? For information, I do get redirected to the 'composant_update' view and … -
Could not resolve URL for hyperlinked relationship using view name "post-detail".
Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Serializers.py post_detail_url = HyperlinkedRelatedField( view_name="posts-api:detail", read_only=True, lookup_field='slug' ) class PostListSerializer(ModelSerializer): class Meta: url = post_detail_url fields = ( 'id', 'url', 'user', 'title', 'content', 'created_at', 'updated_at', ) model = Post Urls.py urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list'), url(r'^create/$', PostCreateAPIView.as_view(), name='create'), url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', PostUpdateAPIView.as_view(), name='update'), url(r'^(?P<slug>[\w-]+)/delete/$', PostDeleteAPIView.as_view(), name='delete'), ] -
Multiple databases syncing in Django
I previously had SQLite default database with Django and was using it for user authentication. I am building a CMS, hence I need to store images. So I added a PostgreSQL database in settings.py and created new models for images in models.py. How do I migrate these new changes to the newly created database? If I do python manage.py migrate the newly created models will be stored in SQLite database only right? -
CreateView and UpdateView based on type of submission?
I have 2 models in Django that are connected by a one to one relationship. For example: class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=100, unique=True) date_joined = models.DateTimeField(auto_now_add=True, null=True) bio = models.CharField(max_length=200, null=True) avatar = models.CharField(max_length=200, null=True) profile = models.OneToOneField(Settings, null=True) class Profile(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) bio = models.CharField(max_length=200, null=True) avatar = models.CharField(max_length=200, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) dob = models.DateField(max_length=8, null=True) Every user may have Profile details, but some users may not have entered any information so they might not have any details provided yet (0 rows). What I'd like to do is create a settings page that either creates or updates the user profile details upon submission. Basically this is what I have so far: class ProfileSettings(UpdateView): template_name = 'oauth/profile-settings.html' form_class = ProfileForm model = Profile def get_object(self, queryset=None): return get_object_or_404(Profile, user=self.request.user) With this type of view, the update works when a user has profile details, but when the user doesn't have profile details a 404 error is displayed instead. Is it possible to display the view to the user even though he doesn't have profile details and if so, could they create profile details for themselves and then can … -
Docker - uable to connect from one container to another to specific port
I have 2 containers Selenium container selenium: image: selenium/standalone-chrome-debug container_name: eorder-dev-selenium networks: - eorder ports: - 5900:5900 and my app container eorder: build: context: . args: env: dev image: eorder_image:dev-latest container_name: eorder-dev depends_on: - eorder-postgres environment: WDB_SOCKET_SERVER: wdb WDB_NO_BROWSER_AUTO_OPEN: 1 volumes: - .:/var/www/app networks: - eorder - agesisdev_agesis ports: - 9005:443 - 8000:8000 I'm able to connect to port 8000 to the second container, where runs my app but I'm not able to do the same from selenium. They are both on the same network and I'm able to ping eorder from selenium. But not able to connect to port 8000 via telnet. Networks: networks: eorder: driver: bridge -
Django 2.0 - Python3.6 - CentOS 7 - MySQL connections
i try to install my website on a webserver which is in CentOS 7 with Django 2.0.6 and Python 3.6. I installed : mysql-connector = 2.1.6, mysql-connector-python = 8.0.11, MySQL-python = 1.2.5, mysqlclient = 1.3.12, PyMySQL = 0.8.1 And when i run this command : python3.6 manage.py migrate I have this error : File "MYPYTHONPATH/python3.6/site-packages/django/db/backends/mysql/base.py", line 36, in <module> raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 1.2.5 But in the base.py file : try: import MySQLdb as Database except ImportError as err: raise ImproperlyConfigured( 'Error loading MySQLdb module.\n' 'Did you install mysqlclient?' ) from err from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip from MySQLdb.converters import conversions # isort:skip # Some of these import MySQLdb, so import them after checking if it's installed. from .client import DatabaseClient # isort:skip from .creation import DatabaseCreation # isort:skip from .features import DatabaseFeatures # isort:skip from .introspection import DatabaseIntrospection # isort:skip from .operations import DatabaseOperations # isort:skip from .schema import DatabaseSchemaEditor # isort:skip from .validation import DatabaseValidation # isort:skip version = Database.version_info if version < (1, 3, 3): raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__) I … -
Django and postgresql schemas
I've been trying to solve this one all week, help very much appreciated. I have various schemas in a postgres db and I would like to be able to map to them from within the same or across different django apps. Some of the schemas are : samples excavation geophysics ... I have tried the recommended way, but I'm not getting any data to display from the schemas, I can only connect to the public schema with managed tables. Here is the database connections from the settings.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=django,public' }, 'NAME': 'gygaia', 'USER': 'appuser', 'PASSWORD': 'secret', }, 'samples': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=samples,public' }, 'NAME': 'gygaia', 'USER': 'appuser', 'PASSWORD': 'secret', }, } source: https://www.amvtek.com/blog/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/ In the model.py I add: from django.db import models # Create your models here. class Storage(models.Model): #id = models.IntegerField(default=0) storage_id = models.AutoField(primary_key=True) store_name = models.CharField(max_length=200, default='') address_1 = models.CharField(max_length=200, default='') address_2 = models.CharField(max_length=200, default='') region = models.CharField(max_length=200, default='') city = models.CharField(max_length=200, default='') zip = models.CharField(max_length=200, default='') country = models.CharField(max_length=200, default="Turkey") user = models.CharField(max_length=200, default="Gygaia") datestamp = models.DateTimeField(auto_now=True) class Meta(): managed=False db_table = 'samples\".\"store' I don't want to restrict schemas to users, and …