Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mezzanine popup not closing
I have 3 models Company,Contacts,CompanyAssociation. Contacts has a m2m realtion with CompanyAsso. And CompanyAss. has a foriegn key relation with Company.Now In the admin panel when I try to add new contact and i click + on m2m field it opens a popup and shows CompanyAss. model when i click on + of froeign key relation it takes me to Company model.I add the data and click save then the popup does not close.The data does get save. What i want is when the company is added it should take me Back to CompanyAssoc model.. -
Struggling to display a modelForm in admin panel
Im trying add custom ModelForm to Django admin panel, however I am getting this error. django.core.exceptions.FieldError: Unknown field(s) (tron, rchain, etc..) I want to have a form in admin-panel when you click add to 'Currencies' there will be a choice of currencies and you can select one. I have been tweaking it for a while and can not come up with a solution. Basically, i believe I need to create a model instances 'on the go' whenever I select a currency in the admin panel.But how do I achieve it ? My code below #modelForm.py class Currencies_Form(ModelForm): #tuplez = [(i,) for i in Coins.arr] cryptoId = forms.ChoiceField(choices=Coins.arr, initial=' ', widget=forms.Select()) class Meta: model = Currencies fields = Coins.arr models.py class Currencies(models.Model): cryptoId = models.CharField(max_length=50) cryptoPrice = models.CharField(max_length=50) My file with an api call and data - CoinAPI.py class Coins: def __init__(self): self.arr = [] self.hashTable = {} params = 100 data = requests.get('https://api.coinmarketcap.com/v1/ticker/?limit={}'.format(params)).json() for objects in data: for k in objects.keys(): if k == 'id': self.arr += objects[k].split() self.hashTable.update({objects[k]:objects['price_usd']}) Coins = Coins() and my admin.py class whatever(admin.ModelAdmin): form = Currencies_Form admin.site.register(Currencies,whatever) Please don't mind the naming, clearly not PEP-8 standard, it's just for my local testing yet. -
Config RegexField's just accept hyphen (-) and numbers only - Django Rest Framework
Hope your guys help me Config RegexField's just accept hyphen (-) and numbers only in Django Rest Framework Now I config: username = RegexField(regex=r'^[a-zA-Z0-9]+$', required=True, max_length=50) It's not work! Thanks in advance! -
Django_permissions, how to template my menu item based on the permissions?
I want to display menu item based on my given permissions, for example users who are not a Project manager thex dont see item project in the menu and so on.. I have a separated Client dashboard from admin dashboard which is not so good and pro. Here my code: models.py class Customer(models.Model): birthday= models.DateField(blank=True, null=True) address= models.CharField(max_length=50, blank=True, null=True) auth_user = models.ForeignKey(to=User) class Meta: db_table = 'Customer' permissions = (("view_user", "Can_view_user"),) views.py class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = 'can_view_user' template_name = "user_list.html" model = User def dispatch(self, request, *args, **kwargs): if check_permission_BM_or_AM(request): if request.user.is_authenticated(): return super(UsersListView, self).dispatch(request, *args, **kwargs) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) permission.py def check_permission_BM_or_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollen = Rollen.objects.get(id=1) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollen.rolle or str(ma.rolle) == rollens.rolle: return True def check_permission_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollens.rolle: return True menuitem.html <ul> <li class="dropdown-submenu "> {% if can_view_user%} <a tabindex="-1" href="/user/list/"><span class="fa fa-fw fa-book "></span> Users</a> {% endif %} </li> view.py (my_app) @login_required(login_url="/accounts/login/") def index(request): if request.user.is_superuser: return HttpResponseRedirect('/administrator/') elif request.user.is_active and request.user.is_authenticated: return HttpResponseRedirect('/user/') views.py(user) class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = … -
Define Django variable in statement
I want to define a variable in my Django template but if I set the variable within the statement I can't call it again. Is there any way to call the variable from the other part of my template? Thank you in advance! My attemt: {% if a > 1 %} {% with "string_1" as var %} {% endwith %} {% elif a < 1%} {% with "string_2" as var %} {% endwith %} {% else %} {% with "string_3" as var %} {% endwith %} {% endif %} {% if var='string_1' %} #here i want to call the variable again <p>This is string_1</p> {%else%} <p>This is not string_1</p> -
Personally identifying data in Django Request
I was working on a Django project which had no user data logging. Then I added IP Address and User Agent logging for posts. What other personally identifying do I get other than IP Address and User Agent in a Django request in the view. I don't want to log too much. The above two should be enough. But I just want to know if there is any other good information to log about the user. -
Delete record without accessing it directly
I am creating a data visualisation site in django and using the rest api for my data. Is there any way of deleting a record without accessing its url directly, as in this case it is impossible. Something like def employee_delete(request): instance = Employee.objects.get(social_security=request.POST) instance.delete() return render(request, "dashboard.html") This only works if you have access to the console as I learned, so I tried to access the data from a form like so def employee_delete(request): if request.method == "POST": form = delete_EmployeeForm(request.POST, request.FILES) if form.is_valid(): instance = Employee.objects.get(social_security=request.POST) instance.delete() return render(request, "dashboard.html") else: form = delete_EmployeeForm() return render(request, "deleteemployee.html",{'form': form}) Would this work if I was able to be more specific about which piece of data I was accessing from the form? I got a typeError trying to use request.Post in that manner. That form contained a single field in 'social_security' from the Employee model. Thanks -
How to implement method in Django REST?
Have the next Django REST question. I have the view. class MessageViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer queryset = Message.objects.filter(isread = False) def mark_read(): queryset = Message.objects.update(isread=True) return Response({'read':queryset}) And router in urls.py router = SimpleRouter() router.register(r'api/get_messages', MessageViewSet) urlpatterns = [ url(r'^$', MainView.as_view(), name='main'), url(r'^', include(router.urls)) ] Now i have 'get_messages' page which shows all list. How can i implement a method which would change 'isread' value of model instanse from False to True, when I visit a 'mark_read' page? As you can see, i tried to write method in the class. But when i'm trying to call it in urls in this way: router.register(r'api/mark_read', MessageViewSet.mark_read), Here comes an error. assert queryset is not None, 'base_name argument not specified, and could ' \ AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. Maybe i shouldnt use router, and rewrite view and urls in other way. If u know how to solve this problem, please answer. Thanks. -
django haystack (solr backend) index only data after specific date
I am trying to index only data after specific created date, not all records of the model with django haystack. Originally I thought that index_queryset() method is used when executing index_update and/or rebuild_index. So I tried to add created__lte=(current_date) and I was wrong it always get all records of the model to index them -
Djangocms with Vue.js frontend
Recently came across these repositories on Github: https://github.com/dreipol/djangocms-spa https://github.com/dreipol/djangocms-spa-vue-js If anyone has used these before please help me with the initial setup. -
TypeError: TypeError("object of type 'NoneType' has no len()",) while convert pdf to image
I am building API which converts uploaded pdf to image based on Django REST framework, on MacOS env. Of course, installed imagemagick and ghostscript well. Here is my code snippet. try: with Image(filename=pdffile, resolution=300) as img: for i, page in enumerate(img.sequence): filename = '{}-{}.jpg'.format(imagefilename, i + 1) file ='{}/{}'.format(tmp_dir, filename) Image(page).save(filename=file) filelist.append(filename) except WandException as e: print e except TypeError as e: print e But I am getting this error: Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in > ignored At the line: with Image(filename=pdffile, resolution=300) as img: I googled this problem, but couldn't find out correct solution. Most of them say like this: Re-install imagemagick. Check system environment path variable. These solutions don't work for me. Have you ever faced issues like this? Have any other solutions? -
Rollup in Django ORM
Is it possible to use ROLLUP aggregation in Django ORM without writing raw SQL? -
Django-cms no reverse match using apphook from admin
i hope you can help me. I'm using django 1.11 and django-cms. I created an apphook to manage urls from a certain page. I already created the page (with all translations) and associated it with my application so everything works fine. My problem occurs when, from admin, i'm inside the change page related to an instance of a model. I see the button 'view on site' that uses an url created this way: /admin/r/content_type_id/object_id/ django.contrib.contenttypes.views.shortcut admin:view_on_site Clicking on it i get the error Reverse for 'myapp_mymodel_detail' not found Do you know the correct way to make it works? -
TinyMCE editor not showing up in Django-Zinnia custom admin
I'm trying to use django-blog-zinnia 0.19 with tinymce and admin. In order to allow non-staff users to use Django's admin interface, I registered an extra BlogAdminSite class and added the necessary urls to point to the custom admin pages. This is what should be used to edit blog entries. When using the regular admin interface using the url http://localhost:8000/en/admin/zinnia/entry/1/change/ tinymce is used as desired. However, when calling the custom blog admin interface using the url http://localhost:8000/en/blog/admin/zinnia/entry/1/change/ tinymce is not shown, just the regular textarea widget. Looking at the HTML source, I find tinymce's files missing in the latter case: I installed django-tinymce 2.2.0 and zinnia-wysiwyg-tinymce 1.4 packages. In settings.py's INSTALLED_APPS sections the relevant apps are added in this order: 'blog', # BlogAdminSite app 'tinymce', 'zinnia', 'zinnia_tinymce', 'django.contrib.admin', Thanks for your help. -
download django data model as csv
how can i turn data collected from Django site, and download it as a .csv file. I want it to be so that there is a button in django admin that downloads all the data as a .csv file this is my model: from django.db import models class Auto(models.Model): YNC = ( ('N', 'No'), ('Y', 'Yes'), ) NYC = ( ('N', 'No'), ('Y', 'Yes'), ) NNY = ( ('N', 'No'), ('Y', 'Yes'), ) nw = ( (1, 'Really Bad'), (1, 'Bad'), (3, 'Average'), (4, 'Good'), (5, 'Really Good'), ) Team = models.CharField() Scout = models.CharField() StartWithCubeLoaded = models.CharField(max_length = 1, choices = YNC, default = 'N') CrossAutoLine = models.CharField(max_length = 1, choices = YNC, default = 'N') RobotCrossCenterLine = models.CharField(max_length = 1, choices = YNC, default = 'N') PlaceCubeInWrongScale = models.CharField(max_length = 1, choices = YNC, default = 'N') RobotHitOtherAllianceRobotInNullZone = models.CharField(max_length = 1, choices = YNC, default = 'N') MisPlaceCube = models.CharField(max_length = 1, choices = YNC, default = 'N') DroppedCubes = models.IntegerField(default = 0) DoubleStackScale = models.CharField(max_length = 1, choices = NYC, default = 'N') Foul = models.CharField(max_length = 1, choices = NYC, default = 'N') KnockedOffCubes = models.IntegerField(default = 0) MissedCubes = models.IntegerField(default = 0) Climbed = … -
Property allowing attribute access
To make part of the django-tables2 API usable in templates, I want to define a property on a class that translates the attribute name to an argument to another method. The current implementation looks (vaguely) like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] This makes it impossible to access a specific cell from a django template, because django templates do not allow passing arguments to functions. I want to support something like row.cell.first_name, which would be easy if the internal structure contained a dict _cells. In reality, the implementation is a bit more complex (getting the value involves calling a function). Computing a dict for all possible cells is not desirable either because it might involve doing unnecessary work. My naive solution looks like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] @property def cell(self): class CellReader(object): def __init__(self, row): self.row = row def __getattr__(self, name): return self.row.get_cell(name) return CellReader(self) Which works and doesn't use too much code, but it feels a bit verbose. Is there something in the standard library I did not think of to implement this functionality in a more concise way? -
Extending/overriding Django TestCase class
My application has three levels of access (i.e. User, Manager, Admin). In my unit tests I have something like this: from django.test import TestCase class DocumentViewTest(TestCase): def setUp(self): # Create 3 users def test_view_url_exists_at_desired_location(self): self.client.login(username='manager', password='xx') resp = self.client.get(reverse('view_upload')) self.assertEqual(str(resp.context['user']), 'manager') Testing all three levels could be defined by the same routine: login user post/get to some url create assertions to check the post/get response I wanted to encapsulate all the steps in some wrapper class or extend the TestCase, so that redundancy is avoided. I was thinking about something like this: from django.test import TestCase class DocumentViewTest(TestCase): def setUp(self): # Create 3 users def test_view_url_exists_at_desired_location(self): self.client.login(username=['manager','admin','simple_user'], password=['xx','x','xxx']) resp_manager, resp_admin, resp_simple_user = self.client.get(reverse('view_upload')) self.assertEqual(str(resp_manager.context['user']), 'manager') self.assertEqual(str(resp_admin.context['user']), 'admin') self.assertEqual(str(resp.resp_simple_user['user']), 'simple_user') Does anyone have suggestions how I could override get/post/login methods? Would creating a wrapper class around TestCase be easier? Any other suggestions? Thanks! -
Django, ImportError: cannot import name Celery
Why is this happening? My celery.py: import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my init.py # import celery from .celery import app as celery_app I even tried renaming celery.py to something else and the error still persisted. Could it be because of my python version? -
How to add a foreign key to an existing model of a newly created model in DJango?
class Person(models.Model): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) DOB = models.DateField() username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __str__(self): return self.first_name + self.last_name class Entry(models.Model): writer = models.ForeignKey(Person, on_delete=models.CASCADE,default="What should I write here?") title = models.CharField(max_length=100, default='Title') moment = models.DateTimeField() text = models.TextField() def __str__(self): return self.title + ' | ' + str(self.moment.strftime("%I:%M %p - %A, %B %d %Y")) Above are my two models, Entry is an old model, Person is a new one. Meaning, I have many instances of Entry but zero of Person. But I want to link Entry with Person. So what I did is, I removed the writer field from entry. Updated the database, made an Instance of Person. So, currently I have 1 instance of Person and n instances of Entry. How can I link them using a foreign key? I don't know what to put in default parameter. -
Django Mathfilter do not working with comparison operator
I have a statement where I use mathfilter in Django template and it do not want to turn to false despite the mathfilter is working. Which is the correct syntax for this? Thank you in advance! {% load mathfilters %} {% if 9|sub:10 > 2 %} # (9-10) > 2 -
django invalid field name(s) for model content type
i looked all around internet i can't find a solution for this error in django this script is worked on by one of the developers before me i'm trying to run ./manage.py migrate but it keeps getting this output django.core.exceptions.FieldError: Invalid field name(s) for model ContentType: 'name'. and this is the whole traceback this is the content of manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smsg.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) -
How to handle url collisions in django/wagtail
how to handle two different views witch match for the same url? (Both views need a database call to determine if the called element is available. Changing the url structure is not an option.) url(r'^', include(wagtail_urls)), This wagtail url is matching all url's and is raising an 404 if the according page/slug is not in the database. But, I also have my own view witch behaves similar. How can I tell django to continue with the next url instead of raising a 404? (I could place my own view before the wagtail view and modify it, but I don't know how to return to the next url?) -
How to keep different files(/versions of files) on local branches and not show them in git status?
Me: I work (develop) on a Django project in a team. And we use postgresql as the database. I had untracked the migrations folders (and files) for obvious reasons. Problem: Sometimes I work on multiple branches and when there is a difference in the models which extend django.db.models.Model the makemigrations fails. My approach on the Problem: I decided to have a different database on my machine for each branch. Found out that this could be done using pygit2 (keep the name of database same as that of the branch). Problem with my approach: The migrations are same in every branch as I have them untracked. I dont want to track migrations because pushing them would disturb the production server migrations. Requirement: Whenever i switch branch, the migrations should change, but at the same time they should remain not pop up during 'git status'. Thank you in advance -
Validate Sign Up User data in serializers - Django Rest Framework
I have an issue with Validate Sign Up User data in serializers - Django Rest Framework. Hope your guys help me! My request: I want to create sign up form with user enter Duplicate email, it'll raise serializer object which duplicate. My serializers: class UserDuplicateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'full_name', 'first_name', 'last_name', ] class UserSignUpSerializer(ModelSerializer): username = CharField(required=True, allow_blank=False) class Meta: model = User fields = [ 'username', 'email', 'password' ] extra_kwargs = {"password": {"write_only": True}} # Validate duplicate username def validate_username(self, value): data = self.get_initial() username = data.get("username") username_qs = User.objects.filter(username=username) if username_qs.exists(): duplicate_obj = User.objects.get(username=username) serializer = UserDuplicateSerializer(duplicate_obj) print(serializer.data) raise ValidationError("This username has been registered!" + serializer.data) else: pass return value def create(self, validated_data): username = validated_data['username'] ... user_obj.save() return validated_data Error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\generics.py" … -
Rsync inside container
I have a command inside my django application to copy file from server to local using rsync. It was working fine normally. But when i containerized the code, the file is not getting copied. How am i supposed to copy file using rsync inside container? COMMAND="rsync -avzhe ssh @:/path/test.txt /destination/path/" ssh = subprocess.Popen(COMMAND, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print ssh result = ssh.stdout.readlines() print result result gives [] after containerizing, while normally i had [received xx bytes, sent xx bytes etc]