Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is not a valid regular expression in urls.py
I faced the problem, I need to add functions to the file urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P[0-9]+)/$', views.detail, name='detail'), url(r'^(?P[0-9]+)/answer/$', views.answer, name='answer') ] Running the server I get "^(?P[0-9]+)/$" is not a valid regular expression: unknown extension ?P[ Tell me what's wrong... -
Celery chain not working on django
My purpose is call two task sequentially When task1 is done call task2. I have made this until now For execute my task in sequential way I use the chain method that I found in documentation. But my task don't need the result of the last task to work as the documentation said. So, I define CELERY_IGNORE_RESULT = True to the chain method not take the result from the previous task when executed. Here is how I'm doing my code task.py @app.task def task1(param): ... @app.task def task2(param): .... views.py from .task import task1, task2 from celery import chain chain(task1.delay(identifier), task2.delay(identifier))().get() Every attempt I made i got this error: unsupported operand type(s) for |: 'AsyncResult' and 'AsyncResult' Does anyone know how can I fix this? -
Multi database - each database writes to self and read from self
tried to google as much as I could but couldn't find what I was looking for.. So idea is: There is one Master Database from which one you read users authentication process. And there is other many databases which ones keep information(her users, files and other) just to itself(it writes to itself and reads) but Master can reach them all. And if master makes changes to lets say to database structure - all fields should change but information on those database should stay (but master can change any of those database information). It's like Multi-master but I do not want that other masters could reach other databases, but only write to itself. Any tips? -
Django language change on contry name
i want to change site language on country name i've already got country name by ip adress just want to change language of the site for diff countries here is my code for ip and country guessing g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip) else: city = 'None' # default city # if city['country_name'] == 'United Kingdom': # lang ='en' in if section i want to change site language if country will be UK but i have no idea how any one help ? as i know i should change url to /en or something like that -
Django filters to return HTML that will be rendered in the template
my_text my_text = '''The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects. Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.''' my_filter @register.filter(is_safe=True) def format_description(description): text = '' for i in description.split('\n'): text += ('<p class="site-description">' + i + '</p>') return text My problem I get the output in raw html like so <p class="site-description">The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects.</p><p class="site-description"> </p><p class="site-description"> Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.</p> instead of The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects. Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does. -
Use json response from browser cache instead of reloading it when use browser Back button
I have a Django project with a view that has a lot of python code to calculate data for specific table in its template (2-4 seconds). To improve user experience I decided to load template immediately with empty table and get necessary data via jQuery $.getJSON request. $(document).ready(function() { $(function() { $.getJSON(devices_list_JSON, function(data){ // fill table data ... } } } I've done so and it works fine except of one issue. When I go to some page and back to my view using browser Back button, browser make JSON request again. And I want to use cached version as it was in a view that calculated all data in its python code. How can I do so? (I use Google Chrome 68.0.3440.106 browser) -
Get Primary key of an element(Teacher) which is referred in student model django
I am new to Django and I don't know how to get access the primary key. I have a scenerio in which there are two users teacher and student one-to-one relationship to abstract user.In my case teachers create student accounts, I have created teachers accounts successfully,I also want to save students registered by the teachers which also know how to do it,but my problems is I also want to save the teacher in student model who registered that particular student, for this I want to get that teacher object(The teacher which is adding student at that time) which I can't,can someone provide suggestions or code how to do it? Models.py File: class User(AbstractUser): is_student=models.BooleanField(default="False") is_prof=models.BooleanField(default="False") class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) designation=models.CharField(max_length=30) class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) teacher=models.ForeignKey(Teacher,on_delete=models.CASCADE,default="") batch=models.CharField(max_length=30) Below my piece of approach to add student, user is created successfully but what to do in last line student= so I can teacher object through teacher_id: obj= User.objects.create_user (username=myids[iterate],password=passwords[iterate], is_student=True,is_prof=False) obj.save() Student.objects.create(user=obj,teacher=(What to do?),batch="F-14") -
Django annotate related field
I want to optimize a simple django query to prefetch all the latest values. sensors = Sensor.objects.all() Here is the model: class Sensor: last_record_at = models.DateTimeField(null=True, blank=True) class Record: value = models.FloatField() sensor = models.ForeignKey('hardware.Sensor', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Before, Sensor model had a foreign key (last record) to record and all the records could be retrieved simply by adding: .select_related('last_record') To optimize the database, I removed that foreign key and replaced it with a datetime field named last_record_at. I am using Django 2.0 and I am wondering if there is a pretty ORM way to retrieve all the sensors and last records in one (or two) query using subqueries, annotation or prefetching. Something like (it does not work): record_sub_query = Record.objects.filter( created=OuterRef('last_record_at'), sensor_id=OuterRef('pk') ) sensors = Sensor.objects.all().annotate( last_record=Subquery(record_sub_query[:1]) ) or using prefetch: sensors = Sensor.objects.all().prefetch_related( Prefetch( 'records', queryset=Record.objects.filter(created=F('sensor__last_record_at')) ) ) The only alternative I see is writing Raw SQL for this rather simple problem. -
Unittesting Emails in Django
Django 2.0.6 I have some unit tests in my Django app. One of the tests needs to verify that emails are sent. How can I achieve this? I read the django docs about testing email sending and email sending in generall via django.core.mail but somehow im still not understanding what is happening and why it is happening the way it does. Hopefully I can explain it as precisely as possible, so here we go: In my testcase I have a instance and call a function with it. The called function is creating and formating an E-Mail instance and is sending it via Email.send(email, '', '', subject, content) After the function call is finished I use the mail.outbox to check if there is an email but there isn't, but why? If I try to do it manually via mail.send_mail(...) and check the outbox afterwards, it works. I also have checked via print satements that the function which should be called, is actually called. All I want is to see is that the email has been succesfully sent. Here is my code sample: def test_send_email_to_teacher(self): # Generate test data self.instance.send_email_to_teachers_preferences_link() print(len(mail.outbox)) #self.assertEqual(len(mail.outbox), 1) -
Django: Handling discount codes
I am currently building a Django application where visitors can buy an online course. I now want to implement the possibility to provide discount codes. As these discount codes should be limited by quantity I now have the following implementation idea: Guest visits www.page.com?discount=TEST The model discount contains the fields discount_codes & max qty. I will check here, if the code exists. Also, I have to count all entries in my order model that used the discount code TEST. My order model contains the foreign_key field 'redeemed_discounts'). As soon the user clicks on Pay (via Stripe) I'll once again count all the orders in my order model which contain 'TEST' to make sure, the 'max_qty' is not reached meanwhile. Now I can charge the visitor. Would you consider this as good implemented or do you see any problems with the way I am planning to do it? -
Hosting Django on a private server
I have been provided with a private server space in a an organisation to host a django application I have been working on. I have the public IP, username, password and ssh port. There is no cpanel. How can i host the project and make it appear in the internet with the domain name not the public IP? Thanks. -
using xvfb for buffering a video and showing it in website
I am developing a web server with django. I need to buffer a video with xvfb and then send this video to the client. I can display the data of xvfb with vcn and I can show the video with this command: xvfb-run -s "-screen 0 1400x900x24" bash x11vnc -display : 0 but what is shown is in server side and I do not have any idea of how I can show this video in my website. Is there any way of saving the output ? -
How to define a Django template method to avoid duplicating of code in html?
I have two different UI pages. In both of the pages, 2 out of 5 html elements are common and rest 3 are not. How to avoid duplicating the code? Current implementation: {% if page 1 %} <h3> Page 1 </h3> <div> Element1 </div> <div> Element2 </div> <div> Element3 </div> <div> Element4 </div> <div> Element5 </div> {% elif page 2 %} <h3> Page 2 </h3> <div> Element1 </div> <div> Element2 </div> <div> Element6 </div> <div> Element7 </div> <div> Element8 </div> How to avoid writing Element1 Element2 twice ? -
Django - get object by id and clone it
I tried to clone model instance object and save it to the database on this way: some_object = ModelName.objects.get(id=1) some_object.id = None some.object.save() But in ModelName i have ManyToMany relation with another model and after saving i didn't get data from another model. How is possible to solve this? -
django-axes failed login attempts are not consecutive
django-axes 4.1.0. I set the following configurations for django-axes which are working fine to soe limit: AXES_LOCK_OUT_AT_FAILURE = config('AXES_LOCK_OUT_AT_FAILURE', default=True, cast=bool) AXES_FAILURE_LIMIT = config('AXES_FAILURE_LIMIT', default=5, cast=int) AXES_COOLOFF_TIME = config('AXES_COOLOFF_TIME', default=24, cast=int) The user will be blocked after 5 failed login attempts as defined in the configs the problem is that they are not consecutive. If the user does 4 failed attempts followed by 1 successful login attempt and the a 1 failed login attempt, he will be blocked. Is there a way to force the failed login attempts to be consecutive in order to block the user from logging in? -
Viloating non-null constraint when creating new user in custom form
Im trying to create a custom registration form via AbstractUser but somehow it does not create entry in database (register new user basically) my models.py class UserProfile(AbstractBaseUser): user = models.OneToOneField(User) username = models.CharField(max_length=32, blank=False) name = models.CharField(max_length=128, blank=False) second_name = models.CharField(max_length=128, blank=False) middle_name = models.CharField(max_length=128, blank=True) birthday = models.DateField(null=False) country = models.CharField(max_length=128) city = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) email = models.EmailField(blank=False, default='youremail@email.com', null=False) USERNAME_FIELD = 'username' my forms.py from index.models import UserProfile, User from django import forms from datetime import datetime from django.contrib.auth.forms import UserCreationForm class UserForm(UserCreationForm): middle_name = forms.CharField(required=False) class Meta: model = UserProfile fields = ['email', 'name', 'second_name', 'password1', 'password2', 'country', 'city', 'birthday'] widgets = { 'birthday': forms.SelectDateWidget(years=range(1900, datetime.now().year + 1)) } when I try to test and register user i get this error null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (13, 1900-01-01, Switzerland, Montreux, 2018-08-23 12:07:07.367219+00, null, email@email.ch, , Alex, test, None, null, somepasswordhash...). -
regex and fnFilter issue with DataTable 1.10
I am using DataTable with Django 1.9. I currently have a table that can be filtered by a column "name". I would like to allow the user to filter by using regex expressions but when I try to filter the datas with "." or "^.", the result is empty. The params of the fnFilter function are correct : otable_{{item.id}}.fnFilter($(this).val(), 4, true, false); Thanks in advance. -
Django: Running tests after ditching South
I currently updating an old Django app to 1.11. The app I'm updating was still running on Django 1.4 and thus using south for migrations. I followed the instructions from the documentation and the app is now using the migration system from Django, and all seems to be working fine (I can add, edit and delete objects in the admin). However, I've also added some tests but Django is unable to run them and crashes with the following error: django.db.utils.ProgrammingError: column "item_id" of relation "logo_studentgroupwordscore" already exists One of the steps in the documentation was executing the new migrations with the fake parameter (manage.py migrate --fake-initial) to fix this error, so I was wondering if I need to take similar steps when running the manage.py test command for the test database, but now such option seems to be available. Does anyone know what I am doing wrong? -
After adding django-debug to App, getting "'djdt' is not a registered namespace"
My question is about setting up to use django-debug. I'm getting the above error after installing the toolbar and panel, and enabling these in my app. I've seen many suggestions for this or a closely related issue, and nothing I've tried has helped. The specific error, during template rendering of /usr/lib/python3.6/site-packages/debug_toolbar/templates/debug_toolbar/base.html, is from: 16 data-render-panel-url="{% url 'djdt:render_panel' %}" My relevant settings.py entries: DEBUG = True INSTALLED_APPS = [ 'debug_toolbar', 'debug_panel', ... ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'debug_panel.middleware.DebugPanelMiddleware', ... ] INTERNAL_IPS = ['127.0.0.1',] Appended to my urls.py: if settings.DEBUG: try: import debug_toolbar urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls))] except ImportError: pass What I've tried: changing the order of these Middleware entries in settings.py (first, middle and last) adding a namespace attribute to my urlpatterns entry Thanks for any further suggestions. -
Wagtail - running tests raises psycopg2.IntegrityError: null value in column "draft_title" violates not-null constraint
I'm trying to run my app tests (Django v1.11 and Wagtail v2.2.1) but I'm getting an exception while the test is creating the test databases: Traceback (most recent call last): File "/home/fleon/.virtualenvs/virmyasb/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "draft_title" violates not-null constraint DETAIL: Failing row contains (3, 0001, 1, 1, Root, root, t, f, /, , f, , null, null, f, 1, null, f, null, null, null, null, null). When looking at the full stack trace, there's an error inside a Wagtail file: [...] lib/python3.6/site-packages/wagtail/core/migrations/0001_squashed_0016_change_page_url_path_to_text_field.py", line 30, in initial_data [...] The Python code in such line is: # Create root page root = Page.objects.create( title="Root", slug='root', content_type=page_content_type, path='0001', depth=1, numchild=1, url_path='/', ) which is not setting the draft_title, hence violating the not-null constraint. Please note I'm using two different databases (base.py): DATABASES = { 'default': dj_database_url.config(), 'thedbname': { 'NAME': 'thedbname', 'ENGINE': 'django.db.backends.mysql', 'USER': 'thedbuser', 'PASSWORD': '***', 'HOST': 'myhost', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } } and the tests work if I remove the MySQL database (?) -
Django: Stripe integration + form.is_valid()
I'm using Stripe checkout and as the 'form' is provided by Stripe, I don't have the typical form.is_valid() check included, as the form is provided and generated through the Stripe script. I now wonder if it's still 'safe' the way I built it? view.py from django.views.generic import TemplateView from django.conf import settings import stripe class IndexView(TemplateView): amount = 9999 template_name = 'website/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_pub_key'] = settings.STRIPE_PUB_KEY return context def post(self, request, *args, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY token = request.POST.get('stripeToken') email = request.POST.get('stripeEmail') # Move into models charge = stripe.Charge.create( amount=9999, currency='EUR', description='My Description', source=token, receipt_email=email, ) return self.get(request, *args, **kwargs) template.html <form method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ stripe_pub_key }}" data-amount="9999" data-currency="EUR" data-name="Lighthouse Courses" data-description="Paul's Masterclass" data-image="{% static 'img/marketplace.png' %}" data-locale="auto" data-zip-code="true" data-label="Buy Access to Paul's Masterclass" data-allow-remember-me="false"> </script> </form> -
How to add current logged in username to model by default
I have a Model.I would like to add logged username to a model field by default.below is my model. class Appointment(models.Model): app_age = models.IntegerField(name='Age') app_date = models.DateField(name='Date') app_time = models.TimeField(name='Time') app_email = models.EmailField(name='Email') added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) In this case i get added_by field as selection list in admin pannel.But i want to make it default logged in username.how to do it? -
Djnago filter query from many to many fields
models.py class Keyword(models.Model): name=models.CharField(max_length=500,unique=True) image = models.ImageField(upload_to='keywords/', blank=True, null=True) mood=models.ManyToManyField(Mood,blank=True) def __str__(self): return str(self.name) class ItemVariation(models.Model): restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE) items_id=models.ForeignKey(Item,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) item_code=models.CharField(max_length=500) keywords= models.ManyToManyField(Keyword) image=models.ImageField(upload_to='dishes/', blank=True, null=True) def __str__(self): return str(self.id) views.py class FoodfeedList(APIView): def get(self,request,format=None): keyword = request.GET['keywords'].split(",") mood=request.GET['mood'] location=request.GET['location'].split(",") price=request.GET['price'] user_id=request.user.id items=Item.objects.all() item_variation=ItemVariation.objects.all() search_restaurant=SearchRestaurant() search_result=search_restaurant.searchRes(location[0],location[1],keyword[0],user_id) all_results=[] json={} for i in search_result: json={} json['res_id'] = i['restaurant']['id'] # keywords_list = ItemVariation.objects.filter(keywords=keyword[0]) items=ItemVariation.objects.filter(restaurant = request.user.id) itemserializer=ItemVariationSerializer(items,many =True) json['itemserializer']=itemserializer.data all_results.append(json) # items_serilizer=ItemsSerializer(items,many=True) return Response(all_results) Output "res_id": 2, "itemserializer": [ { "id": 1, "price": 0, "item_code": "2134ffsd", "image": null, "restaurant": 1, "items_id": 1, "keywords": [1,2,3] }, I need fiter query for items where keywords are name from keyword model with query paraters 'Burger' as keyword my url is like http://127.0.0.1:8000/api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323,7767.323&price=2 if keywords match in ItemVariation model in many to many fields so it should return itemvariation -
How to fix SenderAWS.SimpleQueueService.PurgeQueueInProgressOnly error
I am using celery with SQS and I am getting error saying SenderAWS.SimpleQueueService.PurgeQueueInProgressOnly one PurgeQueue operation on prefix-main-aaaa-aaaa-bbbb-baba-a47ec24e78e8-reply-celery-pidbox is allowed every 60 seconds.cfbf38f0-95ac-52cd-aff8-6b0802566ac1 Please help me to overcome this problem. I got a link on github saying same problem but couldn't get the solution to resolve. https://github.com/celery/celery/issues/3733 -
Django social authentication with registration extra fields
I want to do a social authentication with Google and Facebook. For that I have use social-auth-app-django. When I login with using Google it will directly create an account in django user model and redirect to my URL. But I want to fill extra required details of user, after entering detail create user after user's confirmation and don't want to directly login new user and redirect to my authenticated page. Any suggestion is always appreciated. Thanks.