Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django defining custom routing rules
I come from a TypeScript/Express.js background when it comes to developing APIs, and normally we have a custom AuthRouter that we structure similar to below (implementation scrubbed for client security). We do our auth by taking a Bearer token and sending it to an external API for validation: // app.ts /* Express app setup */ app.use(AuthRouter); /* Other modules that define our other app routes/services */ // AuthRouter.ts router = express.Router() router.all(config.API_BASE + '*', async (req, res, next) => { validate(req.headers.authorization) next(); }); Is there a similar way to achieve the same routing flow in Django? I've already looked into defining a custom Authentication Backend, but I'm afraid it won't play nice since it appears to be coupled to a "User" which isn't the goal, so i can't satisfy the minimum requirements. Is leaving the get_user function empty a valid approach? Ideally, I'm looking for whatever can simulate that next() callback that Express provides. If I have to setup the callback functionality myself, I will, although I think that could get pretty hairy. Any tips would be appreicated!! -
How to solve multiple http request in django googlesearch?
Actually I know the reason why this error is coming but dont know how to solve it. This problem came because of captchas which comes when anything is searched in the google.com. How to remove it .Or there is any alternative to do this. from googlesearch import search for i in search("query",tld='co.in',lang='en',num=10,stop=1,pause=2): print (i) I have already tried by reducing the resting period of the google search. -
Celery & channels conflict
I'm using the latest celery and channels.But I found that when I use channels,My celery can't receive task submit by djano.When I close the channels in django, Celery works well.Dose channels and celery has something conflict? My channels config is: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis://:*@127.0.0.1:6379/4")], }, }, } My celery config is: CELERY_ACCEPT_CONTENT = ['application/json',] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' BROKER_URL = 'redis://:*@127.0.0.1:6379/3' CELERY_RESULT_BACKEND = 'redis://:*@127.0.0.1:6379/2' And I just use python manage.py runserver to start django and channels -
Multiple subdomains with django
I'm trying to run two applications on a webserver with Django + Apache at signal.server.com and noise.server.com. Currently both URLs point to singal.server.com I've been changing options around to no avail. Here is my virtual host for the server.com which works fine WSGIPythonPath /var/www/html/d_signal WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerAdmin hello@mail.server.com ServerName www.server.com DocumentRoot /var/www/html <Directory /var/www/html/> Options Indexes FollowSymLinks AllowOverride All </Directory> ErrorLog /var/log/httpd/server.error.log CustomLog /var/log/httpd/access.log combined <IfModule mod_dir.c> DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm </IfModule> </VirtualHost> virtual config for singal.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName signal.server.com ServerAlias signal.server.com DocumentRoot /var/www/html/d_signal/d_signal WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi.py WSGIDaemonProcess signal.server.com python-home=/var/www/html/d_signal/signal_env socket-user=apache WSGIProcessGroup signal.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/d_signal> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi.py> #Require all granted </Files> </Directory> </VirtualHost> And the virtual config for noise.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName noise.server.com ServerAlias noise.server.com DocumentRoot /var/www/html/d_signal/noise WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi_noise.py WSGIDaemonProcess noise.server.com python-home=/var/www/html/d_signal/noise_env socket-user=apache WSGIProcessGroup noise.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/noise> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi_noise.py> #Require all granted </Files> </Directory> </VirtualHost> If I visit http://noise.server.com/noise/ then I get to the app I want to see. What am I missing here? -
How to get refresh token value within python / django social auth?
Strava is moving from forever tokens to refresh tokens. Part of my app portfolio is a website powered by django that uses python social auth and some django social auth bits to authorize users against their strava credentials. I'm able to get it working fine in the website but can't figure out how to get access to the refresh token values. I need the refresh token values given I have batch processes that use them to connect to strava and sync activities, etc. I expected them to be in the extra data field in the django db but alas only the token, the type and the auth_time are present. So far I've upgraded the following libraries to get this far: social_auth_core and social-auth-app-django. Any ideas? Perhaps I also need to upgrade python-social-auth? I'm assuming there is a oauth2 module that receives the direct with the extra data as url parameters. Just don't know what method that is... Thanks in advance for any suggestions. best, mike -
Using the Django admin site for specific instances of a model
I am working on my first Django app, and was thinking of using a rather abstract database schema, like this: class ListCategories(models.Model): name = models.TextField(max_length=200) type = models.TextField(max_length=200) class ListItems(models.Model): category = models.ForeignKey('ListCategories', on_delete=models.CASCADE) item = models.TextField(max_length=200) sorstorder = models.IntegerField() class ObjectType(models.Model): name = models.TextField(max_length=200) class Object(models.Model): type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) name = models.TextField(max_length=200) class ObjectTypeProperties(models.Model): name = models.TextField(max_length=200) object_type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) list_category = models.ForeignKey('ListCategories', null=True, on_delete=models.CASCADE) class ObjectProperties(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) property = models.ForeignKey('ObjectTypeProperties', on_delete=models.CASCADE) list_item = models.ForeignKey('ListItems', on_delete=models.CASCADE) result = models.TextField(max_length=200) class HistoricalNumericalData(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) object_property = models.ForeignKey('ObjectProperties', on_delete=models.CASCADE) value = models.FloatField() class Image(models.Model): object = models.OneToOneField('Object',on_delete=models.CASCADE) image = models.ImageField() def image_tag(self): return mark_safe('<img src="{}"/>'.format(self.image.url)) image_tag.short_description = 'Image' This is very flexible on the DB, as you can add object types and object properties by simply adding lines to the DB. However, I would like to use the admin interface to add new Objects to the database, and this is where this schema is tricky to use. The form would need to be different for each object type, however, as they would have not the same properties. Is there a way to register models to use with the admin site that behave differently according … -
Django - Data query based on user permissions or user group name
I'm new to Python and started a project where I have a list of Customers that are distributed across different Regions of the world. System users should only have access to users in their own region I added custom permissions for the class Customer. I'm trying to find a way to list all the Customers in one or more regions (for example: latam, emea, us, ...) based on Authentication group name or user permission. Is that possible?? views.py class CustomerListView(PermissionRequiredMixin, LoginRequiredMixin, generic.ListView): model = Customer context_object_name = 'customers' template_name = 'customers/customer.html' login_url = '/' permission_required = 'customer.view_customer' permission_denied_message = 'User has no permission to perform this action.' model.py class Region(models.Model): region_id = models.AutoField(primary_key=True) region_name = models.CharField(max_length=12, unique=True) def __str__(self): return self.region_name class Customer(models.Model): class Meta: permissions = ( ("latam_view", "Can acceess LATAM data"), ("us_view", "Can acceess US data"), ("emea_view", "Can acceess EMEA data"), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=15, null=False, blank=False, unique=True) primary_contact_name = models.CharField(max_length=24, null=False, blank=False) primary_contact_position = models.CharField(max_length=25, null=False, blank=False) primary_contact_department = models.CharField(max_length=15, null=False, blank=False) primary_contact_phone = models.CharField(max_length=17, null=False, blank=False) primary_contact_email = models.EmailField(max_length=30, null=False, blank=False) customer_region = models.ForeignKey(Region, on_delete=models.PROTECT, null=False, blank=False) auth_group = models.ForeignKey(Group, on_delete=models.PROTECT, null=False, blank=False) def __str__(self): return self.customer_name Thank you -
Django ORM with Rest API writing complex query
I wrote a functionality like if a person have related data, user cant perform update. Here you go for my models: class Person(models.Model): alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=20) class Appointment(models.Model): patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE) data = models.CharField(max_length=20) class Sales(models.Model): customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE) amount = models.FloatField() class Prescription(models.Model): patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE) details = models.CharField(max_length=100) My primary key is UUID named alias this is my api view: from django.shortcuts import render from . models import Person, Appointment, Prescription, Sales from . serializers import PersonSerializers from rest_framework.generics import RetrieveUpdateDestroyAPIView from rest_framework.response import Response from rest_framework.exceptions import APIException class PersonView(RetrieveUpdateDestroyAPIView): queryset = Person.objects.all() serializer_class = PersonSerializers lookup_field = 'alias' def update(self, request, *args, **kwargs): # person = Person.objects.filter(alias=kwargs['alias']) appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if prescription: raise APIException('CANT UPDATE') elif appointment: raise APIException('CANT UPDATE') elif sales: raise APIException('CANT UPDATE') else: self.perform_update(serializer) return Response(serializer.data) Look closely above view some query: appointment = Appointment.objects.filter(patient__alias=kwargs['alias']) prescription = Prescription.objects.filter(patient__alias=kwargs['alias']) sales = Sales.objects.filter(customer__alias=kwargs['alias']) I implement here if a Person have sales or appointment or prescription, user can't to perform update and throw an error. Everything … -
reverse relationship serializer in not returning field in json response
I have this models: class User(AbstractUser): username_validator = CustomUnicodeUsernameValidator username = models.CharField( _('username'), max_length=20, unique=True, help_text=_('Required. 15 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField( _('email address'), unique=True, null=False, blank=False, error_messages={ 'unique': _("A user with that email already exists."), }, ) And a Profile model which extends the previous model with personal user information: class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, primary_key=True, parent_link=True, related_name='profiles', related_query_name='profile', on_delete=models.CASCADE ) bio = models.CharField( max_length=100, null=True, blank=True ) birth_date = models.DateField( null=True, blank=True ) avatar_url = models.CharField( max_length=100, null=True, blank=True ) cover_url = models.CharField( max_length=100, null=True, blank=True ) These are my serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = get_user_model() fields = [ 'email', 'username', 'password', 'first_name', 'last_name', ] extra_kwargs = { 'password': {'write_only': True} } And for profile: class ProfileSerializer(serializers.HyperlinkedModelSerializer): profiles = UserSerializer( many=False, read_only=True ) class Meta: model = Profile depth = 1 fields = [ 'url', 'avatar_url', 'bio', 'birth_date', 'cover_url', 'profiles' ] I'm trying to get a response like the following when sending a GET request from http://localhost:8000/profiles/1/ : { "user": { "url": "http://www.tribsport.com:8000/users/1/", "username": "cthulhu", "email": "cthulhu@gmail.com", }, "url": "http://www.tribsport.com:8000/v1/profiles/1/", "avatarUrl": "assets/images/avatars/rick.jpeg", "bio": "Hincha de River Plate!", … -
MySQL or NoSql? What should I use for a custom "User" model
So I'm building a django-rest project for fun, I decided to use a NoSQL with the help of mongoengine (ODM for django) just to see how things will work out. My site will be like a marketplace mainly for trading music instruments. So I defined two models, one for the User and one for the Gear, the Gear model has a field of "owner" which references to the User model, while the user model has the field of "gears" which lists the posted gears he have for trading/selling. (Btw, in mongoengine, we define models as documents) I'm blocked by this specific question. How should I approach my custom "User" model? Should I store it in a relational database or it's fine to store it to a nosql? I already researched and saw that I'll lose most of django power just using a nosql (as expected) and also that storing a "User" model in a nosql is a bad idea as it is "relational". How can I know if my data is relational or not and if it's a great idea to store it into a relational db or not? I can't seem to wrap my mind with other explanations out … -
How to call a model method in views.py
I have a Post model with a custom model method that sets a post status to "DELETED" rather than actually deleting the Post object: STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) class Post(models.Model): title = models.CharField(max_length=30) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) def retire(self): self.status = STATUS_DELETED self.save() pass I am using Generic Edit Views to handle my posts: class PostDeleteView(DeleteView): model = Post success_url = reverse_lazy('delete_post_success') I want to customise the delete method to instead call the retire method in my Post model: def delete(self, request, *args, **kwargs): """ Call the retire() method on the fetched object and then redirect to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.retire() return HttpResponseRedirect(success_url) However this syntax is incorrect (it does not change the Post.status) Where am I going wrong? -
What is a better way to query a ManyToManyField for speed? entire object or id only?
I'm trying to determine the most efficient way to query a ManyToManyField for speed. I have 2 options that I know of: Add the entire object to the field Add just the id to the field If I add the object, obviously with on_delete=models.CASCADE, I get that benefit, which is huge, but I'm afraid adding it might slow query speed down because it's getting an entire object, and many of them at that. Whereas with just the id, it's just an int, so less heavy, and faster I assume. For speed only, what would you suggest? -
Access HTTP_REFERER in django Generic Views
I want to pass the previous URL in a context variable for a generic view: class PostDeleteView(DeleteView, LoginRequiredMixin): previous_url = self.request.META.get('HTTP_REFERER') ... However, I can't access either self or request. How do I go about this? -
Using category slug in url rather than pk
Right now I am able to show a product detail page by going to example.com/products/1 However I would like to be able to go example.com/<category_slug>/<product_slug> views.py def product_detail(request, pk): product = Product.objects.get(pk=pk) return render(request, 'main/product_detail.html', {'product': product}) root urls.py from main.views import product_detail path('products/<int:pk>/', product_detail, name='product-detail'), -
Use POST method to get the text of a h7 tag using Django
I am using Ajax and a POST method to store a data. To validate the data I need to take some information from a h7 tag as shown in the next code. I defined a class and an id for the h7, but the output is None instead of the h7 tag value. HTML Code: <form class= "login_assignment" method="POST" id = "log_ass"> {% csrf_token %} <br> <label><b>Name:</b></label> <h7 class = 'name'></h7> <br> <label><b>Last Name:</b></label> <h7 class = 'last_name'></h7> <br> <label><b>ID:</b></label> <h7 class = 'id_number' id = 'id_number'> </h7> <br> <label><b>Mail</b></label> <h7 class = 'mail'></h7> <br> <label><b>Login Type</b></label> <h7 class = 'login'></h7> <br> <input id = "modify" type="submit" value="Modify"> </form> Ajax Code: $(document).ready(function(){ var $regform = $(".login_assignment") $regform.submit(function(event){ var $formData = $("#log_ass").serialize() event.preventDefault() var $endpoint = window.location.href $.ajax({ method: "POST", url: '/user_login_assignment/', dataType: 'json', data: $formData, success: function(data){ if (data == 'modified') { alert('The user access have been modified'); URL Code: path('user_login_assignment/', views.user_login_assignment, name = 'user_login_assignment') View Code: def user_login_assignment(request): if request.method == 'POST': id_parameter = request.POST.get('id_number') print(id_parameter) return JsonResponse('modified', safe = False) Although the h7 tag looks empty, it actually receive information from an Ajax function, and once it received the text from the ajax function. the user press an … -
What's better to export pdf's in django python functions or Javascript ones?
I have an app where users may want to export a pdf of 1 page/view so when i searched i saw 2 approaches one is to make a button triggers a javascript function and the other is to make a view and make a button that triggers that view. So what's the best approach and why should i choose it? And is there a way that I can Inject extra HTML elements when printed as extra information pulled from the DB and Date/time to be present in the document? -
In the Wagtail how to limit what values are shown in the ManyToManyFields?
I want to limit the number of the users displayed in the ManyToManyField in the Wagtail admin. In the django version of the ModelAdmin it was enough to implement the following: def users_queryset(queryset, field="users"): if queryset and field == "users": queryset = queryset.filter(...) return queryset @django_admin.register(Partner) class PartnerAdmin(django_admin.ModelAdmin): ... def get_field_queryset(self, db, db_field, request): queryset = super().get_field_queryset(db, db_field, request) return users_queryset(queryset, db_field.name) Is there a way in the Wagtail to limit what values are shown in the ManyToManyFields? -
large jquery datatables are slow with django
I am displaying a 20k row jquery datatable through django. It is very slow to render. So I am wondering what could be the alternative approaches to process it faster e.g., through defer rendering, to load only the parts that are displayed? The database is in sql. I tried defer rendering and serverSide options in datatable options but it is still very slow. I understand that those options work only when the data is called through AJAX. The examples given in datatables website are just dumps of AJAX data into predefined columns. In my case, I am using the data as argument to generate links and create icons etc. Here is the code: <div class="container col-9 pb-5 mb-5"> <table id="drugstable" class="table table-hover" style="width: 100%"> <thead> <tr> <th scope="col">#</th> <th scope="col">Drug</th> <th scope="col">Tool</th> <th scope="col">netZoo release</th> <th scope="col">Network</th> <th scope="col">PPI <i class="far fa-question-circle" data-toggle="popover" data-trigger="hover" data-placement="top" title="Data sources" data-content="Directly download the PPI prior used for the generation of the network and check the link to the o> </i></th> <th scope="col">Motif</th> <th scope="col">Expression</th> <th scope="col">TFs</th> <th scope="col">Genes</th> <th scope="col">Reference</th> </tr> </thead> <tbody> {% for drug in drugs %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{{ drug.drugLink }}">{{ drug.drug }}</a></td> <td>{{ drug.tool }}</td> … -
How to have medium like text selector and highlighter using Django?
Medium allows users to arbitrarily select text and highlight them. How do I do that with Django? -
Selenium .click() on link doesn't give the right address
I'm testing a page. I'm writing a functional test and I want to click on a link using Selenium. The link is working (if I click on it by myself). The address should be http://127.0.0.1:8000/lists/addname/ but when selenium click on it go to http://localhost:63286/lists/addname/lists/addname/ and ofcourse it doesn't find the page (63286 is a number always different but shouldn't be the problem, if I click on the link before it does (using time.sleep, for example) I go to the page http://localhost:63286/lists/addname and it works). I'm not expert so maybe it's a trivial error and I don't know what code can be relevant, so tell me if you have to know more. My functional_tests.py: def test_can_add_name_and_read_it_after(self): # Bob go to the homepage self.browser.get(self.live_server_url) # He notice the title in header is Home self.assertIn('Home', self.browser.title) # He finds and clicks the link on the sidebar for the addname page element = self.browser.find_element_by_link_text('Add Name') # element = self.browser.find_element_by_xpath('/html/body/div/div[1]/nav/div/ul/li[2]/a') # this gives the same problem time.sleep(1) element.click() In my template.html the link appear two time but that shouldn't be the problem: <div class="navbar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans "Add Name" %}</a> </div> [...] <div class="sidebar"> <a class="nav-link" href="{% url 'lists:addname' %}">{% trans … -
Model name not visible in html
I have some problem wyth my django project. If i am not using "custom name" of my char field - its working: models.py: class Event(models.Model): name = models.CharField(max_length=50) forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} But if I try to use some 'custom name' like below, I cant see this field "custom_name". models.py: class Event(models.Model): name = models.CharField(max_length=50, name='custom_name') forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ('custom_name') event_detail.html {% extends 'base.html' %} {% block content %} <h2>{{ object.name}}</h2> {% endblock %} What is the problem? -
Image filed is not returning images in Post request Django
hi I am using this structure to upload a image . I want to use a small image saying to attach a image instead of Upload File button . When I display:none to input filed It dosen't return any image in return in post request. when I normally use this <input type="file" name="img" multiple> its returning image in request.Files <div class="image-upload"> <label for="file-up"> <img src="{% static 'MainApp/img/attachment-clip.png' %}"/> </label> <div id="img-file-upload-up" class="post-Attach-Img-file m-1"> <input onchange="showFiles_up(this.files)" type="file" id="file-up" multiple name="images" accept="image/*" style="display:none"/> </div> -
How to filter users in the queryset by the group to which they belong to?
I have a queryset with the users: <QuerySet [<User: usr0>, <User: usr1>]> I know that I can verify if the user belongs to the group like so: In [18]: usr1 = queryset[1] In [19]: usr1.groups.filter(name='Partners').exists() Out[19]: True How can I filter out all the users from the queryset which do not belong to the custom group(s)? -
Error saving model in Django Admin with many FK objects pointing to it
Using Django==2.2.4 Example of the problem using fake models, in a fake parties Django app: class CakeModel(models.Model): . . . class CandleModel(models.Model): . . . cake = models.ForeignKey( 'parties.CakeModel', related_name='candles', on_delete=models.SET_NULL, ) . . . The Django admin page: class CandleModelAdmin(admin.ModelAdmin): model = models.CandleModel extra = 0 fields = [..., some_field, ...] def get_queryset(self, request): '''Override to display less items in the admin page''' qs = super().get_queryset(request) # exclude some items from the QuerySet return limited_qs @admin.register(models.CakeModel) class CakeModelAdmin(admin.ModelAdmin): list_select_related = True inlines = (..., CandleModelAdmin, ...) list_display = (..., some_field, ...) There is no issue when a CakeModel has few CandleModel pointing to it. I have a few that have about 700, and I am testing with fake 1000. Whenever I save the page, it will take forever to save (30+ seconds) and sometimes timeout and display an error page. What can I do to prevent the CakeModel admin page from erroring out when edit a CakeModel field, and click "save" or "save and continue editing"? I might need to add another CandleModel as well, or edit a CandleModel. I tried overriding save_model(), save_related(), response_change(), but not sure how to proceed. Thank you! -
Django extending user model with a onetoone, but have several model.py files in applications
I have a django project with many applications in it, each one has models.py for pieces that are related to that portion of the project (The specific application) though I am using django's model login and user auth but I need more data with that, I saw here: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#custom-permissions That there is a way to create another model that has the extra information and make it a onetoone to the user. The thing is, this extra data I need available to all my other applications, so what models.py do I stuff this new table to be built?