Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
About modifucation of Whoosh score algorithm
I have 2 questions about whoosh, hope someone can help me. (1) How can I get the number of unique items in given documents, it seem that the funtion “doc_field_length” could only support the number of total tokens in given documents. (2) How can I get the number of a query , for example when a query is " banana apple animal" , the number should be 3. Since I would develop a new scoring method instead of the original one "BM25" My whoosh version 2.7.4, python 3.5.6 Thank you very much -
How to link to other user's profile in django?
What I have been trying is to click the post's author(user that created the post) I want it to redirect me to that user's profile,for example in instagram when you click the user that is on top of the post it redirects you to their profile. Everytime I do that instead of seeing the post's author profile I see the loged in user profile. I think there is something wrong in the views.py file or in the base.html. views.py def profile(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) def home(request): created_posts = Create.objects.all().order_by("-added_date") return render(request, 'base.html', {"created_posts": created_posts}) def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] user = request.user created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user) created_obj.save() print('create created') return redirect('home') else: print('create not created') return render(request, 'create.html') models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' urls.py urlpatterns = [ path('', views.home, name='home'), path('profile', views.profile, name='profile'), path('profile/<int:pk>/', views.profile, name='profile_pk'), path('create', views.create, name='create'), ] profile.html (shows user's profile) … -
accessing product sub categories like ebay in django form
i am trying to replicate the category structure sites like Ebay use when posting a product. For example, if you want to post an Iphone for sale, you go to post an ad, choose a category from the drop down menu on the form('electronics & computers'), then choose a subcategory of "phones", then the last sub category of "iphone". To create this structure i am using django-categories. Creating a product in the admin page works file, the admin form allows me to choose from a drop down menu of every category, however i can't seem to replicate that same process on my own form, to give users the ability to choose from the many categories. If your not aware if django-categories it is a Modified Preorder Tree Traversal. Here is my advert model class Advert(models.Model): title = models.CharField(max_length=100, blank=False, null=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='media/', blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(blank=False, null=False) condition = models.CharField(max_length=10, choices=COND_CATEGORIES, blank=False, null=False) price = models.DecimalField(decimal_places=2, max_digits=14, blank=False, null=False) description = models.TextField(blank=False, null=False) date_posted = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) search_vector = SearchVectorField(null=True, blank=True) Here is the category model class Category(CategoryBase): class Meta: … -
Do I need to setup Whitenoise if Deploying with django-heroku?
The Heroku documentation says: The django-heroku package automatically configures your Django application to work on Heroku. It is compatible with Django 2.0 applications. It provides many niceties, including the reading of DATABASE_URL, logging configuration, a Heroku CI–compatible TestRunner, and automatically configures ‘staticfiles’ to “just work”. However, I saw other sources where they recommend setting up whitenoise for handling static files. Do I need whitenois if I setup django-heroku? Thanks. -
How do i save to database Js to Django
views.py def game1(request): if request.method == 'POST': point = request.POST['puan'] username = request.user.username User.objects.filter(username= username ).update(point=point) messages.add_message(request,messages.SUCCESS,'Puan başarıyla güncellendi.') return render(request, 'pages/gamepage.html') else: messages.add_message(request,messages.WARNING,'Bir hata oluştu.') return render(request, 'game/game.html') game1.html if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) { alert("Oyun bitti.\nPuanınız: " + snake.maxCells +"\nPuanınız kaydediliyor..."); // location.reload(); } Good day everybody i need help with something How to print the snake.maxCells into the database after the alert -
how i can update a model's field from another model in django?
my models.py is : class clients(models.Model): client_id = models.IntegerField(unique=True, primary_key=True ) ' ' money = models.IntegerField(default = 0) class transfermoney(models.Model): first_client_id = models.IntegerField() second_client_id = models.IntegerField() amountofmoney = models.PositiveIntegerField() time = models.TimeField(auto_now=True) date = models.DateField(auto_now=True) my serializers.py is : class UserSerializer(serializers.ModelSerializer): class Meta: model = clients fields = ('__all__') class moneytransfer(serializers.ModelSerializer): class Meta: model = transfermoney fields = ('__all__') my views.py is : class transferingmoney(APIView): def post(self,request): serializer = moneytransfer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i'm using django rest framework , and what i want is ,everytime when i make a post request into "transfermoney" model , it take the "first_client_id" and search for it into the "client_id" in the "clients" model and add the "amountofmoney" from "transfermoney" model to the "money" field in "clients" model , and the same for the "second_client_id" please how can i do that ? -
Why is Django a 'less secure' app according to Google?
Why does Google consider a request from my Django app to send an email via SMTP (smtp.gmail.com) to be insecure? Reading their security standards is not very helpful: How more secure apps help protect your account When a third-party app meets our security standards, you can: See what level of account access you’re giving the app before you connect your Google Account Let the app access only a relevant part of your Google Account, like your email or calendar Connect your Google Account to the app without exposing your password Disconnect your Google Account from the app at any time This is a very common issue when emailing from Django. There are tutorials and stackoverflow question/answers (second answer) that 'solve' this by changing settings in your google account to allow less secure apps. I had this working and was OK with it until I read this from Control Access to Less Secure Sites: Because Google is beginning to shut off Google Account access to less secure apps, the enforcement option is no longer available. We recommend turning off less secure apps access now. You should start using alternatives to less secure apps. As Google gradually moves away from allowing less … -
Django not rendering CSS
I am new to programming and currently Django will not render my CSS. This is the html request GET http://127.0.0.1:8000/static/blog/main.css net::ERR_ABORTED 404 (Not Found) Here's my current set up and what I know to be required for using static files. I don't understand how my paths are wrong if they are? In settings.py...it is installed INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', along with URL defined STATIC_URL = '/static/' This is my directory for my css file /Users/jason/PycharmProjects/blog/mysite/blog/static/blog/main and this is my html header {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> -
How to filter for a ManytoManyField with through in Django?
Trying to filter through all protocol data sources with their specific datasources in Protocol. Tried to use this: ProtocolDataSource.objects.filter(protocol__data_sources=..., protocol__data_sources=...) but obviously this comes up with an error. The dots are the name of the data source. class DataSource(Base): name = models.CharField( max_length=200, unique=True, verbose_name='Data Source Name') url = models.URLField( max_length=255, unique=True, verbose_name='Data Source URL') desc_help = 'Please briefly describe this data source.' description = models.TextField( verbose_name='Data Source Description', help_text=desc_help) class ProtocolDataSource(Base): protocol = models.ForeignKey( Protocol, related_name='protocol_data_sources') data_source = models.ForeignKey( DataSource, verbose_name='Data Source') path = models.CharField( max_length=255, verbose_name='Path to record collection') class Protocol(BaseWithImmutableKey): name = models.CharField( max_length=200, unique=True, verbose_name='Protocol Name') data_sources = models.ManyToManyField( DataSource, through='ProtocolDataSource') users = models.ManyToManyField(User, through='ProtocolUser', blank=True) organizations = models.ManyToManyField(Organization, blank=True) -
Django Wagtail template - if statement not working
Hi hopefully this is a simple fix. I'm still fairly new to Django/Wagtail and would appreciate any help. My goal is to better format my form fields by filtering with the field.label_tag value. I know for a fact the value of field.label_tag is as expected, but still no luck after confirming the output in the template and trying a few variations on the if statement. {% for field in form.visible_fields %} <div class="control-group"> <div class="form-group floating-label-form-group controls"> <label>{{ field.label_tag }}</label> {% if field.label_tag|stringformat:"s" == "Email Address" %} <strong>field.label_tag</strong> {% endif %} {% if field.label_tag|stringformat:"s" == "Message" %} {% render_field field class+="form-control" placeholder+="Message" id+="message" %} {% endif %} <p class="help-block text-danger"></p> </div> </div> {% endfor %} -
Django model form saving
Creating an eCommerce website now I have a Address model form which has another model as a foreignkey element i.e Billing Model. So the issue here is the Address form does not save I tried printing out the input data to see if it actually is receiving anything but nothing Below is my address model class Address(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES) address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=120, default='South Africa') province = models.CharField(max_length=120) postal_code = models.CharField(max_length=120) def __str__(self): return str(self.billing_profile) Below is my address form from django import forms from .models import Address class AddressForm(forms.ModelForm): class Meta: model = Address fields = [ 'address_line_1', 'address_line_2', 'country', 'province', 'postal_code', ] Bellow is my my html to render page {% if not object.shipping_address %} <div class="row"> <div class="col-md-6 mx-auto col-10"> <p class='lead'>Shipping Adress</p><br> {% url 'checkout_address' as checkout_address %} {% include 'addressForm.html' with form=address_form next_url=request.build_absoulute_uri adress_type='shipping' action_url=checkout_address %} </div> </div> </div> {% else %} <h1>Checkout</h1> <p>Cart Total: {{ object.cart.total }}</p> <p>Shipping Total: {{ object.shipping_total}}</p> <p>Order Total: {{ object.total }}</p> -
Can I use chromedriver with selenium for webscraping within django?
I am trying to call chromedriver with selenium inside Django for webscraping, but am having trouble. I already have a python script than scrapes data with selenium and chromedriver, but want to integrate it into Django. Is this possible? How would this work? I would like to keep using chromedriver for my webscraping within Django and prefebally don't want to show the user the chromedriver window. Would the window being controlled open up on the user's end? Would the user of the Django website need to have chromedriver installed for it to work? Would appreciate any help and advise. -
Django, Ajax and jQuery - posting form without reloading page and printing "succes" message for user
I would like to kindly ask you for your help. I wanted to create simple voting system. I somehow succeeded. I have simple "UP" button that post form with simple +1 integer for scorevalue of post. It have a lot of problems right now but I will fight with them later. Right now I wanted to add this +1 score without refreshing page (like most modern websites). I did my googling and I came up with this: https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ I have to say that it is working quite well, even with my zero knowledge about js, jquery or ajax. My problem is, that javascript is adding this +1 but it also is giving me some errors that I cannot grasp: responseText: "TypeError at /viewquestion/6/voteup\n__init__() missing 1 required positional argument: 'data'\n\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/viewquestion/6/voteup\nDjango Version: 3.0.4\n I would like to either get rid of them or understand nature of them :P And my second or main problem is that. Voting is working, but score don't change because ofcourse, page is not reloading. And I also cannot print "Success voting" message for user because, well website is not refreshing. Giving user some simple message "Voting Success" would be enough for me. Best … -
How to develop two list views that lead to one detail view in django?
I want to create a website that has a section for events. So the mapping would be done as: Homepage > Events > Event name > Event date > Event details Basically, the same type of event was held multiple times a year, so event date is a list of dates on which the event was held. I don't know how to approach this problem. I mean, I want to display a list that further displays another list and then the event details are displayed. I don't have any clue on how to do that in django. -
Django, TypeError: unhashable type: 'dict', where is the error?
I'm new in django. I'm trying to run my code but give me the following error: TypeError: unhashable type: 'dict'. I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports? Here my models.py class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantita')*F('prezzo'), ) def get_monthly_totals(self): conto = dict((c.id, c) for c in Conto.objects.all()) return list( (conto, datetime.date(year, month, 1), totale) for conto_id, year, month, totale in ( self.values_list('conto__nome', 'data__year', 'data__month') .annotate(totale=Sum(F('quantita') * F('prezzo'))) .values_list('conto__nome', 'data__year', 'data__month', 'totale') )) class Conto(models.Model): nome=models.CharField('Nome Conto', max_length=30, blank=True, default="") def __str__(self): return self.nome class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE,) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) um = models.CharField() quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField('Data di acquisto', default="GG/MM/YYYY") objects=MaterialeManager() def __str__(self): return str(self.sottocategoria) and here my views.py: def conto_economico(request): defaults = list(0 for m in range(12)) elements = dict() for conto, data, totale in Materiale.objects.get_monthly_totals(): if conto not in elements: elements[conto] = list(defaults) index = data.month - 1 # jan is one, but on index 0 elements[conto][index] = totale context= {'elements': elements,} return render(request, 'conto_economico/conto_economico.html', context) -
Django urls NoReverseMatch - missing argument
I've a more or less working comment and edit comment system. However, when I configured everything so that the proper userreview_id is pulled to the url in my UpdateView, it broke the link going from index page to details (it is in details thatare displayed comments, access to comment form and to updateview form). Here is my code with Broken URL urlpatterns = [ # ex: /restaurants/ path('', views.index, name='index'), # ex: /restaurants/15 path('<int:restaurant_id>/', views.details, name='details'), path('/edit/review/<int:userreview_id>', views.EditReview.as_view(), name='edit-review'), ] Details view def details(request, restaurant_id): # calling restaurant ID and displaying it's data restaurant = get_object_or_404(Restaurant, pk=restaurant_id) # calling a review and displaying it's data user_review_list = UserReview.objects.filter(pk=restaurant_id) user_reviews = [] for user_review in user_review_list: if user_review.posted_by == request.user: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by, "edit": user_review.get_edit_url}) else: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by}) return render(request, 'restaurants/details.html', {'restaurant': restaurant, 'user_review_list': user_reviews,}) index template {% extends "base_generic.html" %} {% block content %} <h1>Restauracje Poznan</h1> <p> Search by name or city <form action="{% url 'restaurants:search_results' %}" method="get" class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <input name="q" type="text" placeholder="Search..."> </div> <div> <input type="submit" class="btn btn-primary mb-2" value="Search"> </div> </form> </p> <h2>Restaurants and other gastronomy places:</h2> {% if restaurants_list %} <ul class="list-group"> {% for restaurant in … -
Real time updates in a Django template
I have a django webapp that displays stock data. How it works: I make requests to a stock data API and get data every 15 mins when the US stock market is open. This is a background periodic task using Celery. I have a database where I update this data as soon as I get it from the API. Then I send the updated data from the database to a view, where I can visualize it in a HTML table. Using jQuery I refresh the table every 5mins to give it a feel of "real time", although it is not. My goal is to get the HTML table updated (or item by item) as soon as the database gets updated too, making it 100% real time. The website will have registered users (up to 2500-5000 users) that will be visualizing this data at the same time. I have googled around and didn't find much info. There's django channels (websockets), but all the tutorials I've seen are focused on building real time chats. I'm not sure how efficient websockets are since I have zero experience with them. The website is hosted on Heroku Hobby for what its worth. My goal is … -
Django - decorators restrict "staff"
My goal is to restrict the access the the "staff Group" I am trying to do that with the decorators.py but when I do that, it restricts every user I have registered and not only the staff. When I log in with admin it gives me " you are not authorized" that should be only for the "staff" that should see only one template of the platform. Here the picture also of my admin page. core/decorators.py from django.http import HttpResponse from django.shortcuts import redirect def allowed_user(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all() if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse(' You are not Authorized!') return wrapper_func return decorator core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView from .decorators import allowed_user # Create your views here. from quiz.models import Questions from jobs.models import post_job @allowed_user(allowed_roles=['Admin, Students']) def homepage(request): return render(request, 'core/homepage.html') @allowed_user(allowed_roles=['Admin, Students']) def userProfileView(request, username): user= get_object_or_404(User, username=username) jobs = post_job.objects.all() categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores), 'jobs': jobs … -
Display video Django application
I'm trying to display a test video at my Django app, this is how the .html file looked like {% extends "blog/base.html" %} {% load static %} {% block content %} <video oncontextmenu="return false;" width='320' height= '240' autoplay controls controlsList="nodownload"> <source src="{% static 'videos/test.mp4' type='video/mp4' %}"> Your browser does not support the video tag. </video> {% endblock content %} after setting the settings.py for defining the static root STATIC_URL = '/static/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' also the URL patterns were adjusted: if settings.DEBUG: # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now the problem is that I can display the video only using local host, and I can't display it in production using a public IP or vistual one, where I can see a video fram that can not be displayed! I think something is missing in the settings.py for defining the URL pattern being accessed publicly during calling from a foreign router. but I can't figure it out! I need help in amending the code! thanks a lot! -
Exception Value: local variable 'other_user' referenced before assignment
So, this is probably just something simple I'm doing wrong here. But basically, I am attempting to simply pass in the pk of the other_user. I tested that the query works correctly, and am indeed printing the other user. Just don't know where to place it correctly in my code so I can pass it to the render part. local variable 'other_user' referenced before assignment def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST, other_user.id) if form.is_valid(): form.save() return redirect('dating_app:messages', other_user.id) else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() print(conversation) other_user = conversation.members.filter(id=profile_id).get() print(other_user) form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form } return render(request, 'dating_app/message.html', context) -
'The requested URL / was not found on this server' Django Deployment issue
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> This is my urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage), path('rh/', views.rh, name="rh"), path('gvt/', views.gvt, name="gvt"), path('fth/', views.fth, name="fth"), path('pages/', include('pages.urls')), ] This is my wsgi.py from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excelsite.settings') application = get_wsgi_application() sys.path.append('/home/alexholst/excelsite') -
Django Rest API Djoser Refresh and Access Token Problem
I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint. I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows: { "mobile": "12345", "driving_id": "478161839", "full_name": "John Doe", } This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
What is similar to PrimeNG for Django?
I know that Django makes use of html templating system to make the UI development easy. But no one can start building a table ( like in https://primefaces.org/primeng/showcase/#/table) with html templating system from scratch right? (I assume that will be time taking and will require more resources) Is there a library that provides rich UI components like in PrimeNG for Django? -
Djnago, how to figure out in template a list value from my Manager?
I have the following models.py: class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantity')*F('price'), ) def get_monthly_totals(self): products = dict((p.id, p) for p in Products.objects.all()) return list( (product, datetime.date(year, month, 1), totale) for product_id, year, month, totale in ( self.values_list('product__nome', 'date__year', 'date__month') .annotate(totale=Sum(F('quantity') * F('price'))) .values_list('product__nome', 'date__year', 'date__month', 'totale') ) class Materiale(models.Model): product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity=models.DecimalField() price=models.DecimalField() date=models.DateField() obejcts=MaterialManager() Could I figure out in my template the .values_list('product__nome', 'date__year', 'date__month', 'totale'). I try with Materiale.objects.all() but does not work. -
if field.choices change in a model, what happens to older records that have selections that are no longer in the list?
Would the data for these records be deleted automatically or left as they were? I'm wondering whether to use a seperate model to list these or if this is even an issue.