Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem of Q() for and two condition in Django models
Suppose that I have these models: class X(models.Model): interface = models.OneToOneField('Interface', related_name='x') class Y(models.Model): interface = models.OneToOneField('Interface', related_name='y') class Interface(models.Model): CHOICE = ( (0, 'this is x'), (1, 'this is y'), ) owner_type = models.IntegerField(choices=CHOICE,) Now, I want to get count Interface Objects that dosen't have x relation and y relation. I used these two way: z = Interface.objects.filter(x__isnull=True).filter(y__isnull=True).count() # Get correct number of objects x = Interface.objects.filter(Q(x__isnull=True)and Q(y__isnull=True)).count() # Get wrong number of objects The z return correct result but x return wrong number. Why this happend? -
Radio Button is not selected with GET Request Django FormModel
Radio button Django is getting rendered in the form but the problem is when I try to get the selected Radio Button. It isn't selecting as per the value in the database. It just shows to select from the Radio Button I am able to POST but not GET. Model.py class myModel(models.Model): STATUS_CHOICES = [(1, 'Ok'), (2, 'Not Ok')] left_leg = models.BooleanField(choices=STATUS_CHOICES, default=1, null=True) forms.py class myModelForm(forms.ModelForm): model = myModel fields = ('left_leg') widgets = {'left_leg': forms.RadioSelect} views.py def myview(request, pk): aa = myModel.objects.get(pk=pk) if request.method == 'POST': form = myModelForm(request.POST, instance=aa) if form.is_valid(): form.save() return redirect("/") else: context = {'form': form} return render(request, "aa.html", context) aa.html <div class="col-lg-2"> <div class="form-group"> {{ form.left_leg.errors }} {% for choice in form.left_leg%} {{ choice }} {% endfor %} </div> </div> url.py path('path/update/<int:pk>/', myView, name='xx'), Please help -
I am Unable to extend the User model in Django
Here I have changed the model and view name but I am unable to extend my user model why it gives the error like Registration() got an unexpected keyword argument 'myuser' please try to solve this error. And this problem arises many time please give me the solution. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.fname class Candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.position) views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname reg = Registration(dob=dob,myuser=myuser) reg.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") error: … -
Some sent datas are not written, while some of them are written Django & Postman
Hello guys I am trying to authenticate in API written in Django Rest Framework with React.js, but before React I am testing my API with Postman, however, while trying to sign up, I am facing a problem. I am giving all required fields but it is not writing to db, when I look at Django Admin, These fields are still empty, while others are filled with the data I have given first_name second_name dob (date of birth) longitude lattitude interests Here is my models.py file in users app from django.db import models from django.contrib.auth.models import AbstractUser from courses.models import Field class CustomUser(AbstractUser): username = models.CharField(max_length=32 , verbose_name="Login", unique=True, ) first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False) second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False) # & dob = date of birth dob = models.DateField(auto_now_add=False, verbose_name="Yoshingiz", blank=False, null=True) gender_choices = [("e", "Erkak"), ("a", "Ayol")] gender = models.CharField(choices=gender_choices, verbose_name="Jinsingiz", default="e", max_length=1) interests = models.ManyToManyField(Field, verbose_name="Qiziqishlaringiz") longitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (uzunlik)", null=True, blank=True) latitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (kenglik)", null=True, blank=True) Here is my forms.py file in users app from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = … -
django orm inner join group by data
class Dishes(models.Model): """ 菜品""" cuisine_list = ((0, '川菜'), (1, '粤菜'), (2, '徽菜'), (3, '湘菜')) name = models.CharField('菜名', max_length=100) material = models.TextField('材料') cuisine = models.IntegerField('菜系', choices=cuisine_list) price = models.IntegerField('价格') def __str__(self): return self.name how to select : Information about the most expensive dish in each cuisine, including dish names and ingredients Dishes.objects.values('cuisine').annotate(max_price=Max("price")) In this way, we can only find the information with the highest price in each cuisine, excluding the names and ingredients of the dishes. It would be fine if we could query for cuisine and max_price from inner join, but what should we write in ORM? -
After clicking to like button redirecting to top of the page?
I am doing like and dislike the article. Like and dislike is working perfectly but the only problem is when I click I stay on the same page but I redirected to the top of the page. All I want to stay not only the page but also the same position my every article have images so to read the entire article we have to scroll down and the like button is the end of the article. Here are some details. post_detail page(like button) <form action="{% url 'like_post' single_post.category.slug single_post.slug %}" method="POST"> {% csrf_token %} <button type="submit" name="like_btn" value={{single_post.id}} class="ui red button like_btn" > <i class="heart icon"></i> Like ({{single_post.total_likes}}) </button> </form> urls.py path('<slug:category_slug>/<slug:post_slug>', views.post_detail , name="post_detail"), path('like/<slug:category_slug>/<slug:post_slug>', views.like_post, name="like_post") post model class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField(max_length=100) image = models.ImageField(upload_to = 'photos/post_image/%Y/%m/%d/', default="../static/images/pp2.jpg") category = models.ForeignKey(Category, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_likes') description = FroalaField() views = models.IntegerField(default=0) comments = GenericRelation(Comment) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Post, self).save(*args, **kwargs) def total_likes(self): return self.likes.count() def get_url(self): return reverse("post_detail", args=[self.category.slug, self.slug]) def __str__(self): return self.title views.py def like_post(request,category_slug, post_slug): post = get_object_or_404(Post, id=request.POST.get('like_btn')) liked = False if post.likes.filter(id … -
why Image is not loading in django template?
I uploaded a picture in the Django database but when I try to show this picture in Django templates, it's not showing anything but showing the image title. Here is my index.html {% for value in data %} <div class="product-box"> <div class="img-wrapper"> <div class="front"> <a href="product-page(no-sidebar).html"><img src="{{ value.product_img.url }}" class="img-fluid blur-up lazyload bg-img" alt=""></a> </div> <div class="back"> <a href="product-page(no-sidebar).html"><img src="{{ value.product_img.url }}" class="img-fluid blur-up lazyload bg-img" alt=""></a> </div> <div class="cart-info cart-wrap"> <button data-bs-toggle="modal" data-bs-target="#addtocart" title="Add to cart"><i class="ti-shopping-cart"></i></button> <a href="javascript:void(0)" title="Add to Wishlist"><i class="ti-heart" aria-hidden="true"></i></a> <a href="#" data-bs-toggle="modal" data-bs-target="#quick-view" title="Quick View"><i class="ti-search" aria-hidden="true"></i></a> <a href="compare.html" title="Compare"><i class="ti-reload" aria-hidden="true"></i></a> </div> </div> <div class="product-detail"> <div class="rating"><i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i></div> <a href="product-page(no-sidebar).html"> <h6>{{ value.product_title }}</h6> </a> <h4>{{ value.price }}</h4> <ul class="color-variant"> <li class="bg-light0"></li> <li class="bg-light1"></li> <li class="bg-light2"></li> </ul> </div> </div> {% endfor %} Here is my views.py def home(request): context={ 'data': Products.objects.all() } return render(request, 'auctionApp/index.html',context) -
Server Error (500) On Password Request when deployed Django Project at Heroku
I have deployed my Django Project on Heroku https://billpayy.herokuapp.com/. When I try to reset the password, it gives an Error 500 page. The Password Reset functionality works fine locally but gives this error when deployed. Also, couldn't decode much from the Error Logs: 2021-05-30T12:08:10.012088+00:00 heroku[router]: at=info method=POST path="/account/password_reset/" host=billpayy.herokuapp.com requ est_id=90b04f79-c813-4efa-8d2a-aa922d0bcae9 fwd="27.4.64.168" dyno=web.1 connect=4ms service=765ms status=500 bytes=403 protocol=http 2021-05-30T12:08:10.012273+00:00 app[web.1]: 10.30.51.66 - - [30/May/2021:12:08:10 +0000] "POST /account/password_reset/ HTTP/1.1" 50 0 145 "http://billpayy.herokuapp.com/account/password_reset/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l ike Gecko) Chrome/91.0.4472.77 Safari/537.36" settings.py """ Django settings for billing_site project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os import django_heroku from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['billpayy.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'billingapp.apps.BillingappConfig', 'users.apps.UsersConfig', 'bootstrap4', 'crispy_forms', 'bootstrap_datepicker_plus', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
How to use .filter correctly in Django and code seems not to be executed
I'm trying to map positions from one table to another table, but at the moment i am really confused about using .filter. I have a Worker class like this, class Worker(models.Model): """Model representing a worker.""" personal_id = models.IntegerField(primary_key=True, help_text='Unique ID for a worker in the whole company') position = models.ForeignKey(Position, on_delete=models.SET_NULL, null=True) Machine_of_Worker = models.ManyToManyField('Machine', blank=True, related_name = 'workers') """ insert filtering method here """ class Meta: ordering = ['personal_id'] def __str__(self): """String for representing the Model object.""" return f'{self.last_name}, {self.first_name}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('worker-detail', args=[str(self.personal_id)]) a Machine class like this > class Machine(models.Model): > """Model representing a Machine.""" > machine_id = models.IntegerField(primary_key=True, help_text="enter machine number as unique id here") > Worker_On_Machine = models.ManyToManyField(Worker, blank=True, related_name = 'machines') > position = models.ForeignKey(Position, on_delete=models.SET_NULL, blank=True, null=True) and a position class according to this. class Position(models.Model): """ Model representation of the positions and ground states """ square_id = models.IntegerField(primary_key=True, help_text='Unique ID for a position square in x/y coordinate in the whole company') x_pos = models.IntegerField(default = 0, help_text="enter x coordinate here") y_pos = models.IntegerField(default = 0, help_text="enter y coordinate here") My WorkerAdmin looks like this class WorkerAdmin(admin.ModelAdmin): readonly_fields = ['worker_on_machine'] list_display … -
how to run many task parallel in celery?
I have code like this : def calculator(number): ( I/O bound operation .get data from API and insert to Redis ) def starter(): for i in range(100): calculator(i) this code takes 250 seconds to finish. I rewrite code with celery ,like this : @shared_task def calculator(number): ( I/O bound operation. get data from API and insert to Redis ) def starter(): for i in range(100): calculator.delay(i) and I start my celery worker with : celery -A my_app worker -l info -c 4 and it took me about 260 seconds and there isn't any difference in those both ways I take 250-260 seconds. I want to break 260 to 50 seconds to finish jobs. can anyone help me? -
How to 'convert' MP3 file to numpy array or list
I'm working on an audio-related project that connects with Django backend via rest api. Part of the front-end requires to display waveforms of associated mp3 files and for this, it in turn requires optimized data of each mp3 file in form of an array, which the front-end (javascript) then processes and converts to a waveform. I can pick the associated mp3 file from backend storage, the problem is converting it into an array which I can serve to the front-end api. I have tried several methods but none seem to be working. I tried this How to read a MP3 audio file into a numpy array / save a numpy array to MP3? which leaves my computer hanging until I forced it to restart by holding the power button down. I have a working ffmpeg and so, I have also tried this Trying to convert an mp3 file to a Numpy Array, and ffmpeg just hangs which continues to raise TypeError on np.fromstring(data[data.find("data")+4:], np.int16). I can't actually say what the problem is and I really hope someone can help. Thank you in advance! -
self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200
This is were the error comes from def test_single_status_retrieve(self): serializer_data = ProfileStatusSerializer(instance=self.status).data response = self.client.get(reverse("status-detail", kwargs={"pk": 1})) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content) self.assertEqual(serializer_data, response_data) It seems like the error is coming from somewhere else. This is what I got when I ran the test (ProjectName) bash-3.2$ python3 manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F......... ================================================================= FAIL: test_single_status_retrieve (profiles.tests.ProfileStatusViewSetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "path.../ProjectName/src/profiles/tests.py", line 101, in test_single_status_retrieve self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 10 tests in 1.362s FAILED (failures=1) Destroying test database for alias 'default'... -
How does Google Translate handle audio streaming for "Translate by Audio"
How to best way to stream microphone data from browser to server and are there any documentation about how does Google handle this topic? As an example in case: "Translate by Audio" in Google Translate. I use Django web framework in the backend, behind a Nginx reverse proxy and I would like to process microphone data coming from browser. Open for suggestions. Thx! -
Django - Use TextInput form to look up a ForeignKey
I'm currently trying to build an application in Django where users should be able to create new entries for a model. Said model contains a ForeignKey relation to a different model. However, the classic dropdown form field is not practical, because there could be hundreds of entries to choose from. Instead, I'd like to allow users to simply type in the name of the entry (all names are unique), which then gets transformed to the corresponding ID when pressing the Submit button. I feel like this should be pretty straightforward to do, but since I'm new to Django I'm having a hard time to figure out how to do it. Currently the problem is, that the form field is declared invalid, due to the ForeignKey not existing (since the user typed in the name and not the ID of the database entry). Code example: forms.py: class DogForm(ModelForm): class Meta: model = Dog fields = "__all__" widgets = {" shelter": widgets.TextInput(attrs={"id":" shelter", "placeholder":" Dog Shelter"}), "name": widgets.TextInput({"id":"name", "placeholder":"Name"}), def clean(self): shelter= self.data.get("shelter") self.cleaned_data["shelter"] = Shelter.objects.get(name=shelter) return self.cleaned_data views.py: class DogCreate(CreateView): model = Dog form_class = DogForm def form_valid(self, form): if form.is_valid(): instance = form.save(commit=False) instance.save() return super(DogCreate, self).form_valid(form) As you can … -
How to receive video in real-time for computation?
I want to create a Deep learning model which can detect objects in real time, I'll be creating an Android application which will send realtime video. The Backend which will be created in Django which will receive the video and forward it to the DL model to for further computation in real-time. After that the model will providee the results which needs to be sent back toh the Android application / client for displaying the results. How to receive the video in Backend in realtime so that the DL model can do the computation? -
Show pie chart based on status in Django template
Good Afternoon, I want to show a pie chart on my django project where the data feeding the chart will be the count of each individual status currently I have this in my views.py def pie_chart(request): labels = [] data = [] queryset = Task.objects.aggregate( ncompl = Count('pk', filter=Q(status='complete')), noverrun = Count('pk', filter=Q(status='overdue')), ninprog = Count('pk', filter=Q(status='in progress')), nnotstrtd = Count('pk', filter=Q(status='not started')) ) for task in queryset: labels.append(task.title) data.append(queryset) return render(request, 'pie_chart.html', { 'labels': labels, 'data': data, }) for my template.html I have <div class="map_section padding_infor_info"> <canvas id="pie_chart"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> var config = { type: 'pie', data: { datasets: [{ data: {{ data|safe }}, backgroundColor: [ '#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3' ], label: 'Population' }], labels: {{ labels|safe }} }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> models.py class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, related_name="tasks", on_delete=models.CASCADE) priority = models.CharField(max_length=20, choices=priority) status = models.CharField(max_length=20, choices=status) assigned = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField(default=date.today) end_date = models.DateField(default=date.today) def __str__(self): return '%s - %s' % (self.project.name, self.title) def get_absolute_url(self): return reverse('projects:task-details') i want to archive results as enter image description here -
Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2> ~
I don't want to fetch all the querysets and I would like to have their assigned values in those values Need to fix the problem? ValueError at /join/element_detail/ Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2>, <Designated: 3>, <Designated: 4>, <Designated: 5>, <Designated: 6>, <Designated: 7>, <Designated: 8>, <Designated: 9>]>": "Element.designated_code" must be a "Designated" instance. Request Method: POST Request URL: http://127.0.0.1:8000/join/element_detail/ Django Version: 3.1.5 Exception Type: ValueError Exception Value: Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2>, <Designated: 3>, <Designated: 4>, <Designated: 5>, <Designated: 6>, <Designated: 7>, <Designated: 8>, <Designated: 9>]>": "Element.designated_code" must be a "Designated" instance. views.py from django.shortcuts import render # Create your views here. from zeronine.forms import ElementForm from zeronine.models import * def element_detail(request): designated_object = Designated.objects.all() element_object = Element.objects.all() value_object = Value.objects.all() if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] element.designated_code = designated_object element.save() return render(request, 'zeronine/list.html') else: form = ElementForm() return render(request, 'zeronine/detail.html', {'form': form, 'designated_object': designated_object, 'element_object': element_object, 'value_object': value_object}) -
Application Error in Heroku while deploying Django app, specifically, the log tail says = Build failed -- check your build output: *link*
This is my very first time deploying a Django app in heroku and I was following an article to git push and all the other tasks. The problem started when I started to push master. My app was not loading. So from heroku documentation I moved the push to main and deleted the master. And a new problem arose that is the application error, and asked to heroku log --tails. Later I found the Procfile didn't had the right app name. corrected that and restarted heroku. Still it shows application error with the line in red saying : Build failed -- check your build output: https://dashboard.heroku.com/apps/6609d304-92ca-454e-8659-561a8adbb11a/activity/builds/6c1dd096-0d90-49af-a5db-55eec4dff27b for the heroku logs --tail. terminal : heroku logs --tail (env) D:\DJPROJ\OFFSET_V1.1\v1>heroku logs --tail 2021-05-30T08:27:39.043493+00:00 app[api]: Initial release by user aera4242@gmail.com 2021-05-30T08:27:39.043493+00:00 app[api]: Release v1 created by user aera4242@gmail.com 2021-05-30T08:27:39.615588+00:00 app[api]: Enable Logplex by user aera4242@gmail.com 2021-05-30T08:27:39.615588+00:00 app[api]: Release v2 created by user aera4242@gmail.com 2021-05-30T08:33:03.000000+00:00 app[api]: Build started by user aera4242@gmail.com 2021-05-30T08:33:32.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/6609d304-92ca-454e-8659-561a8adbb11a/activity/builds/bb5f0314-a49e-4e29-b6a0-1ec421b92733 2021-05-30T08:47:08.146897+00:00 app[api]: Starting process with command `python manage.py migrate` by user aera4242@gmail.com 2021-05-30T08:47:08.852782+00:00 heroku[run.2613]: State changed from starting to up 2021-05-30T08:47:09.202077+00:00 heroku[run.2613]: Awaiting client 2021-05-30T08:47:09.491181+00:00 heroku[run.2613]: Starting process with command `python manage.py migrate` … -
Django Bootstrap column issue and help/explanation
Hey guys I need help with Django logic & bootstrap, as well as an explanation if possible. I am trying to achieve the attached file. I did it with plain html/bootstrap, but I am unable to do it in Django, so there is definitely some flow within my code. what I am trying to achive <div class="container-fluid"> <div class="row"> {% for post in object_list %} <div class="col-lg-3 col-sm-12"> {% if post.is_on_home_page post.is_side_story is True %} {% if post.home_or_category_image %} <div class="top-articles-images"><img class="img-fluid" src="{{ post.home_or_category_image.url }}"></div> {% endif %} <div class="cover-info"> <a class="top-articles-label" href="{% url 'categories' post.category.slug %}">{{ post.category }}</a> <h4> <a href="{% url 'article-detail' post.slug %}"> {{ post.title }}</a> </h4> <p> {{ post.snippet }} </p> <p> By: {{ post.author }} </p> {% endif %} </div> <div class="col-lg-6 col-sm-12"> {% if post.is_on_home_page and post.is_main_on_home_page is True %} {% if post.home_or_category_image %} <div class="top-articles-images"><img class="img-fluid" src="{{ post.home_or_category_image.url }}"></div> {% endif %} <div class="cover-info"> <a class="top-articles-label" href="{% url 'categories' post.category.slug %}"> {{ post.category }} </a> <h4> <a href="{% url 'article-detail' post.slug %}"> {{ post.title }}</a> </h4> <p> {{ post.snippet }} </p> <p> By: {{ post.author }} </p> {% endif %} </div> <div class="col-lg-3 col-sm-12"> {% if post.is_on_home_page and post.is_side_story is True %} {% … -
Set default font family for TinyMCE HTMLFiled()
I have set default font family "Sofia Sans" in tag for all templates in custom.css but when I paste a text with different font family in the Django Admin TinyMCE HTMLFiled() it overrides the default font. Is it posible to set default font family for the HTMLFiled() to be "Sofia Sans" no matter what the copied text font is? -
Django File Field : Audio File is not forwarding and rewinding
Well I don't even know that is it a django problem or not but can you please help me I have following field in my model. url = models.FileField(upload_to='music', null=True) I have no problem uploading the file. in my API - I'm getting the url of the file which I'm uploading but when I use it with javascript I'm not able to forward it or rewind it. even if directly open it from link in the browser I face the same problem. I guess it's not loading the meta data of the file first. but what should I do. -
Error while running '$ python manage.py collectstatic --noinput'. Even though I have set STATIC_ROOT and STATIC_FILES_DIRS
This is the error message I get: [2021-05-30T10:39:25.931285815Z] -----> $ python manage.py collectstatic --noinput [2021-05-30T10:39:26.203723037Z] Traceback (most recent call last): [2021-05-30T10:39:26.216276562Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 204, in fetch_command [2021-05-30T10:39:26.218321657Z] app_name = commands[subcommand] [2021-05-30T10:39:26.220104587Z] KeyError: 'collectstatic' [2021-05-30T10:39:26.224315059Z] During handling of the above exception, another exception occurred: [2021-05-30T10:39:26.226203429Z] Traceback (most recent call last): [2021-05-30T10:39:26.228807809Z] File "/workspace/manage.py", line 22, in <module> [2021-05-30T10:39:26.229778775Z] main() [2021-05-30T10:39:26.232093136Z] File "/workspace/manage.py", line 18, in main [2021-05-30T10:39:26.234133309Z] execute_from_command_line(sys.argv) [2021-05-30T10:39:26.239913239Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line [2021-05-30T10:39:26.241335162Z] utility.execute() [2021-05-30T10:39:26.246299500Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute [2021-05-30T10:39:26.249345439Z] self.fetch_command(subcommand).run_from_argv(self.argv) [2021-05-30T10:39:26.255367504Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 211, in fetch_command [2021-05-30T10:39:26.256776257Z] settings.INSTALLED_APPS [2021-05-30T10:39:26.263303743Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 57, in __getattr__ [2021-05-30T10:39:26.263988051Z] self._setup(name) [2021-05-30T10:39:26.269528994Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 44, in _setup [2021-05-30T10:39:26.271917901Z] self._wrapped = Settings(settings_module) [2021-05-30T10:39:26.276311739Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 107, in __init__ [2021-05-30T10:39:26.279100519Z] mod = importlib.import_module(self.SETTINGS_MODULE) [2021-05-30T10:39:26.283428429Z] File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module [2021-05-30T10:39:26.286322693Z] return _bootstrap._gcd_import(name[level:], package, level) [2021-05-30T10:39:26.289320899Z] File "<frozen importlib._bootstrap>", line 1030, in _gcd_import [2021-05-30T10:39:26.292269277Z] File "<frozen importlib._bootstrap>", line 1007, in _find_and_load [2021-05-30T10:39:26.295544601Z] File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked [2021-05-30T10:39:26.298809741Z] File "<frozen importlib._bootstrap>", line 680, in _load_unlocked [2021-05-30T10:39:26.302382236Z] File "<frozen importlib._bootstrap_external>", line 790, in exec_module [2021-05-30T10:39:26.306047614Z] File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed [2021-05-30T10:39:26.313158573Z] File "/workspace/onlineminer/settings.py", line 5, in <module> [2021-05-30T10:39:26.313914416Z] import dj_database_url [2021-05-30T10:39:26.316344819Z] ModuleNotFoundError: No module … -
Django REST social login with dj_rest_auth does not authenticate the user
I am building an application. The client is built with Next.js and the backend with Django and Django REST framework. In this application, I would like to have social login. So far, my situation is this. I have set up the OAuth on the Google dashboard On the client, I am using next-auth - The client is successfully calling Google and getting an access token from there. On the client, the callback that runs after getting the access token from Google makes a call my Django API. I have set up the backend with dj_rest_auth - My settings are almost identical to the ones described here. Once the client callback runs and calls my Django API with the access token from Google, I successfully get on the client an access token and a refresh token. If it is a new user loggin in the first time, a new user is created in Djangos DB const response = await fetch(`${djangoAPIurl}/api/social/login/google/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ access_token: accessToken, id_token: idToken }) }); const data = await response.json(); const { access_token, refresh_token } = data; Both access_token and refresh_token are defined and appear to be valid tokens. So … -
Chart js space above bar graph
I generate graph depending on the value from my calculations. Problem is, I don't know how to set up 'margins', how to define where to put data labels. Datalables definition: datalabels: { anchor: 'end', align: 'start', offset: 5, Problem is, when a certain month value is 0, it's written over the labels on the bottom. Easy way to fix this would be to define a space about each column, so that it can that text can never go 'off screen' and define align: 'end'. Case 2: -
Module does not define class error while replacing default admin site
I'm following a tutorial for the Django admin app and I'm trying a step in which the default admin site is replaced with a custom subclass of AdminSite from django.contrib.admin. My project structure is: MyAdminTutorial |- MyAdminTutorial |- MyActualApp |- JustAUserApp MyActualApp.admin.py: class MyAdminSite(admin.AdminSite): pass admin.site = MyAdminSite() admin.site.register(User, UserAdmin) admin.site.register(Group, GroupAdmin) MyActualApp.apps.py: from django.contrib.admin.apps import AdminConfig class MyAdminConfig(AdminConfig): default_site = 'MyActualApp.admin.MyAdminSite' MyAdminTutorial.settings.py INSTALLED_APPS = [ "MyActualApp.apps.MyAdminConfig", # 'django.contrib.admin', .... "JustAUserApp", ] If I try to run the development server I get this error: ImportError: Module "MyActualApp.admin" does not define a "MyAdminSite" attribute/class Messing around in the debugger i found the error stems from a call to getattr() inside import_string() in django.utils.module_loading.py. For the current call to import_string() the module name and path are set to MyActualApp.admin, getting the current location in the debug console yields the main MyActualApp directory (the project's), but calling getattr(module, "MyAdminSite") triggers the error above. I expect the MyAdminSite class to be found, but that's not the case, what is going on in this project, what further checks am I not considering?