Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django manage.py runserver hangs after second request (intermittent)
My Django 1.11 app (using runserver) hangs after several requests. It doesn't matter whether it's accessed by Chrome, Postman, or curl. When it hangs, not even Ctrl+C can close it. The python.exe process must be killed. I tried debugging it but when Django is stuck, Python cannot be paused to get the threads/stack. -
get_list won't display my list on individual rows
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly, this example is if there was two check boxes selected: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as 88 89 and not [88,89] Using the following template my app … -
Connectindo to Twisted Server from Django
I have a twisted server and a django webserver. I want the django server to send a message to the twisted server. The django server sends the first message but the second message displays the error message "ReactorNotRestartable". My Django Code: Eu tenho um servidor twisted e um servidor web django. Quero que o servidor django envie uma mensagem para o servidor twisted. O servidor django envia a primeira mensagem mas a segunda em diante exibe a mensagem de erro "ReactorNotRestartable". Meu código Django: from twisted.spread import pb from twisted.internet import reactor class EchoClient(object): def connect(self): clientfactory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, clientfactory) d = clientfactory.getRootObject() d.addCallback(self.send_msg) def send_msg(self, result): d = result.callRemote("echo", "hello network") d.addCallback(self.get_msg) def get_msg(self, result): print "server echoed: ", result reactor.stop() def main(): EchoClient().connect() reactor.run(installSignalHandlers=0) -
How to brodcast to multiple rooms on Django channel?
i'm making a chat for 1 on 1, i made it using django channel. the model I use is as below: class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='author') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient') message = models.TextField(max_length=3000) message_html = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.message while for url django for chat with the other person : url(r'^to/(?P<username>[\w.@+-]+)/$', views.ChatView.as_view(), name='chat_page') and routing in django channels: chat_routing = [ route("websocket.connect", chat_connect, path=r'^/(?P<username>[\w.@+-]+)/'), route("websocket.receive", chat_receive, path=r'^/(?P<username>[\w.@+-]+)/$'), route("websocket.disconnect", chat_disconnect, path=r'^/(?P<username>[\w.@+-]+)/$')] channel_routing = [ include(chat_routing, path=r'^/to'),] so for example if foo wants to chat to bar then it can with http://localhost:8000/to/bar and this works well with django channels but when broadcast is updated only the room "bar", whereas room "foo" does not get the message so i want to broadcast the message to two room: http://localhost:8000/to/bar AND http://localhost:8000/to/foo this is my code to send message in consumer.py Group("to-%s" % username).send({'text': json.dumps(my_dict)}) how this can be achieved, Thank you for the help -
Django models testing with pytest
When i run the following test, import pytest from mixer.backend.django import mixer from ..models import User pytestmark = pytest.mark.django_db(transaction=False) class TestUser: def test_model(self): obj = mixer.blend(User, email='test@test.com') assert obj.pk == 1, 'Should create a user instance' i get an error ==================================== ERRORS ==================================== _______________ ERROR collecting users_app/tests/test_models.py ________________ users_app/tests/test_models.py:5: in <module> pytestmark = pytest.mark.django_db(transaction=False) E AttributeError: MarkDecorator instance has no attribute 'django_db' !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!! =========================== 1 error in 0.74 seconds ============================ my test_settings.py looks like this from .settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } EMAIL_BACKEND = 'django.core.mail.backends.locmem.Emailbackend' What is wrong with my pytest? I have tried to change to pytest.mark.django_db to the real database name(which is an sqlite database too). -
Django ModuleNotFoundError
I can't make a simple Django project work at all. I get the same error as listed in this question which I found: Python/Django =- ModuleNotFoundError: No module named 'restaurants' The only difference for me is that it says "No module named entries". This doesn't seem to have a resolution and I don't understand the comment on it either. My directory structure is like this: app |- manage.py |- app |- __init__.py |- entries | |- __init__.py | |- apps.py | |- models.py | |- views.py | |- admin.py | |- tests.py | |- migrations - __init__.py | |- urls.py |- settings.py |- __pycache__ |- wsgi.py I have added the entries app to the INSTALLED_APPS list in settings.py. But from there it just seems to run into a problem. I have been trying to work this out for ages and I just don't get it (even though it is probably easy). -
how to use supervisor when I should running a celery in django which is in a virtualenv?
yesterday, i deployed a django project with nginx,uwsgi,celery,supervisor. it seems ok. but some questions come about. generally saying, this time i deployed a django,use the local python, but if i must use the python Environment in a virtual,what should i do ? for example,i code some task(whith django-celery) which will be used by django site to contorl some timing task,and the django project based python3(the python3 envrionment is in a virtualenv). so the celery should be used by python3,which is in a virtualenv,not the local python environment. it means that if i setting the commond in supervisor "commond=python ****/manage.py celery" would error come. the uwsgi has some setting about this, i can set the path of virtualenv. but in supervisor, i had not get some setting or some way to use the virtualenv. help please. -
django hot processing performance
i run django framework in windows7 , but i note that it work hard and it consumes more processing capacity like shown in the picture below , i want to reduce it but i dont know how or which settings should be modified; -
new username is created instead of getting updated
I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created. Here is what I have tried class EmployeeForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = models.Employee fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number', 'email', 'gender', 'role', 'username', 'password', 'avatar',) def employee(request): form = EmployeeForm(request.POST or None) if request.method == "POST" and form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance user = User.objects.create_user( username=username, password=password, email=email) user.save() form.save() messages.success(request, 'Thank you') return redirect('employee-list') messages.warning(request, 'Error') context = { 'form': form } return render(request, 'dashboard/hrm/employee.html', context) Edit part def edit_employee(request, id): instance = get_object_or_404(Employee, id=id) form = EmployeeForm(request.POST or None, instance=instance) if request.method == "POST" and form.is_valid(): employee = Employee.objects.get(id=id) prev_username = employee.username username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] office_instance = OfficeSetup.objects.get(owner=request.user) form = form.save(commit=False) form.office = office_instance … -
Pug & Django: reverse URL + variable inline?
Desired output: You're currently following xx artists Assuming I'm using Pug in a Django template, how would I achieve that if I don't want to hardcode the URL (which I have named as artists in my URL), and if the artist count is also a variable? I can do this: p You're currently following #{user_artists_count} artists but how can I make the last part a link to a Django URL with the name artists? -
django templatetag working incorrectly
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. Using the following template my app prints correctly, however, all on one row. {% for app in retreivecheckbox %} {{ app }} {% endfor %} When I try … -
Zappa/AWS - Emails won't send and just timeout
Currently, I have tried both plain-old Django SMTP and a few different api-based Django libraries for my transactional email provider (Postmark). When I run my development server, everything works perfectly. Emails send via the Postmark API with no problem. When I deploy to AWS with Zappa, visit my website, and do a task that is supposed to send an email (Ex. Resetting a user's password) the page continually loads until it says Endpoint request timed out. I have tried setting the timeout of my AWS Lambda function to a longer duration in case Django decides to throw an error. Here is the error that was thrown. Just keep in mind this error only happens in production. I created a custom management command in able to retrieve this error. HTTPSConnectionPool(host='api.postmarkapp.com', port=443): Max retries exceeded with url: /email/batch (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f6cfbd5dd30>: Failed to establish a new connection: [Errno 110] Connection timed out',)): ConnectionError Traceback (most recent call last): File "/var/task/handler.py", line 509, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 376, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/var/task/django/core/management/base.py", line 330, in execute … -
Django File upload - Path to file
I am uploading a file using the model.FileField method, but I am at a loss on how to actually return the path of the uploaded file (I can't recreate the path as there can be duplicate files and the imagename changes) Views.py if form.is_valid(): newdoc = Invoices(docfile = request.FILES['docfile']) newdoc.save() Models.py class Invoices(models.Model): docfile = models.FileField(upload_to='invoices/') timestamp = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=20, default="default_user") I found some references to document.uploaded_file path etc, but they throw an error - no property document. Is it possible using the method above to get the actual path to the saved file including the possibly changed filename? -
Django (allauth) to ignore dot in the username
I would like to follow google's username convention where they take in a username as it is with dot, but consider any username with different dot placement to be identical. Since google shows the name with dot if the user signs up with it, they must store that name verbatim in the database. Should I create another field without the username, so that it would be more efficient to search for duplicates at the signup or siginin request? Or is there a query method to do this within Django? So far I am using the User model from Django as it is, so I'd prefer not having to inherit it to make a new subclass. -
Django - loop over list in template to check if a value exists, display something later
I find a list of Upvote model instances attached to a specific question, so I can check if the current user has already upvoted the question. I want to display a different button if the user has already upvoted this particular question. The problem is, the current {% if .. %} tags don't work, because a question can have many upvotes. I only need the {% if ..%} tags to simply check to see if one of the upvote.user == request.user. How do I approach this situation? I'm looking at different solutions, like creating a variable and setting that to True if a match was found (seems difficult), or writing a custom template tag. I feel like I'm over-complicating this issue though. HTML Template {% for question in questions %} {% for upvote in question.upvote_set.all %} {% if upvote.user == request.user %} # Display the upvote button {% else %} # Display a different button {% endif %} {% endfor %} models.py class Question(models.Model): # ... code user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='question', null=True, blank=True) class Upvote(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) -
URLCache not working when using p2_OAuth2 Data Loader
I'm trying to cache various REST calls in my iOS app and can't seem to find an approach that works. Our objective is to leverage caching to solve for offline situations and this is just a start to try to get caching working at a basic level. Some of the details here: REST responses include this header (using Django REST Framework): Cache-Control: private, max-age=3600 AppDelgate Code: let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as String let dir = cacheDirectory.appendingFormat("/urlCache/") let memoryCapacity = 10 * 1024 * 1024 let diskCapacity = 50 * 1024 * 1024 let cache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: dir) URLCache.shared = cache Although I don't believe I really need to do this to get some level of caching working? Initialization of OAuth2 classes: init(context: AnyObject, accessToken: String) { oauth2.authConfig.authorizeContext = context oauth2.authConfig.authorizeEmbedded = true oauth2.authConfig.authorizeEmbeddedAutoDismiss = true oauth2.logger = OAuth2DebugLogger(.debug) oauth2.accessToken = accessToken loader = OAuth2DataLoader(oauth2: oauth2) striveaiRoot = URL(string: Bundle.main.infoDictionary!["StriveAIRoot"] as! String)! self.accessToken = accessToken } Example code calling the REST API via DataLoader: func getFeed(callback: @escaping ((OAuth2Response) -> Void)) { let uri = striveaiRoot.appendingPathComponent("feed") let size = URLCache.shared.currentMemoryUsage NSLog("using %d of cache", size) let req = oauth2.request(forURL: uri, cachePolicy: .useProtocolCachePolicy) self.loader?.perform(request: req, callback: callback) … -
Django - how to create a group of reusable apps
I have a group of related apps i would like to keep in a common directory/package. As for now everything worked fine, but the problem is when I want to define AUTH_USER_MODEL as it's not working with a string like package.app.model. I've found some solutions like importing the model in __init__.py but those feels somewhat hacky - i don't have much experience with python or django, but it looks like maybe i'm approaching the problem wrong way? What i would like to acheive is to create a reusable group of apps i could easily drop into few of my projects and update from time to time in some sensible way. Of course i could create just one app, but i don't like that idea as there are going to be some different domains (like accounts, cms, e-commerce, etc) which preferably should be in separate apps. Those projects are going to have some other specific, project-related apps also (that's why i would like to group the core, common base in some form of a package if possible). Also, this won't be any publicly distributed thing - just reusable between few specific projects im doing. What i'm searching for is something simple … -
django rest framework same route, different
i'm using django rest framework to build an api, here is my problem url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'), url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'), class ProfileRetrieveView(RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileUpdateView(UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = (IsAuthenticated, ) When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins. -
Django - Check Other Objects Prior to Save
I want to override the built-in django .save() method to perform a check against all other objects in the database. For example: class User(models.Model): name = models.CharField(max_length=120) class Admin(models.Model): name = models.CharField(max_length=120) class SecurityGroup(models.Model): name = models.CharField(max_length=120) users = models.ManytoManyField(User) admins = models.ManytoManyField(Admin) def save(self, *args, **kwargs): # check admins don't exist in any other SecurityGroup prior to save super(Person, self).save(*args, **kwargs) # Call the "real" save() method. The documentation example is pretty simple, and doesn't describe this type of pre-save check. Is it possible to achieve this save functionality internal to the SecurityGroup Model, or do I need to create a form and use SecurityGroup.save(commit=False) for this type of pre-save check? Thanks for the help. -
Queryset in Django if empty field returns all elements
I want to do a filter in Django that uses form method. If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements. How can I do that? I am new in Django if request.GET.get('Var'): Var = request.GET.get('Var') else: Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW models.objects.filter(Var=Var) -
Saving data from Backbone to Django with two parameters
I have to save data with two parameters into this Django model class Employee(Base): language = models.ForeignKey(Language, on_delete=models.CASCADE) employee_img = models.ForeignKey(EmployeePicture, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True, verbose_name='Name') position = models.CharField(max_length=100, null=True, blank=True, verbose_name='Position') description = models.TextField(null=True, blank=True, verbose_name='Description') My url is like: http://website.com/control/employee/18/en/, where the number is the id of employee_img and the en is a field in language. I set my Backbone view like this: module.exports = Backbone.View.extend({ el: '.EmployeeForm', template: template, events: { 'blur input': 'updateValue', 'click .Button--add': 'savedata' }, initialize: function() { this.newModel = new EmployeeModel(app.data.employeeDataInWindowObject); }, updateValue: function(event) { console.log('value updated'); var value = $(event.target).val(); this.newModel.set($(event.target).attr('name'), value); }, savedata: function(event) { event.preventDefault(); this.newModel.save(null, { headers: { employee_img_id: app.data.employeeDataInWindowObject.employeeImg, language_id: app.data.employeeDataInWindowObject.language }, success: function() { console.log('Sucess saving data'); } }); } }); As you can see I retrieve data from an object window.app.data.employeeDataInWindowObject where I saved it previously. My backbone model looks like: module.exports = Backbone.Model.extend({ urlRoot: '/control/api/employee/' }); My Django router: url(r'^employee/$', ApiEmployeeView.as_view()), url(r'^employee/(?P<obj_id>\d+)/(?P<lang>\w+)/$', ApiEmployeeView.as_view()) Am I passing parameters correctly? Thanks! -
templatetag not rendering in template/html
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. I have an array defined as the following checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) When I print my array the console displays it correctly: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() # Calls .getlist() on a querydict # Use: querydict | get_list {{ querydict|get_list:"itemToGet" }} @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) @register.filter def get_at_index(list, index): return list[index] Now i'm trying to get my template to display what's in my console but as individual rows/indexes. I'm told get_list will do that for me. I've also tried get_at_index. Using the following template my app prints correctly, just all on one row because it's an array. {% for app in retreivecheckbox %} {{ app }} {% endfor %} When I try several variations of the following my template displays nothing. Why doesn't my get_list break my array into indexed lines? {% load app_filters %} {% for app in retreivecheckbox|get_list:report_id %} … -
make some django/wagtail files private
Is there a way to make some files unaccessible via direct url? For example, an image appears on a page but the image location doesn't work on it's own. -
Django - AttributeError
I created my custom User model. While doing migrations, I get an AtrributeError from django.db import models from time import timezone from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.mail import send_mail from django.utils.http import urlquote from django.utils.translation import ugettext_lazy as _ class CustomUsermanager(BaseUserManager): def _create_user(self, is_anonymous, first_name, last_name, email, username, password, home_address, user_type, image_path): now = timezone.now() if not email: raise ValueError('The gives emial must be set') email = self.normalize_email(email) user = self.model( is_anonymous=is_anonymous, first_name=first_name, last_name=last_name, email=email, username=username, home_address=home_address, user_type=user_type, image_path=image_path, created_time=now, last_login=now ) user.set_password(password) user.save(using=self._db) return user def create_a_admin(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, password, home_address, 0, image_path) def create_a_nonanonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, username, 1, password, home_address, 1, image_path) def create_an_anonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, 1, password, home_address, 1, image_path) def create_a_nonanonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, username, 2, password, home_address, 2, image_path) def create_an_anonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, 2, password, home_address, 2, image_path) def create_a_prof(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, … -
Django Signal Triggered But Not Saving
Exactly like the title says. The post_save receiver is being triggered, and permissions are being changed in these methods, but they remain unchanged on the admin page. Here's the model I'm using, stripped to just the part in question. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from guardian.shortcuts import assign_perm, remove_perm class Role(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_admin = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_role(sender, instance, created, **kwargs): if created: Role.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_role(sender, instance, **kwargs): if instance.role.is_admin: assign_perm('auth.add_user', instance) else: remove_perm('auth.add_user', instance) instance.role.save() The if..else in the save_user_role method works in the django shell, but not in my signal. I (don't think) I can save instance again, because that'll cause an infinite loop of post saves. Saving to my Role model didn't work, as permissions have to be save to Users and Groups. I'm guessing this is a misunderstanding of how I'm supposed to use signals, or saving models. Why are my permissions not being saved? What can I do in future to avoid this?