Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku does not load static files, Django
The project deployed on Heroku does not load static files. Log: method=GET path="/static/vendor/bootstrap/js/bootstrap.bundle.min.js" status=404 My settings are (settings.py on github): MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ BASE_DIR / 'static' ] Static files are loaded if I modify STATIC_ROOT STATIC_ROOT = BASE_DIR / 'static' But then it fails on a local machine. I have followed both Heroku and WhiteNoise guidelines with little help. https://devcenter.heroku.com/articles/django-assets http://whitenoise.evans.io/en/stable/django.html How could I debug or investigate the issue? -
What technologies to use to create my website
I'm thinking to start a website where some specific people can upload and publish educative content for a specific community or for the public, I'm a python programmer with some front end web skills, Now for my website, I don't know exactly which back-end technology would be good, please when you tell me your suggestions give me the reason why, All my regards. -
Add quantity in ManyToMany fields in Djangp
I'm developing a CRM that controls and organizes sales in DJANGO. SO I have the class Sale (Venda) and the class Product. In the class Sale, I have the Many To Many fields referencing the Product class. My question is if is possible to add a field related to the quantity. I mean, a person can ask in a single sale to add multiple quantities of multiple products, right? Can I implement that in models.py? My codes are: Venda.models.py: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(null=True, decimal_places=2, max_digits=100) cost = models.DecimalField(null=True, decimal_places=2, max_digits=100) stock = models.IntegerField(null=True, blank=True) materials = models.ManyToManyField(to='producao.MateriaPrima') def __str__(self): return self.name class Sale(models.Model): client = models.ForeignKey(Cliente, null=True, on_delete=models.SET_NULL) product = models.ManyToManyField(Produto) plataform = models.CharField(choices=PLATAFORMAS, null=True, max_length=1000) status = models.CharField(choices=STATUS, null=True, max_length=1000) data_pedido = models.DateTimeField(auto_now_add=False, null=True, default=datetime.now) data_entrega= models.DateField(auto_now_add=False, blank=True, null=True) paid = models.BooleanField(default=False) payment = models.CharField(choices=PAGAMETOS, null=True, max_length=200) num_itens = models.IntegerField(null=True, blank=True) total_price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=100) profit = models.DecimalField(decimal_places=2, null=True, blank=True, max_digits=100) the last three items are calculated and filled automatically in signals.py But the way this is implemented, the user can only add a single unit of each product in a Sale object. I want to know if there is a way … -
how to check if a database field's value has been changed in django?
hi I am trying to code an ecommerce website with django , is there any way to check if a model's field's value has been changed? for example I like to send the customer a message after his/her order status has changed. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Order(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) status=models.CharField(max_length=50,default='pending') # other firlds ... @receiver(post_save, sender=Order) def send_sms_if_changed(sender, instance, **kwargs): #what should i write ? # if instance.status has changed : # send_sms(to=instance.owner.phone,message=f'your order status is {order.status}') -
Could I use one Django Modelform in 2 scenerios with different number of fields used?
I'm new to Django Formmodel and Class-Based View and so confused by those. Suppose I have a model Post with some fields such as owner, content, time_created... Could I create a formmodel from it and use it in two Class-Based Views with different numbers of fields used, like: One CreateView that uses only content field, other fields will be automatically added by code, or an UpdateView that uses the same field to allow users to edit their posts. One DetailView uses all fields to show info about posts when users want to see post details. Please guide me with this problem. Thanks all ^^ -
How to input a default value in {{ form.label }}
I am trying to develop my flask blog, and in register.html, I want to set a help register message. For example, when the user clicks on the username form, it can indicate "it must be 3-15 characters long"; or set a default value in the form, when the user clicks it, it would disappear. But I don't know how to achieve it in {{form.username.label}} here's my original code: <fieldset class="form-group"> <legend class="form-title" style="font-weight: 700;">Register</legend> <div class="form-group"> <p>{{ form.username.label }} {{ form.username }} {% for error in form.username.errors %} <span style="color: orange;">[{{ error }}]</span> {% endfor %}</p> </div> -
Create a Like Dislike System with Python Flask and MySQL [closed]
I am creating a website, where I want people to like or dislike the post, and when some other user, logs in, he must also be able to see the likes and dislikes, I created that with php before, but now I need to do it with Flask using Python, Please help me! Here's the php code: https://github.com/Saksham11986/Like_Dislike-System-with-Php Regards! Answers would be appreciated! Thanks in Advance Sorry for the bad explanation and English, I am new here, so please advice me, to improve the question -
User creation in Django after successful payment in Stripe
I want to give access to certain pages on the website only to registered users who have paid a membership fee through Stripe. I already have view that creates the User and decorators in front of the restricted views. How can the Member be created and the Stripe ids added to his profile only after Stripe has successfully accepted the payment and redirected him to the 'success' page? Views.py: # views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') group = Group.objects.get(name='Member') user.groups.add(group) Member.objects.create(user=user, name=username, first_name=first_name, last_name=last_name, email=email) messages.success(request, 'Account was created for ' + username) return redirect('login_page') content = {'form':form } return render(request,'spacs_money_app/register.html', content) #views.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_TEST_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_MONTHLY_PRICE_ID, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) Models.py: # models.py class Member(models.Model): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) stripe_id = models.CharField(max_length=200, null=True) first_name = models.CharField(max_length=200, null=True) … -
Django form data is not submitting to the database
I have created a subscription form which is to display on the sidebar my website. It was working fine initially but after making a test deployment, I realised the form no more submits to the database. I am using wagtail admin and MailChimp marketing automation platform when submitting data. This is the form.py from django import forms from .models import Subscribers class EmailSignupForm(forms.ModelForm): name = forms.EmailField(widget=forms.TextInput(attrs={ "type": "name", "name": "name", "id": "subscribe-name", "placeholder": "Your name here", }), label="") email = forms.EmailField(widget=forms.TextInput(attrs={ "type": "email", "name": "email", "id": "subscribe-email", "placeholder": "Type your email address", }), label="") class Meta: model = Subscribers fields = ('name','email', ) This is the template which is a section of the whole page {% block subscribe %} {%load static%} <aside class="section popular"> <h3 class="section-title">Subscribe</h3> <div class="content"> <div class="section-image"> <img class="header-image" src="{% static '/images/image.jpg' %}" alt="image"> </div> <p class="mess-head"><strong>Subscribe to our newsletter to receive news updates by email.<strong></p> <form action="{% url 'subscribe' %}" method="POST" id="subscribe-form"> {% csrf_token %} <div class="form-group"> {{ form }} <button type="submit" class="btn btn-success" id="submit-email"> Subscribe </button> </div> </form> <p>{% if messages %} <ul class="messages mess-text"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }} mess-text alert-warning" {% endif %}> {{ … -
Custom User subclassing AbstractUser giving NoReverseMatch when called in listview template
I am in need of some help. The best way I can describe my problem as how I have done in the title and I get a noreverse match error. Can anyone shed some light as to why I am getting this problem. Here is my code. # model code class CustomUser(AbstractUser): position = models.CharField(max_length=30, null=True ) email = models.EmailField(null=True, blank=False, unique=True ) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=True, unique=True) date_created = models.DateTimeField(auto_now_add=True, editable=True) def __str__(self): return self.username # USERNAME_FIELD = 'email' def get_absolute_url(self): return reverse("customuser_detail", args=[str(self.id)]) class Meta: ordering = ["username"] # view code class CustomUserListView(ListView): model = CustomUser context_object_name = 'object_customuser_list' template_name = 'accounts/user_profiles/customuser_list.html' paginate_by = 25 fields = '__all__' ordering = ('first_name','last_name') class CustomUserDetailView(DetailView): model = CustomUser context_object_name = 'object_customuser_detail' template_name = 'accounts/userprofiles/customuser_detail.html' #urls path('new_user/', views.CustomUserCreateView.as_view() , name='customuser_create'), path('profiles/list', views.CustomUserListView.as_view() , name='customuser_list'), path('profiles/details', views.CustomUserDetailView.as_view() , name='customuser_detail'), # template: <tbody> {% for obj in object_customuser_list %} <tr> <td style="text-align:center"> <a href="{% url 'customuser_detail' obj.id %}" class="search-link">{{ obj.username }}</a> </td> <td> <a>{{ obj.first_name }}</a> </td> <td> <a>{{ obj.last_name }}</a> </td> <td> <a>{{ obj.email }}</a> </td> <td> <a>{{ obj.position }}</a> </td> <td> <a>{{ … -
Problem in creation of Many to Many links
My goal is to create links between artists who make a song together (Eminem link with 50 cents). Requests are made & no error & no warings, but: When artist_a is linked with artist_b, artist_a is linked with all artists linked in artist_b. For example: A -> B B -> C So : A -> B, C command def get_artists(self, artist=None): """ Initialize artists :return: """ payload = { "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer " + SPOTIFY_KEY, } if artist is None: artist = Artist(name="Youv Dee", id_spotify="5P3mgWx3KvnURMhlVm5pMS") if len(Artist.objects.filter(id_spotify="5P3mgWx3KvnURMhlVm5pMS")) == 0: artist.save() album = requests.get("https://api.spotify.com/v1/artists/5P3mgWx3KvnURMhlVm5pMS/albums", headers=payload) else: album = requests.get("https://api.spotify.com/v1/artists/{artist_id}/albums".format(artist_id=artist.id_spotify), headers=payload) for item in album.json()['items']: album_id_spotify = item['uri'].split(':')[2] album_songs = requests.get("https://api.spotify.com/v1/albums/{album_id}".format(album_id=album_id_spotify), headers=payload).json() for track in (album_songs['tracks']['items']): if len(track['artists']) > 1: artists = [] for artist_on_song in track['artists']: # Populate artists array with artist instance artist_instance, created = Artist.objects.get_or_create(name=artist_on_song['name'], id_spotify=artist_on_song['id']) artists.append(artist_instance) if created: a.append(artist_instance) # link artists for artist_a in artists: for artist_b in artists: print(artist_a) print(artist_b) print() if artist_a.id_spotify != artist_b.id_spotify and \ len(artist_a.artists_linked.filter(id_spotify=artist_b.id_spotify)) == 0: #link NOT already exists artist_a.artists_linked.add(artist_b) model class Artist(models.Model): name = models.CharField( max_length=200, verbose_name="Artist's name" ) id_spotify = models.CharField( max_length=200, verbose_name="spotify id", default="" ) artists_linked = models.field( to='Artist', verbose_name="Linked artists" ) def __str__(self): return … -
"Run manage.py task" and .env file environment variables
In PyCharm one can set environment variables in the "Run/Debug" configurations with the EnvFile plugin (https://plugins.jetbrains.com/plugin/7861-envfile). That works for the configuration e.g. the default Django development server. However, it doesn't work with the Tools->Run manage.py Task menu. I know that I can set environment variables in the PyCharm Django settings (Preferences -> Language and Frameworks -> Django) but there I can't use an env file, but only specify each environment variable manually. Is there a convenient way how my "Run manage.py Task" always have the same settings as in the Run configuration? I am using PyCharm 2020.3.3 (Professional Edition), Build #PY-203.7148.72. -
django-allauth: do not let user sign in before email confirmation
After signing up using the django-allauth behind-the-hood, the user gets both logged in and sent a verification email. The thing is, I want to let a user sign-in only after he has verified his email address. How can I do it? I'm worried some user could spam my website with fake accounts. Thanks in advance. -
django-mptt count items in add_related_count?
How to add filter(is_pluplic=True) to Question? Category.objects.add_related_count( Category.objects.filter(is_public=True), Question, 'category', 'question_counts', cumulative=True) -
django.core.serializers.base.DeserializationError: Problem installing fixture
Trying to preload fixtures but when I run python manage.py loaddata fixtures/permissions.json, I get: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 575, in get_field return self.fields_map[field_name] KeyError: 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "/usr/local/lib/python3.7/site-packages/django/core/serializers/python.py", line 117, in Deserializer field = Model._meta.get_field(field_name) File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 577, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Permission has no field named 'name' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 172, in load_label for obj in objects: File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/app/fixtures/permissions.json': my /fixtures/permissions.json: [ { "model": "users.permission", "pk": 1, "fields": { "name": "view_users" } }, … -
LEFT JOIN LATERAL Joining subquery in Django ORM
SELECT * FROM "table1" as "dd" LEFT JOIN LATERAL ( SELECT SUM(U02."quantity") AS "total", U02.drug_id FROM "order_items" U02 WHERE ( U02."branch_id" = 2 AND U02."type" = 'created' AND "dd".id = U02.drug_id AND U02."created_at" >= '2021-01-27T16:13:19.381564+00:00' :: timestamptz ) GROUP BY U02."drug_id" LIMIT 1 ) AS "last_month_ordered_quantity" on ("dd"."id" = "last_month_ordered_quantity"."drug_id") LEFT OUTER JOIN "units" ON ("dd"."unit_id" = "units"."id") WHERE "dd".id = 64 -
React Login Status
I made a login and register page with React (I've used Django for backend). I can register and login users. I want to show a text just for logged in users. But i don't know how to check login status for a user. I'm waiting your answers. Thanks. auth.js import React, {useState, useEffect, Component} from 'react'; import { API } from './api-service'; import './giris/css/util.css'; import './giris/css/main.css'; import './giris/css/bootstrap.min.css'; import './giris/vendor/bootstrap/css/bootstrap.min.css'; import './giris/fonts/font-awesome-4.7.0/css/font-awesome.min.css'; import './giris/fonts/Linearicons-Free-v1.0.0/icon-font.min.css'; import './giris/vendor/animate/animate.css'; import './giris/vendor/css-hamburgers/hamburgers.min.css'; import './giris/vendor/select2/select2.min.css'; import { useCookies } from 'react-cookie'; function Auth(){ const [ username, setUsername ] = useState(''); const [ password, setPassword ] = useState(''); const [ mail, setMail ] = useState(''); const [ confirm_password, setConfirmPass ] = useState(''); const [ isLoginView, setIsLoginView ] = useState(true); const [ userError, setUserError] = useState(false) const [ token, setToken] = useCookies(['mr-token']); const [regError, setRegError] = useState(false) const [samePass, setSamePass] = useState(false) const [mailCheck, setMailCheck] = useState(false) const [kayitbasari, setKayitBasari] = useState(false) useEffect ( () => { if (token['mr-token']) console.log(token['mr-token']) if(token['mr-token']) window.location.href = '/'; }, [token]) const loginClicked = () => { API.loginUser({username, password}) .then( resp => checkToken(resp)) } const checkMail = (resp) => { let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if ( re.test(mail) ) { checkSamePass() } else … -
How To Move "Add Another" Link Button Inline To The Top Django Admin
I am working on a Django project and I would want to move the 'Add Another' link to the top of the inlines. The long list of inline records make it hard to add another field, that's why I want to move the bottom to the top. [Photo][1] -
How can change the color of like button and increase by one when hit the like button in Django using ajax
I found difficult to change the color of the like button when the button hit and increase by +1 (in likes) in Django using ajax my html template <form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form"> {% csrf_token %} <input type="hidden" class="likin" name="next" value="{{ request.path }}"> <button class="remove-default-btn" type="submit" id="openPopup" class="like-btn{{ request.path }}" style="border: none; "> <i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i> Like </button> JavaScript $("#my-like-form").submit(function(e){ e.preventDefault(); // Prevent form submission let form = $(this); let url = form.attr("action"); let res const likes = $(`.like-btn{{ request.path }}`).text(); const trimCount = parseInt(likes) $.ajax({ type: "POST", url: url, data: form.serialize(), dataType: "json", success: function(response) { selector = document.getElementsByName(response.next); if(response.liked==true){ $(selector).css("color","blue"); res = trimCount - 1 } else if(response.liked==false){ $(selector).css("color","black"); res = trimCount + 1 } } }) }) -
Django Static Files Won't Load On Firefox
For some reason the CSS files for my Django webpages won't load in. It originally was loading fine, and changes to the CSS would update accordingly, however often it stops updating the CSS as it is changed, and instead continues loading the previous version of the CSS file. Quitting and reopening the server does not work. The CSS loads in fine on Chrome and Safari, so it can't be a problem with the static path I don't think. Does anyone have any clue as to why this occurs and any way to fix it? Thank you :) -
How can I display items from a dictionary in a html webpage from a Django ListView template?
I'm trying to display the results of a query in a MongoDB database but I can't display the results passed by views.py. Here is the page where I show them by iterating with a for loop over products: {% extends "portfolio/base.html" %} {% load static %} {% block content %} <table class="table table-striped" align='center'> <thead> <tr> <th align="center">Brand</th> <th align="center">Perfume Name</th> <th align="center">Gender</th> <th align="center">Theme</th> <th align="center">Notes</th> </tr> </thead> <tbody> {% for element in products %} <tr> <td>{{ element.q0.Results.0.Brand.Name }}</td> <td>{{ element.q0.Results.0.Name }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} And this is views.py where I request and send them. import pymongo import todo.config as config from django.views.generic import TemplateView, ListView from django.db.models import Q username = config.username password = config.password client = pymongo.MongoClient( f"mongodb+srv://{username}:{password}@cluster0.n2hnd.mongodb.net/ifresearch?retryWrites=true&w=majority") collection = client.test.sephora_backup3 ... class SearchResultsView(ListView): model = Perfume template_name = 'todo/search_similar_results.html' def get_queryset(self): # new query = self.request.GET.get('q') print(query) products = list(collection.find({"q0.Results.0.Name": {"$regex": query, "$options": "i"}})) print("products: ", products) return products There are results in the products but nothing is shown in the html -
Django unique_together constraint for date validation
I have following model: class Completion(models.Model): date_completed = models.DateTimeField(auto_now=False, auto_now_add=False) related_task = models.ForeignKey(Task, on_delete=models.CASCADE) I need to check that each Completion have unique date (not datetime - only the date) for each Task (which is Completion's related field). In other words, I need something like this: class Meta: unique_together = [ 'date_completed__date', 'related_task' ] I know it does not work this way (and should not), so I would like to ask, how can I achieve the desired result (if it is possible altogether). -
Integrity error while adding item to database
So I am trying to add an item to my database inside my django app. However, I keep getting an integrity error while trying to do so. The error looks like this: IntegrityError at /newcategory NOT NULL constraint failed: buyit_category.tag Request Method: POST Request URL: http://127.0.0.1:8000/newcategory Django Version: 3.1.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: buyit_category.tag I had the field "tag" for my category but did remove it, since I didn't really need it. I also made migrations and migrated the altered model, so I am quite confused on why it keeps giving me that error. Here is my view for that part: @require_POST def newCategory(request): form = CategoryForm(request.POST) if form.is_valid(): new_category = Category(name=request.POST['name']) new_category.save() return redirect('items') this is the template which is getting rendered: {% extends 'buyit/base.html' %} {% block body %} <h4>NEUE KATEGORIE HINZUFÜGEN</h4> <form action="{% url 'newCategory' %}" method="POST" role="form"> {% csrf_token %} <div class="form-group"> <div class="input-group"> {{ form.name }} <span class="input-group-btn"> <button type="submit" class="btn btn-success" id="add-btn">Hinzufügen</button> </span> </div> </div> </form> {% endblock %} This is the model I am using: from django.db import models class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name I also tried to add the tag field back and … -
I want to allow only the user who created the task can edit
I want to allow only the user who has created the task can only edit or delete the task not others . but others can see there task IM USING GOOGLE AUTH FOR USERS MODELS.PY from django.contrib.auth.models import User class Projects(models.Model): project_name = models.CharField(max_length=20) description = models.TextField() url = models.CharField(max_length=60,null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.project_name} ' VIEWS.PY not added home,add,update,delete view ' def Logout(request): logout(request) return redirect('home') ' -
API call via url in django
I'm attempting to make an api call in django to a url. #api call url = "https://api.lemlist.com/api/team" querystring = {"user":apikey} response = requests.request("GET", url, params=querystring) Lemlist shows that the following call can be made as follows, but its in a different language: curl https://api.lemlist.com/api/team \ --user ":YourApiKey" https://developer.lemlist.com/#authentication With the python call noted above, I'm getting a 400 error. Thanks!