Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms two fields with same same value one being unique with default value and other being hidden field
I have a model with two fields one unique uuid field and another urlfield class Image(models.Model): url = models.URLField() uuid = models.UUIDField(default=uuid4,unique=True) I create a django model form class ImageUploadForm(forms.ModelForm): filename = forms.HiddenInput() class Meta: model = Image fields = "__all__" in the formview uuid field will be set automatically with a unique uuid, I want to set the filename with the same uuid automatically set to uuid field by default. How can i achieve this? -
How to perform load test for certain input in my endpoint?
I want to check if my end point is able to withstand certain number of hits in a time. Let's say 40 million per second. I want a script to perform the above task. Python to be specific using requests or something like this. Can you guys help me to find reference for this problem or the script right way so I don't have spend writing ;) -
No such table in django
When I click in my table in http://127.0.0.1:8000/admin/, I see this error: OperationalError at /admin/home/table/ no such table: home_table. I ran Python manage.py makemigrations home, Python manage.py makemigrations and Python manage.py migrate but they didn't work. -
I have similar type of problems on each step
NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. 1 {% load i18n %}{% autoescape off %} 2 {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} 3 4 {% trans "Please go to the following page and choose a new password:" %} 5 {% block reset_link %} 6 {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} 7 {% endblock %} 8 {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} 9 10 {% trans "Thanks for using our site!" %} 11 12 {% blocktrans %}The {{ site_name }} team{% endblocktrans %} 13 14 {% endautoescape %} 15 -
Django Tenants Help, Explanation
I am wondering for research reasons. I am reading up about Django tenants. I understand how it works. How can I create a separate domains for each tenant ? But this should happen automatically ? In this sense. I "have" a platform like Shopify. When ever an user registers a new store it creates a new schema (Database) for the user (Tenant). But how do I handle the Domains part ? Could be sub domains for users that register without having a domain and a user that wants to use there own domain ? I understand the tenants part to this problem not the domains part. I don't mind using DNS which can be added to the domain either like Cloudflare does. Any help would be appreciated. This all needs to happen automatically TA -
Django: Pagination without changing url?
I learned the pagination basics for Django from this link: https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html However! the only problem I have is that I want to paginate without changing url. By that, I mean I need to paginate a table while there are multiple tables in a html page. How do i paginate only one table??? My code: This is the basic structure of the html template: ... <table class="uk-table uk-table-striped"> <tbody> {% for post_status in post.statusPage %} <tr> <td>{{ post_status.status_time }}</td> <td>{{ post_status.repost_count }}</td> <td>{{ post_status.comment_count }}</td> <td>{{ post_status.like_count }}</td> </tr> {% endfor %} </tbody> </table> {% if post.statusPage.has_other_pages %} <ul class="uk-pagination uk-flex-center" uk-margin> {% if post.statusPage.has_previous %} <li><a href="#"><span uk-pagination-previous></span></a></li> {% else %} <li><a><span uk-pagination-previous></span></a></li> {% endif %} {% for i in post.statusPage.paginator.page_range %} {% if post.statusPage.number == i %} <li class="uk-active"><span>{{ i }}</span></li> {% else %} <li><a href="#">{{ i }}</a></li> {% endif %} {% endfor %} {% if post.statusPage.has_next %} <li><a href="#"><span uk-pagination-next></span></a></li> {% else %} <li><a><span uk-pagination-next></span></a></li> {% endif %} </ul> {% endif %} In side the template, there are multiple post objects post Each post has its own table and paginator: post.statusPage is the page object of the post. -
Add value of javascript variable in database
I am working on a quiz with js and django. Now after the quiz is completed, a variable in javascript stores the value of final score of a user. Now there are three fields in my database(MySQL): username, password and final_score. Now I want the final score to be stored in database. How can I do that? I have gone through answers explaining the use of AJAX and jquery but still I am not able to get to my answer. -
Some thing is converting my form method to GET from POST How can i overide all javascript call
I am working with django form with some html template and stuck in a probelm where my form in html is converting my POST method to GET method how can I override all the javascripts call over custom call -
Working of Domain and sub-domain names of websites
How do sub-domain names work? Actually I want to develop platrom for CVs and I bought a domain www.cv.com, now I want the url for each user with his/her name like www.john.cv.com or www.cv.john.com? Single domain works or I have to buy sub-domains too? How its managed programmatically? -
How to insert html based on object with a input and submit button using AJAX in Django?
Let's say I have these two models: models.py from django.db import models class Model1(models.Model): input = models.CharField() output = models.CharField() class Model2(models.Model): input = models.CharField() output = models.CharField() Now let's say I have this html template with form: index.html <form> <input type="text" id="input" name="input> <input type="submit" id="input-submit> </form> <div id="output-div></div> What I want to do is when one enters into the text field and clicks on the submit button, it will take the objects from both models that have the input equal to what is entered in the text field and put their outputs into the #output-div div using ajax without refreshing while separating them by model, like so: <div id="output-div> Model1 outputs: {% for each in model1 %} {{ each.output }} {% endfor %} Model2 outputs: {% for each in model2 %} {{ each.output }} {% endfor %} </div> However, I want it so that the header for each list will not appear if the model object filter returns none. Here is the rest of the relevant incomplete code: views.py def get_inputs(request): if request.is_ajax: q = request.GET['term'] model1 = Model1.objects.filter(input=q) model2 = Model2.objects.filter(input=q) return #insert return code here ajax.js $("#output-div").click(function() { var input_val = $("#input).val() #Insert rest of code … -
Why are different URLs rendering the same view in Django 2.0?
Each time I run the command to start the server, python manage.py runserver, the first URL I load works just fine. The problem comes when I try and open another page in my web app. Whatever I loaded first after restarting the server is what renders when I try and load any other URL on the web app after it. For example, If I load the page named 'personal' after restarting the server, it will load properly. Then, if I try and load 'departmental,' the only thing that changes is the Title of the page and the URL in the address bar. The page content remains the same. Here is my urls.py file for the app: urlpatterns = [ path('', views.login_page, name='login'), path('departmental', views.departmental_dashboard, name='home'), path('personal', views.personal_dashboard, name='personal'), path('admin_dash', views.admin_dashboard, name='admin'), path('adm/<username>', views.admin_individual, name='admin_individual'), ] I have found similar posts but they all date back to Django 1.X and URL configuration was changed significantly with the release of Django 2.0. Thanks in advance! -
Is it possible to save files in Hadoop without saving them in local file system?
Is it possible to save files in Hadoop without saving them in local file system? I would like to do something like shown below however I would like to save file directly in HDFS. At the moment I save files in documents directory and only then I can save them in DHFS for instance using hadoop fs -put. class DataUploadView(GenericAPIView): def post(self, request): myfile = request.FILES['photo'] fs = FileSystemStorage(location='documents/') filename = fs.save(myfile.name, myfile) local_path = 'my/path/documents/' + str(myfile.name) hdfs_path = '/user/user1/' + str(myfile.name) run(['hadoop', 'fs', '-put', local_path, hdfs_path], shell=True) -
File folder locations in Django
I have this model: class Photos (models.Model): file = models.ImageField() description = models.CharField(max_length=255, blank=True) Purpose = models.CharField(default='None', max_length=10) uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'photo' verbose_name_plural = 'photos' def __str__(self): return self.description This model houses all of the Photos that gets uploaded to the site. I have three other models that refer to it: class Member(Models.Model): ...(various fields) Photos = models.ManytoManyForeignKey(Photos) class Unit(models.Model): ...(various fields) Photos = models.ManytoManyForeignKey(Photos) class avatar(models.Model): ...(various fields) Photos = models.ForeignKey(Photos) My question is where the files are located. I know I can add uploaded-to: parameter in the PHotos class, but is there a way that I can specialize which folder to go to based on the referring model? such as uploaded-to: '/avatars/' when the class avatar is engaged? or to /Member-Photos/ folder for the Members class? Thanks -
@login_required view decorator only accepts superuser in Django test
In a Django unit test using TestCase I want to POST data to a view that has the @login_required decorator. test_views.py: class ExportQuestionnaireTest(TestCase): def setUp(self): self.user = User.objects.create_user( username='jose', email='jose@test.com', password='passwd' ) # self.user.is_superuser = True # self.user.save() self.client.login(username=self.user, password='passwd') def test_same_questionnaire_used_in_different_steps_return_correct_content(self): data = { 'per_participant': 'on', 'action': 'run' } response = self.client.post(reverse('export_view'), data) views.py: @login_required def export_view(request, template_name="export/export_data.html"): export_form = ExportForm() ... As can be seen in test_views.py, I'm creating a user and logged in through self.client.login, then POSTing to the view. When running the test, the request doesn't achieve the view. But when I uncomment the two lines in test_views.py (i. e., make self.user superuser), the request achieves the view (verified that debbuging with Pycharm). What could be the reason? -
How to use django authentication(django.contrib.auth) with my Android app
I am using Django as my backend for my android app. I have been handling post request using @csrf-exempt annotation with my views as I wasn't able to deal with csrf verification while sending post request from android(VOLLEY LIBRARY). Now, I have to use django.contrib.auth login and logout methods but sessions aren't working when I am sending post request from android. -
Can't Parse Multipart-Encoded Files
I want to send a post request containing a photo and other information. I'm using the requests library to handle the posting of data. I did this, >>> bname = os.path.basename(man.userprofile.photo.name) >>> bname 'nas_S53FSvs.jpg' >>> headers {'Authorization': 'Token ed412f80442ed034e7', 'Content-Type': 'application/json'} >>> values {'sal': 'mrs', 'address': '10b dae', 'city': 'compton', 'state': 'ca', 'gender': 'male', 'date_of_birth': '2010-02-02'} >>> >>> files ={ ... 'json':(None, json.dumps(values), 'application/json'), ... 'photo':(bname, open(img_path, 'rb'), 'application/octet-stream') ... } >>> r = requests.post(uri, files=files, headers=headers) >>> r.text >>> And I got this error: '{"detail":"JSON parse error - \'utf-8\' codec can\'t decode byte 0xff in position 406: invalid start byte"}' When I send this requests via httpie, it's working fine. I'm using djangorestframework for my api. What am I missing? -
Django url redirect doesnt work
I am trying to learn how to work with Django framework but I have an issue I dont know how to solve. Perhaps it will be something i am overlooking but i didnt find out what. All I want to do is, when I am on the website I click on menu item and then it will redirect me to other page. I have menu item Contact with this code <li><a href="{% url 'contact' %}">Contact</a></li> so I created url, view and contact.html page. In urls.py I have path('contact', views.contact, name='contact'), In views.py I have def contact(request): return redirect('contact') And then I click on menu item and i get redirected to correct page http://127.0.0.1:8000/contact but I get this error This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS Where do I make mistake? I tried to clear my cookies but it didnt help. Any ideas? -
django-channels 2.x How to implement login required on the consumer class?
I am using django-channels 2.1.2. Since it had a drastic change from 1.x to 2.x, I would like to know the way to enforce login on the consumer class. So far: from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.consumer import SyncConsumer from doclet.models import * class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): to_room_id = self.scope['url_route']['kwargs']['to_room_id'] self.user = self.scope["user"] if self.user.is_authenticated: if self.user.rooms.filter(pk=int(to_room_id)).exists(): self.to_room = Room.objects.get(pk=int(to_room_id)) self.room_name = 'room_%s' %self.to_room.id else: self.close() #do something to create room for the user # Join room group await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() -
Django form object in custom widgets
I'm trying to make custom widgets, using the form render TemplatesSetting FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' with my own templates. I use: class MyTextInput(TextInput): template_name = 'django/forms/widgets/my_text_widget.html' def get_context(self, name, value, attrs): # I could add some stuff here context = super().get_context(name, value, attrs) return context It works fine, but I would like to be able to pass the form object to the widget, if it's possible in some way. ¿Why? To be able to render the widget conditionally, for example {% if form.[widget.name].errors %} </some/html/> ¿Is this possible? I've tried everything I could imagine, but obviously the form object is not passed to the widget. Maybe it's not a good idea! Thanks -
Custom DetailView like function returns the same set of data - Django
I have a view with a list of items and want to create a detail view of those items so i can update, enable or disable items, the problem I have is I always get the same set of data no matter what item I click on to get the details of. I've been stuck with this issues now for a couple of days i have posted this here multiple times now but never had an answer , maybe in failing to explain my issue. i would really appreciate any assistance view that handles the details def detalle_Items(request, pk): model = Transaccion template_name = 'inventario/carrito/test-template.html' try: items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk) except Transaccion.DoesNotExist: raise Http404() return render(request, template_name, {'items_update':items_update}) This is where the function gets trigerred by the green "actualizar" button no matter what button I press this is what I get: this is my views.py set of functions for carrito: # =========================================================================== # # LOGICA PARA CREAR CARRITOS # =========================================================================== # # ===================> Logica relacinado con Cortadores <=====================# def home_carrito(request): template_name = 'inventario/carrito/createcarrito.html' model = Carritos carritos = Carritos.objects.all() if carritos: return render(request, template_name, {'carritos':carritos}) else: return render(request,template_name) class CarritoCreate(CreateView): model = Carritos fields = [ 'no_carrito', 'empleado', 'activo', … -
django 2.0.7 NoReverseMatch at /posts
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. After Django goes to 2.0.7, I set up some url rules. It works locally at 127.0.0.1 on my computer, but not remotely on the machine (ubuntu 1604). code: post_list.html: {% for post in posts %} <div> <p>published: {{ post.published_date }}</p> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} blog.urls: urlpatterns = [ path('', views.home_page, name='home_page'), path('posts', views.post_list, name='post_list'), path('post/<pk>/', views.post_detail, name='post_detail'), ] blog.views: def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) Thank you in advance! -
How to map url parameter to some other filter field in Django DRF?
I have in views.py: class XYZAPIView(GenericAPIView): queryset = ABCModel.objects serializer_class = ABCModelSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('field_1',) In url, GET parameter will come as X which is field in related table to model ABCModel through field_2. I don't want my url parameter to be as field_2__X, i just want it as X, is there any way through any generic approach or any solution using filters.py ? How to map url parameter with some other parameter in filter in proper manner? -
Django How to approve the User after submitting the form and send a link?
Please help me i am puzzled i am Newbie in Django . i am having two front ends one is for my company employee and one is for customers . if a customer signup the form is send to my employee page and company employee after viewing all his details verifying his documents. how the employee approve and decline the customers.and if click on approve send an email with the link of booking car if decline it has to be deleted . for eg : john is registered in our site completed the form and employe verify his details manually from different offices and then approve that user or decline . after click on approve. john will recieve an email with the link . Please Help me to write the view Models.py class Customer(models.Model): class Meta(): db_table = "customer" verbose_name = "Customer" verbose_name_plural = "Customers" ordering = ['customer_firstname', 'customer_lastname'] customer_firstname = models.CharField( max_length=64, blank=False, null=False ) customer_lastname = models.CharField( max_length=64, blank=False, null=False ) customer_age = models.IntegerField( blank=False, null=False ) customer_idno = models.IntegerField( blank=False, null=False, ) customer_license_expire = models.DateField( blank=False, null=False) customer_phone = models.IntegerField( blank=False, null=False) customer_email = models.EmailField( blank=False ) customer_is_approved = models.NullBooleanField( blank=False, null=False ) def __str__(self): return self.customer_firstname -
Django - Google App Engine Cron 300 Error
I am able to successfully run my "job" by visiting "https://keel-test.appspot.com/tasks/test/". I tested the header using "http://www.webconfs.com/http-header-check.php" which returns a 200 response. I successfully pushed the following cron.yaml to Google App Engines: cron: - description: "test" url: /tasks/test schedule: every 8 hours I tried running the task via the GCP Console Task queues page. However, the GCP console says that the CRON job returns a 300 error. There are zero logs except that the page returns a 301 when run by CRON and 200 if the URL above is visited manually. -
Fail to get access token in Django oauth toolkit in client-credentials grant with Postman
As title says, i have an issue. I have no problem in getting access token via Postman in password grant by providing (username, password, grant_type, client_id, and client_secret). Access token was received successfully. But, when come to client-credentials grant, when i enter (client_id, client_secret and grant_type) as parameters, what i received was 500 internal server error as diagram show below. 500 internal server error . both client-id and client-secret I am pretty sure it was correct value as i got it from localhost:8000/admin Application. I realise i might need a parameter called audience a.k.a API identifier. What is audience The audience is a parameter set during authorization, and it contains the unique identifier of the target API. This is how you tell Auth0 for which API to issue an Access Token (in other words, which is the intended audience of this token). If you do not want to access a custom API, then by setting the audience to YOUR_AUTH0_DOMAIN/userinfo, you can use the opaque Access Token to retrieve the user's profile. So, i have no idea how to get audience value. So, my next question is how i get the audience value of my API server? Please guide me and …