Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select raw data from multi table
I would like to select raw data from multiple tables. eg. query = tempmodel.objects.raw('select empid as id,employee.empid,ccmaster.cscid from employee left join ccmaster on employee.cscid = ccmaster.cscid' Am I need to create a new model for tempmodel that includes all required fields? I already tried with cursor.execute but this only returns result value, not with the field. How can I select raw for multi-table? I already check that one=> raw sql with multiple table but honestly, I don't understand the answer. -
Is there a way to change what icon set for tempus dominus datetimepicker?
I've just started using tempusdominus for Bootstrap 4.0. I've got it working all well and integrates nicely with my backend. However, my site is already using an icon set (material-icons) and I want to see if I can use the icons in this font already. I changed this <div class="input-group-text"><i class="fa fa-calendar"></i></div> To use my icon from material-icons. However, I can't seem to figure out how to change the icon of the clock. I've located it in the Javascript and also looked at the docs and it only seems possible to me to change which Font Awesome icon you use. -
Django reverse function isn't properly working in management commands
I'm trying to send emails via a management command, but I'm having a hard time adding an unsubscribe link. As I stated in the title, Django reverse function from django.core.urlresolvers isn't working as expected. Honestly, I've no idea where to look. I've tried to use FORCE_SCRIPT_NAME and SCRIPT_NAME settings but these didn't get me anywhere. I'm using Django 1.8 and Python 2.7. for subscriber in active_subscribers: news_template_params['unsubscribe_link'] = reverse('news:news_unsubscribe_from_subscription', args=(subscriber.code,)) send_mail( subject=subject, message=message, html_message=render_to_string('news/email-news.html', news_template_params), from_email=from_email, recipient_list=[subscriber.email], fail_silently=True ) When I use print to see the result of reverse function, I see: print news_template_params['unsubscribe_link'] # ==> /None/news/subscription/unsubscribe/e4559105-dfb3-4c42-8019-d1ac1sasd23 The same goes for get_absoulte_url method of news objects in email template. Why is there /None/? How does it appear? -
Why can't I find elements on the page using behave-django?
I am simply trying to create my first behavioural test to locate a link on a page so that I can click on it. I have tried this with both the Chrome and Firefox drivers, but I keep getting the following error when I try to : selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: Cookie Policy I've been following several guides, but they all seem to be pretty consistent, and have found no significant discrepancy between my implementation and their instruction. The driver setup looks like this in environment.py: def before_scenario(context, feature): context.browser = webdriver.Firefox() context.browser.implicitly_wait(10) The failing step is: @when('I click on "{link_text}"') def i_click_on(context, link_text): link = context.browser.find_element_by_link_text(link_text) link.click() The scenario looks like this: Scenario: Navigate to cookie policy Given I am on the homepage When I click on "Cookie Policy" The relevant part of the html being searched is: <a href="/terms">Terms and Conditions</a>, <a href="/privacy">Privacy Policy</a>, <a href="/research-policy">Research Policy and Consent</a>, and <a href="/cookie-statement">Cookie Policy</a> The resulting error is: /Users/olorton/.local/share/virtualenvs/ogg-django-7ceMMn7K/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/behave_runner.py -t wip --stop --no-skipped --format progress manage.py behave -fcom.jetbrains.pycharm.formatter /Users/olorton/Code/ogg-django/features -t wip --stop --no-skipped --format progress -n Creating test database for alias 'default'... features/basic_user_flow.feature Traceback (most recent call last): File "/Users/olorton/.local/share/virtualenvs/ogg-django-7ceMMn7K/lib/python3.7/site-packages/behave/model.py", line 1329, in run match.run(runner.context) File … -
Why does Django ORM add a not specified field in the GROUP BY clause
I want to perform this query with the ORM : SELECT ARRAY_AGG("wcm_workflows_transition"."name") AS "names" FROM "wcm_workflows_transition" GROUP BY "wcm_workflows_transition"."workflow_id" ORDER BY "wcm_workflows_transition"."name" ASC; To do this I use Transition.objects.values("workflow__id").annotate(names=ArrayAgg("name")).values("names") But for some unknown reasons, Django adds "wcm_workflows_transition"."name" to the GROUP BY clause. So the query performed by the previous Django ORM expression is : SELECT ARRAY_AGG("wcm_workflows_transition"."name") AS "names" FROM "wcm_workflows_transition" GROUP BY "wcm_workflows_transition"."workflow_id", "wcm_workflows_transition"."name" ORDER BY "wcm_workflows_transition"."name" ASC; I cannot use aggregate because I want to use the queryset in a subquery. Here are the models (simplified) class Workflow: name = models.CharField(_(u'Name'), max_length=100, unique=True, db_index=True) class Transition(models.Model): name = models.CharField(_(u'Name'), max_length=100, db_index=True) workflow = models.ForeignKey(Workflow, verbose_name=_(u'Workflow'), related_name='transitions', db_index=True, on_delete=models.PROTECT) class Meta: ordering = ('name', ) Now I have two questions : Why Django ORM adds this fields to the GROUP BY clause ? How to perform the expected query using the ORM What I have tried : I thought that Django added in the GROUP BY all the fields that are used in the annotation, so I changed the field aggregated but it didn't change the grouped by fields. Then I asked myself if the name field had any constraint. In fact it has the db_index=True constraint. So I changed … -
Why duplicate data(notification) is saved(for same event) and web-socket connection is killed forcefully in Django-Channels?
I have created a real time notifier using web-socket, implemented using Django-Channels. It sends the "Post Author" a real time notification whenever any user likes the author's post. The problem is, for single like button click, multiple notifications are being saved in database until the web-socket is disconnected. In the following lines I will provide detail of what is actually happening(to the best of my understanding) behind the scene. 1. Like button is clicked. <a class="like-btn" id="like-btn-{{ post.pk }}" data-likes="{{ post.likes.count }}" href="{% url 'like_toggle' post.slug %}"> Like </a> JavaScript prevents the default action and generates an AJAX call to a URL. $('.like-btn').click(function (event) { event.preventDefault(); var this_ = $(this); var url = this_.attr('href'); var likesCount = parseInt(this_.attr('data-likes')) || 0; $.ajax({ url: url, method: "GET", data: {}, success: function (json) { // DOM is manipulated accordingly. }, error: function (json) { // Error. } }); }); The URL is mapped to a function defined in views.py. (Note: Code for Post Model is at the last if required for reference.) # In urls.py urlpatterns = [ path('<slug:slug>/like/', views.post_like_toggle, name="like_toggle"), ] # In views.py @login_required def post_like_toggle(request, slug): """ Function to like/unlike posts using AJAX. """ post = Post.objects.get(slug=slug) user = request.user … -
Is it possible to use vue.js with wagtail stream-fields without using DRF?
is it possible to use vue.js with wagtail stream-fields without using DRF? I would like to use wagtail and vue.js without going the headless route. So is it possible to use vue.js as part of wagtail's stream-field? -
Python Ajax Request to get searches data
At first here you go: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx If you search like smith, you will get some data and if you search whatever name you want, you will get data. so now I am tyring to get data with python request. import requests url = 'https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx' resposne = requests.get(url, params={'key': 'smith'}) print(resposne.text) then I dont see the data the searched. I want the data with what keyword i search with python. I want to get this data to visualize on my Django website but i don't to save the data in the database. I just want when user search data from the frontend, then they will see the data on the page. Can anyone help me how to get it done? How to search data with python request? I heard of selenium but I knew it works with a browser but I am confused will it work with Django following my requirement? -
AttributeError After processing the view
After Submitting the like button data is successfuly updating with the database but after this step it won't redirecting to the successful url. instead of that it is throwing attribute error. If I use HttpResponseRedirect('/album/') instaed of successful url this error is not comming. models.py Codes in models.py class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote.objects.create(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongVoteCreateView(View): form_class = SongVoteForm context = {} def get_success_url(self,**kwargs): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) def post(self,request,pk=None,song_id=None): user = self.request.user song_obj = Song.objects.get(pk=song_id) vote_obj,created = Vote.objects.get_or_create(song = song_obj,user = user) vote_form = SongVoteForm(request.POST, instance=vote_obj) if vote_form.is_valid(): new_vote = vote_form.save(commit=False) new_vote.user = self.request.user new_vote.save() return new_vote Error code Please refer this link for the traceback 'Vote' object has no attribute 'get' -
Token authentication in django (rest_framework) not working
the title pretty much says it all. I'm trying to authenticate with a token. I am getting information from the django database to my flutter app. I've successfully retrieved my token from the rest_framework and added it to the headers of the rest request. I printed these headers in django which results in { 'Content-Length': '0', 'Content-Type': 'text/plain', 'User-Agent': 'Dart/2.5 (dart:io)', 'Accept-Encoding': 'gzip', 'Authorization': 'Token 10cf58e1402b8e48c1a455aaff7f7bcf53e24231', 'Host': '192.168.0.110:8000' } The result however, is the webpage with a login form and not the rest data that I've requested. What am I missing? settings.py ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ... -
How to add a registered user to the User model (within Authentication and authorization section) in Django?
A newbie here. This is a Django related question. How can I save a newly registered user to the User Model (auth.model)? Currently, the only account which is seen inside the admin panel -- under Users (Authentication and Authorization section) is the superuser (aka me). I am using DRF (Rest framework) in order to register a user and not an HTML form. models.py: class Register(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length = 100) email = models.EmailField(max_length = 100) password = models.CharField(max_length = 100) def __str__(self): return self.name views.py: class RegisterView(APIView): def post(self, request, format=None): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response("Thank you for registering", status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from .models import Register class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Register fields = ['username', 'email', 'password'] When registering a new user via POSTMAN, the data is saved within the Register model (which is fine) but my issue is that it's not seen within the Users model. Any feedback is highly appreciated. Thank you. -
How can I annotate?
How can I annotate all copies_sold of books for each Author from django.db import models from django.db.models import Count class AuthorQuerySet(models.QuerySet): def annotate_with_copies_sold(self): return Author.objects.annotate(num_copies=Count('books__copies_sold')) class AuthorManager(models.Manager): def get_queryset(self): return AuthorQuerySet(self.model, using=self._db) def annotate_with_copies_sold(self): return self.get_queryset().annotate_with_copies_sold() class Author(models.Model): objects = AuthorManager() first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=30) copies_sold = models.PositiveIntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') -
SMTPSender Issue with Django and EmailMultiAlternatives
I'm working on a little Django project for my corporation and I need to send emails through my web application. The issue encountered is: SMTPSenderRefused (530, b'5.7.1 Client was not authenticated', 'valentin.j*****@*****.com') I configured the mail settings correctly: EMAIL_HOST = 'ptx.send.corp.****' EMAIL_HOST_USER = 'valentin.j*****@*****.com' EMAIL_PORT = 587 EMAIL_USER = '' EMAIL_PASSWORD = '' And this is my code in my views.py file: class TemplateGenerator(TemplateView): form_class = CommunicationForm template_name = 'form.html' success_url = '/HTML_Result/' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('HTML_Result') args = {'form': form} return render(request, self.template_name, args) class HTMLResult(TemplateView): template_name = 'template_1.html' def get(self, request): data = Communication.objects.values().latest('id') get_template_email(data) return render(request, self.template_name, {'data': data}) def get_template_email(data): subject = "Communication E2E" context = {'data': data} from_email, to = settings.EMAIL_HOST_USER, settings.EMAIL_HOST_USER html_content = render_to_string('template_1.html', context) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() I have a form page with some fields, once the form is validated, I overcome to an HTML page completed by form values. And this page, this template should be send by email (up to now, there is no button to send email, just when I come to … -
save() missing 1 required positional argument: 'self'
I need help with figuring out this error. Does anybody know what I did wrong here? This is the model.py database that gives out the error -
Passing multiple arguments in django view
I have tree different users and I want to use one view function and three different forms. So I need to pass two arguments to user_signup view: the request object and the form Class. In urls.py I have the following code path('signup/admin/', views.user_signup(request, AdminSignupForm), name='admin_signup') in views.py I defined user_signup function def user_signup(request, form, template_name='users/signup_staff.html'): if request.method == 'POST': form = form(request.POST) if form.is_valid(): user = form.save() # save function is redefined in AdminSignupForm else: form = form() return render(request, template_name, {'form': form}) How can I pass a request object to user_signup? -
Requested resource '{spyne.examples.django}' not found
I'm trying to develop a soap service in Django using Spyne.i clone spyne for app 'Hello_world' in django application, but i get error.i need help. My codes is similar with the below.. app = Application([HelloWorldService], 'spyne.examples.hello.http', in_protocol=HttpRpc(), out_protocol=Soap11(), ) but i get bellow error. <faultcode>soap11env:Client.ResourceNotFound</faultcode> <faultstring>Requested resource '{spyne.examples.django}' not found</faultstring> <faultactor/> -
Django ForeignKey reverse Query
I have 3 models related witch each other with FK: class MainEvent(models.Model): name = models.CharField(max_length=512, blank=True) class Event(models.Model): main_event = models.ForeignKey(MainEvent, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=512, blank=True) class SubEvent(models.Model): event = models.ForeignKey(Event, blank=True, null=True, on_delete=models.CASCADE) done = models.BooleanField(default=False) What i need is to create single reverse query on model MainEvent that holds related Events and Subevents. I will use this with Q for filter multiple options. For example: there are 2 MainEvents, each of them have 2 or more Events and each Event have 2 or more Subevents. I'm trying to create single Query something like this: [MainEvent_1:[Event_1:[Subevent_1,Subevent_2,...],Event_2:[Subevent_5,...]], MainEvent_2:[Event_2:[Subevent_2,..]]] For now I'm creating dictionary that holds desired output, but with this i con't use Q relations like & or |. At the end i'm using this data in template table to show all events and filter them: desired table structure: main event_1: event_1: subevent_1 subevent_2 event_2: subev... ........... main event_2: event_2: subev.... Thank you for your time. -
Auto update slug field in UpdateView
I have a simple blog where the post model contains a slug field that is prefilled with the post title. I would like to know how to get this slug updated in the background when the user updates a post title in the viewUpdate: models.py class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( CustomUser, on_delete=models.CASCADE ) slug = models.SlugField(unique=True) def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) urls.py urlpatterns = [ path('post/<slug:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] views.py class PostUpdateView(UpdateView): model = Post fields = ['title', 'content', 'tags'] I assume I should add something else to view.py in order to have the slug updated but after hours googling it, I could not find it. Please let me know if you need more information. It is quite a simple question so I am not sure if I should provide anything else. -
I need Help in displaying data imported from database in form of tables using django
I am making a website in which i need to display data in form of tables. I have 2 filters in form select tag which will filter the data and display in then and there in the table. //my views.py def synop_view(req): return render(req,'synops/viewsynop.html') //my html code <div class="col-sm-3 lead ml-5 mt-4"> Select Date <input type="date" class="custom-select" name="synopdate" id="myDate" > </div> <div class="col-sm-3 lead mt-4 "> UTC <select class="custom-select" name="time" id="stime"> <option value="" disabled selected>Choose your option</option> <option value="0000">0000 UTC</option> <option value="0300">0300 UTC</option> <option value="0600">0600 UTC</option> <option value="0900">0900 UTC</option> <option value="1200">1200 UTC</option> <option value="1500">1500 UTC</option> <option value="1800">1800 UTC</option> <option value="2100">2100 UTC</option> </select> </div> </div> -
Please i want to create a folder on a web page using django
I want to create a folder on a web page using django but i am unable to find answers. Please i need help, thank you in advance. I have tried searching online but i could not find something relating to that -
Django Orm , include function like asp.net core
class Genre(models.Model): name = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) i have this kind of model i want to query the data to become like this. how do i do it like this ??? [ { "id": 3, "title": "123123", "release_year": 4, "number_in_stock": 12, "daily_rate": 1.234, "genre": { genre_id: 4, name: "Action }, "date_created": "2019-10-30T08:33:59.846Z" } ] -
how to start the hamlpy
I try to use hamlpy for my project. I made the following settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ## 'hamlpy', 'testapp', ] TEMPLATE_LOADERS = ( 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], ## 'APP_DIRS': True, 'OPTIONS': { 'loaders': TEMPLATE_LOADERS, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my view: haml = lambda request: render(request,"article.haml",{}) my template: #profile .left.column #date 2010/02/18 #address Toronto, ON .right.column #bio Jesse Miller But the result page output is one line: profile .left.column #date 2010/02/18 #address Toronto, ON .right.column #bio Jesse Miller I mean nothing: the template has handled as usually django-template. What is the secret for hamlpy works on django? P.S: Django 1.11 -
python django bokeh need to select picture from database instead of path
source_glyph = AjaxDataSource( data_url=url_pic, polling_interval=STREAMING_INTERVAL, adapter=adapter_picture, method="GET" ) source_glyph.data = dict( url=[picture_path], x1=[int(picture_x_position)], y1=[int(picture_y_position)], w1=[int(width)], h1=[int(height)], ) image1 = ImageURL( url="url", x="x1", y="y1", w="w1", h="h1", anchor="center", global_alpha=0.3 ) p1.add_glyph(source_glyph, image1) picture path contains f'http://127.0.0.1:8000/media/pictures/{only_files[0]}' I need to read picture from database some how instead of from a folder. How to do it -
Django model save scikit-learn model to file field error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
I have this model and internal function that's going to create a scikit-learn model, train it save it then link it to a filefield so I can retrieve it and use it later to make predictions. class StockTrainModel(models.Model): trained_model = models.FileField(upload_to="training_model", blank=True) ... def __str__(self): return str(self.stock) def train_model(self): ... clf = RandomForestClassifier(max_depth=2, random_state=0) clf.fit(X_train, y_train) self.training_score = clf.score(X_test, y_test) * 100 filepath = 'media/uploads/training_model/{0}.sav'.format(self.stock.symbol) joblib.dump(clf, filepath) f = open(filepath) self.trained_model.save('{0}.sav'.format(self.stock.symbol), File(f, 'rb')) return self.trained_model the problem is as shown in the error below it fails with a utf-8 error encoding error and in this case I'm not exactly sure which encoding joblib that's scikit-learn model uses to encode the file, I assumed it's just bytes and tried using rb "read bytes" on the file open but it still returns the same error. --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-5-3b847b21decc> in <module> ----> 1 train_model.train_model() ~/code/coder/common/models.py in train_model(self) 159 160 f = open(filepath) --> 161 self.trained_model.save('{0}.sav'.format(self.stock.symbol), File(f, 'rb')) 162 163 return self.trained_model .... ~/code/envs/coder/lib/python3.6/codecs.py in decode(self, input, final) 319 # decode input (taking the buffer into account) 320 data = self.buffer + input --> 321 (result, consumed) = self._buffer_decode(data, self.errors, final) 322 # keep undecoded input until the next … -
Python fetching data and showing to my django website
I am developing a website and implementing a search system/ I am just want to fetch data from here: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx and show the data on my django website. I don't want to store the data in DB I am not getting how to achieve this. If you search on this website: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx with a keyword like smith it will show you huge data but no URL changes, this is the challenge to scrape So I think I need to scrape the data with selenium? or any other best way to achieve my goal? I need expert suggestion, what is the best way to do it?