Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a model class have a specific relation with another set of model classes django?
This is my models: class company(models.Model): User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) Name = models.CharField(max_length=50,blank=False) class group(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_Name = models.CharField(max_length=32,unique=True,error_messages={'unique':"This Group Name has already been registered"}) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group') class ledger1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys') Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) So these are my models I have created for my accounting application... The company model is connected to group and ledger through foreign key... I want to provide different group and ledgers for different companies which the user have Created... As such when the User will go in the Company details page he can access those groups and ledgers which he have created for that company name which is displayed in the company detail page in my django template... Its similar to the user specific relation that when some user is logged in it will show information for that user ... The flow of the application will be like this: Firstly the user will login -> Then he will select a company which he have created -> Then he will be redirected to the company details page where he can access only those group and ledger he have created for the selected company... Can anyone help me … -
many to many relationship in django rest frame work
I had an issue of understanding the django rest framework doc about many to many relationship and upload files like image, here my code. models.py class Team(models.Model): admin = models.ForeignKey(User, null=True, blank=True, related_name='admin', on_delete=models.CASCADE) name = models.CharField(blank=True, max_length=100) longitude = models.FloatField(blank=True, null=True, max_length=20) latitude = models.FloatField(blank=True, null=True, max_length=20) score = models.IntegerField(blank=True, null=True, default=0) country = models.ForeignKey(Country, blank=True, on_delete=models.DO_NOTHING) city = models.ForeignKey(City, blank=True, on_delete=models.DO_NOTHING) players = models.ManyToManyField(User, blank=True, related_name='players') created = models.DateField(auto_now_add=True) class TeamImage(models.Model): Team = models.ForeignKey(to=Team, null=True, blank=True, on_delete=models.CASCADE) img = models.ImageField(upload_to='team_img/', null=True, blank=True) serializer.py class TeamCreateSerializer(ModelSerializer): # admin = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), # many=False, default=serializers.CurrentUserDefault()) players = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True) country = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all()) city = serializers.PrimaryKeyRelatedField(queryset=City.objects.all()) score = serializers.IntegerField(read_only=True) images = TaskImageSerializer(source='teamimage_set', many=True, read_only=False) # images = TaskImageSerializer(many=True, read_only=True) class Meta: model = Team fields = [ # 'admin', 'name', 'longitude', 'latitude', 'score', 'country', 'city', 'players', 'created', 'images', ] def create(self, validated_data): images_data = self.context.get('view').request.FILES team = Team.objects.create(name=validated_data.get('name', 'no-title'), latitude=validated_data.get('latitude'), longitude=validated_data.get('longitude'), # score=validated_data.get('score'), country=validated_data.get('country'), city=validated_data.get('city'), # players=validated_data.get('players'), created=validated_data.get('created'), # images=validated_data.get('images'), ) for image_data in images_data.values(): TeamImage.objects.create(task=team, image=image_data) return team view.py class TeamAPIView(ListCreateAPIView): queryset = Team.objects.all() serializer_class = TeamCreateSerializer permission_classes = [AllowAny, AllowAnonymous] pagination_class = ProfileLimitPagination def perform_create(self, serializer): serializer.save(admin=self.request.user) what im trying to do is set the exist players records to team … -
Update User (first_name,avatar) REST framework
I need to update my user in REST framework views.py def post(self,request): user=User.objects.get(id=request.user.id) user_serializer=UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() return Response(user_serializer.data, status=status.HTTP_201_CREATED) else: return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'avatar'] models.py class User(AbstractUser): fb_userid = models.CharField(max_length=256) avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) response: DETAIL: Key (username)=() already exists. -
how to find out how many times an specific word used in a entire web site, using python?
I want to implement a full investigation to find out which sub-field of deep learning has better job positions in the future. So i need a tool to count how many times an specific word(deep learning, computer vision, CNN,RNN,...) used in a entire web site such as indeed.com I'm now working on convolutional neural networks, but i don't have clear perception of future job positions frequency in computer vision, speech recognition and other sub-fields of deep learning. I don't know does it's better to switch to data science with my machine learning background? -
Django: requirements.txt
So far I know requirements.txt like this: Django==2.0. Now I saw this style of writing Django>=1.8,<2.1.99 Can you explain to me what it means? -
Unable to create table in the database using Django oracle12c
I am working on a college project for which I am supposed to use oracle database as the backend and I have chosen to work with django as the programming language. I have successfully connected django with oracle 12c and also have cx_Oracle installed. But when i try to run the command py manage.py migrate the following errors show up. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\Hp\Desktop\onlinepharma> py manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, testing Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site- packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\oracle\base.py", line 513, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00955: name is already used by an existing object The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\Hp\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = … -
DJStripe (Django): looking for a simple example of customer creation and subscription
I am looking for a simple DjStrip example where we can create a simple customer and charge it to a subscription. -
Using Chained Foreign Key with read only field in django admin
I wanted to know how to filter the inputs of a ForeignKey based on a readonly field in django admin, if thats even possible at all (using django-smart-selects). When I create an object I have field B chained to A, both editable, and smart-selects works wonders. When I change A, B options change accordingly. When I'm editing this object I make field A read only, and now field B always show blank. If I make A editable, B shows correct value and starts working again. class SomeModel(models.Model): A = models.ForeignKey(AnotherModel, on_delete=models.SET_NULL, null=True, blank=True) B = ChainedForeignKey(YetAnotherModel, chained_field='A', chained_model_field='A', on_delete=models.SET_NULL, null=True, blank=True) class SomeModel(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj: # editing an existing object readonly_fields = ('A',) return self.readonly_fields + readonly_fields -
Django how to update thousands of entries
I'm trying to optimize my application, basically what it's doing right now is filter/format/compute a JSON file and insert the data into my database.So I managed to optimize the create part by using bulk_create. But in most of the case I've to update instead of create, and I didn't find anything about a way to update many entries in same time instead of doing it one by one. I tried to use transaction.atomic but not sure I use it properly. with transaction.atomic(): # Iterate trough all auctions from Json API for a in auctionData.get('auctions') : # Check if item is in Item table if a.get('item') in itemsIdx : # Format data for database d = {k: v for k, v in a.items() if k in auctionFields} d['lastModified'] = apiLastModified auc = d.pop('auc', None) # if auction already in database update otherwhise create if auc in latestAuctionsIdx: currentEntry = Auction.objects.filter(auc=auc).update(**d) else : currentEntry = Auction(auc=auc, **d) currentEntry.save() I still feel it's taking too much time, about 15sec for 3000 updates. If you know anything to make it quicker, please let me know. Cheers -
'NoneType' object has no attribute 'is_relation' error on Django Migrations
I am trying to remove some fields from existing model of Django on Heroku, So I run make migrations, then migrate commands, it seemed like succesfully did the migrations. After that I found out one field was missing, so I created next migration file myself, put dependency to previous auto generated migration file. When I run it, I have an error like this: ~ $ python manage.py migrate Operations to perform: Apply all migrations: API, admin, auth, authtoken, contenttypes, sessions Running migrations: Applying API.0007_timezoneremoval...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 119, in apply operation.state_forwards(self.app_label, project_state) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 150, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' Where this error may be caused … -
messages.error() not formatting correctly, but .success() does
Having an issue with messages.error() not showing up on the html template properly. I have a Participant models where Users register their participants in a research project. When they complete the registration form, the custom form_valid() method within the CreateView sends off to another function which assess the new patient's eligibility - if eligible the form is saved to the model and a messages.success() is shown. If they are not eligible, the form is not saved and a messages.error() should be shown. Currently, all of the eligibility check functionality works perfectly and if eligible the success message is shown. However, when not eligible the error message does not show properly. The text is shown on the redirect page, however it is not formatted as an error message should be in the red box. views.py class ParticipantRegisterView(LoginRequiredMixin, CreateView): model = Participant form_class = ParticipantRegisterForm template_name = 'participants/register.html' success_url = reverse_lazy('accounts:dashboard') def participant_eligible(self, temp): if not temp.is_eligible: return False else: return True def form_valid(self, form): form.instance.provider = self.request.user temp = form.save(commit=False) if self.participant_eligible(temp): messages.success(self.request, 'Participant registered') return super().form_valid(form) else: messages.error(self.request, 'Participant ineligible') return redirect(reverse_lazy('accounts:dashboard')) relevant portion of base.html that the template for 'accounts:dashboard' extends <html lang="en" dir="ltr"> ... <main role="main" class="container"> <div … -
How do I toggle a div based on whether a bool is true or not?
I want to hide a div if a bool is false and show it if true. This is what I have so far. Html <div class="hidden-div" {{ form.field }} </div> Jquery $('#id_field').on('change',function(){ if $('#id_field').val() == "true"; { $('.hidden-div').show(); } else { $('.hidden-div').hide(); }}); I think the problem is the value of #id_field. Not sure what I should check for. I've already checked true, True, "true", "True", 1, "Yes", " Yes" (the "Yes" is the string value of choices variable set in choices.py. I've also tried checking #id_field_0. -
Extract all docstrings (__doc__) from my Django files
I have a project in Django and I write docstrings in my modules, classes and functions. But I need a way to extract all __doc__ from there automatically. Like "python manage.py collectstatic" but for .__doc__ instances for all .py codes. Something like that? Some ideas? -
How to integrate django with kibana
I am learning Django 2 and need integrate django with kibana, and configurate setting for send logs to kibana. If anyone knows integrations, please share with me. -
how to get post.user.username using self.kwargs.get in Python Django
I have the below working code in my accounts DetailView so it shows the rating for each user in the users profile page profile view context['ratings_list'] = Ratings.objects.filter(rating_for__username__iexact= self.kwargs.get('username')) I want to use the same code in my posts list view where the username will be post.user.username. Example: Below is how I want the post list page looks it has multiple posts Post 1 by Samir Tendulkar. Samir Tendulkar's rating: 8/10 Post 2 by John Doe. John Doe's rating: 7/10 post view I know this the wrong code but how can i achieve this. I need the post users username context['ratings_list'] = Rating.objects.filter(rating_for__username__iexact= self.kwargs.get('post.user.username')) rating model: class Rating(models.Model): rating_from = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='rating_from') rating_for = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='rating_for') post model class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() In my profile template (Which is actually the User's Profile Template) {% if rating_list %} Rating: {% for rating in rating_list|slice:":1" %} {{ rating.average_rating }} / 10 {% endfor %} {% else %} User has no rating yet {% endif %} I am not sure how to get post ListView template -
Facebook Graph API and python facebook-sdk upload multiple files
I'm trying to post to the Page feed with multiple images. I'm following Doc's Facebook Graph API and Doc's facebook-sdk for python. Only the message is published, without the image. token = "my_token" graph = facebook.GraphAPI(access_token=token, version="3.0") photo_id = graph.put_photo(image=open('favicon.png', 'rb'), published=False) print('PHOTO ID ', photo_id.get('id', '')) post = graph.put_object(parent_object="page_id", connection_name="feed", message="Message with images upload!", attachments=[{'media_fbid': photo_id.get('id', '')}]) print('POST ID', post.get('id', '')) Image and post IDs are returned without errors. However, the image is not published along with the message. I'm using attachments parameter, maybe it's another. Any idea? -
django icontains to search postgres database
I currently have a Django application and postgres database. I want to have a search bar that allows users to enter in a value and it will search some of the fields of the model to search for matching values. I want this to work even for values of "". I currently have: MyModel.objects.filter(myfield__icontains=search_query).order_by(...) How would I make this so that it can search multiple fields of the model at the same time. What is the most efficient way to do so? Is "icontains" okay for this? Any help would be greatly appreciated! -
Couldn't find a tree builder with the features you requested
Could you please suggest a fix for the problem? Although 'lxml' and 'html5lib' are installed, and designating the parser, bs4 returns "FeatureNotFound". I've already referred to bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml All the package installation are basically done through root account. The code and environment is as followed. ・Sakura VPS ・CentOS7 ・python3 ・django def Scraper(x): #setup query = x query = query.decode('utf-8') searchUrl = 'https://www.google.co.jp/search?q=' + query urls = [] html = requests.get(searchUrl).text bs = BeautifulSoup(html, 'html5lib') -
Query Wagtail Form Fields into Homepage
I was wondering if it was possible to query the form fields from a abstract wagtail form into page model. I would like to put a wagtail form on my homepage(page) model, but don't really understand how you would accomplish this, if it is even possible. Any feedback is appreciated home_page.html ... <form action="{% pageurl page %}" method="POST"> {% csrf_token %} <div class="row"> <div class="col-md-12 col-sm-12"> {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} <h3>Contact Form</h3><br> </div> {% for field in form.visible_fields %} <div class="col-md-6 col-sm-12"> <div class="form-group"> {% render_field field class+="form-control" %} </div> </div> {% endfor %} </div> <div class="pull-center"> <button type="submit" class="btn btn-contact mt-3">Submit</button> </div> </form> models.py imports removed class HomePage(Page): firstheader = RichTextField(blank=True) firstbody = RichTextField(blank=True) registerbuttonurl = models.CharField(blank=True, max_length=250) secondheader = RichTextField(blank=True) secondbody = RichTextField(blank=True) registerlink = RichTextField(blank=True) def category_list(self): return FormPage.objects.all() content_panels = Page.content_panels + [ FieldPanel('firstheader', classname="full"), FieldPanel('firstbody', classname="full"), FieldPanel('registerbuttonurl'), FieldPanel('secondheader', classname="full"), FieldPanel('secondbody', classname="full"), FieldPanel('registerlink', classname="full"), InlinePanel('gallery_images', label="Certified Distributor Logos"), ] class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') class FormPage(AbstractEmailForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), … -
Calling a python script inside other python script using two different envs
I have two different Django applications, both are running in the same Linux server (Ubuntu 18.04 LTS), using Python 3.6 64bit. The app A is running in Django 1.11 and a Virtualenv A. The app B is running in Djando 2.1 and a virtualenv B. In the App B I need to call a function to migrate tables in App A, when I run the command in shell everything works fine. /path/to/envA/python /path/to/appA/manage.py migrate But when I try to run the same command inside App B using subprocess I have an error of no module, I suspect this is because of different envs. This is my code inside App B: subprocess.Popen(["/path/to/envA/python", "manage.py", "migrate"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) I yet tried to use shell=True but this do not work and freeze my console. -
django urls invalid syntax
I'm trying to convert urls in django project from url to path. This is what I have now and I'm getting an invalid syntax on the last comma Any idea why? Is there something I'm missing urlpatterns = [ path('favicon.ico', RedirectView.as_view( url=staticfiles_storage.url('assets/icons/favicon.ico'), permanent=False), name="favicon"), path('bets/', include('bets.paths'), path('login/', auth_views.login, {'template_name': 'base_login.html'}, name='login'), path('logout/', auth_views.logout, {'next_page': '/'}, name='logout'), path('password_reset/', auth_views.password_reset, {'template_name': 'registration/password_reset_form.html'}, name='password_reset'), path('password_reset/done/', auth_views.password_reset_done, {'template_name': 'registration/password_reset_done.html'}, name='password_reset_done'), path('reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}- [0-9A-Za-z]{1,20})/', auth_views.password_reset_confirm, {'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'), path('reset/done/', auth_views.password_reset_complete, {'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'), path('admin/', admin.site.urls), ] -
Image refuses to overlay another image within div
I cannot seem to get this icon to fit within this div. I have a div containing the first image (as well as the second icon-image). Parent div has a transparent background-overlay. Then, the image. Now, I'm trying to get the icon to overlay but it seems to be acting according to inline-block properties. Thanks in advance. <div class="slide"> <div class="imageoverlay"> <img class="slide-img z-depth-5" src="{% static 'projectweekapp/images/7.jpg' %}" alt=""> <img class="footer-icon" src="{% static 'projectweekapp/images/heart_white.png' %}" alt=""> </div> </div> .slide{ width: 100%; display: block; margin-bottom: 3px; vertical-align: top; } .imageoverlay{ min-width: 100%; max-width: 100%; background: linear-gradient(to top, rgba(0,0,0, .7) 15%, rgba(255,255,255, 0) 70% ); } .slide-img{ max-width: 100%; min-width: 100%; border-top-right-radius: 5px; border-top-left-radius: 5px; position: relative; z-index: -1; } .footer-icon{ max-width: 20px !important; max-height: 20px !important; position: absolute; z-index: 1; } -
How to send a hyperlink in a django send_mail inside html_message
I want to send a hyperlink inside the send_mail in Django , i have set html_message to an anchor but it didn't work , when i am sending an h1 tag it is working fine My django code: def sendEmail(request): email = request.POST.get('email', '') print(email) html_message='<h1><a href="http://google.com">Click</a></h1>' send_mail( 'Password Recovery', 'Subject', 'boutrosd@hotmail.com', [email], html_message=html_message ) return JsonResponse(0, safe=False) -
Django: TypeError using manage.py
I'm running Ubuntu 18.04, python3.7, and django2.1 Currently on just step 2 on Mozilla's django tutorial : https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website Checked my code multiple times and it's identical to Mozilla's code. When I try to run python3.7 manage.py runmigrations or python3.7 manage.py runserver I get: TypeError: bad operand type for unary +: 'list' I've quadruple checked to make sure that my code is identical to the guides. Please comment if it'd be helpful for me to post anymore of my code however. locallibrary/locallibrary/urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='/catalog/')), ] from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Catalog/urls.py from django.urls import path from catalog import views urlpatterns = [ ] Would it be helpful if I posted my entire typeerror? -
Multi-tenant Centralized Authentication Server
I am trying to create a centralized authentication server for multiple Django apps (APIs). I've seen posts/recommendations but none fit exactly what I am looking for. Overview: Users can be associated to one or multiple projects Users have same credentials to all projects they are associated to Use JWT tokens - use payload to add user data, sub-domain (project) to route to, role, etc Sub-domain will not be used for login. All users will login to same site and will be routed to project they are associated to (or given list if there are multiple). SSO is optional. Questions/uncertainties: Q: Should the authentication tokens be created on the authentication server or on each project? ie) Each user having one auth token for all projects or have one auth token for each project? Q: Roles will be stored in each app. I would like to send the roles along with the authentication token in the JWT. Should this data be redundantly stored on the authentication server? Another other way would be for the authentication server to access the project databases. What is the best way to handle this? Users will have different roles for each project. Q: Auth server will have …