Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the number of comments from a specific post in django
I have a little problem with a query. I work on a blog website with django. For posts I have the first page where i display all the posts as a list, with their details (title, date posted etc.) and I want to display the number of comments for each post along with title, date posted and tags. I'm not sure how to make that, I need to implement something on the model classes or in view function that renders the page ? Here are the model classes. class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=500) content = models.TextField() tags = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_text = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Comment ' + str(self.id) and the view function def blog(request): context = { 'posts': Post.objects.all(), 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) -
Django REST API - SerializerMethodField() causes too many queries
I am a bit lost here. I have created a nested relationship that goes as follows: Text -> multiple Sentences-> multiple Words models.py: class Text(models.Model): title = models.CharField(max_length=250) class Sentence(models.Model): text = models.ForeignKey(Text, related_name='sentences', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() class Meta: unique_together = ['text', 'order'] ordering = ['order'] class Word(models.Model): sentence = models.ForeignKey(Sentence, related_name='words', on_delete=models.CASCADE, blank=True, null=True) order = models.IntegerField() word = models.CharField(max_length=50) vocabulary = models.ForeignKey(Vocabulary, on_delete=models.SET_NULL, blank=True, null=True) class Meta: unique_together = ['sentence', 'order'] ordering = ['order'] class Vocabulary(models.Model): vocabulary = models.CharField(max_length=50) class KnownWords(models.Model): vocabulary = models.ForeignKey(Vocabulary, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) The idea is that a text is split into individual words. Each word is associated with a vocabulary and users can know the vocabulary. serializer.py: class WordSerializer(serializers.ModelSerializer): is_known = serializers.SerializerMethodField() class Meta: model = Word fields = ['id', 'order', 'word', 'vocabulary', 'is_known '] def get_is_known(self, obj): if KnownWords.objects.filter(vocabulary=obj.vocabulary).exists(): obj.is_known = True else: obj.is_known = False return obj.is_known class SentenceSerializer(serializers.ModelSerializer): words = WordSerializer(many=True) class Meta: model = Sentence fields = ['id', 'order', 'words'] class TextSerializer(serializers.ModelSerializer): sentences = SentenceSerializer(many=True) vocabulary = serializers.SerializerMethodField() class Meta: model = Text fields = ['id', 'title', 'sentences'] views.py: class TextDetail(generics.RetrieveAPIView): queryset = Text.objects.prefetch_related('sentences', 'sentences__words') serializer_class = TextSerializer The reason why ìs_known is a … -
Unable to create process using
I'm trying to run my django code but I'm presented with this error: Unable to create process using 'C:\Users\My_username\AppData\Local\Programs\Python\Python39\python.exe manage.py runserver', How do I deal with this? -
Is it possible to call a function of __init__.py from views.py in django?
init.py : def abc(): some code views.py: from . import __init__ __init__.abc() This gives error AttributeError: 'method-wrapper' object has no attribute 'abc' Is it possible to call the abc() function from views.py ? -
django password reset does not work on server but works on local machine
I am using gmail password manager to generate password. When I try to send email for password reset on sever I get 500 Error. This same format works when I try to send password reset email locally. These are my settings in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config['EMAIL_USER'] EMAIL_HOST_PASSWORD = config['EMAIL_PASS'] DEFAULT_FROM_EMAIL = config['EMAIL_USER'] I have even tried to hard code email and password, but that still does not work. I am using apache2 and here is my configurations: src => all the project files, recipe_app => project settings src |__recipe_app |__settings.py |__wsgi.py Alias /static /home/<user>/src/static <Directory /home/<user>/src/static> Require all granted </Directory> Alias /media /home/<user>/src/media <Directory /home/<user>/src/media> Require all granted </Directory> <Directory /home/<user>/src/recipe_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/<user>/src/recipe_app/wsgi.py WSGIDaemonProcess recipe_app python-path=/home/<user>/src python-home=/home/<user>/src/venv WSGIProcessGroup recipe_app -
Getting an Not Found: /blogs/like when adding Ajax to like button
I am trying to make the like button in the post_detail.html page clicked without refreshing the page so, I included the like section in a separate HTML called like-section.html. The problem is now I am getting a Not Found: /blogs/like when I click on the like button and it doesn't change anything when I click it except in the terminal I see this error. Here is the model.py class Post(models.Model): ------------------------------ liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') Here is the views.py def like_post(request): user = request.user post_obj = None if request.method == 'POST': post_id = request.POST.get('post_id') try: post_obj = Post.objects.get(id=post_id) except Post.DoesNotExist: return JsonResponse({'detail': 'Not found'}, status=404) else: if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post_id': post_id, } if request.is_ajax: html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) elif request.method == 'GET': post_id = request.GET.get('post_id') try: post_obj = Post.objects.get(id=post_id) except Post.DoesNotExist: return JsonResponse({'detail': 'Not found'}, status=404) Here is the like-section.html <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% if user not in post.liked.all %} <a id="like" class="bwhite sm-button" style="color: … -
Having trouble setting the DIRS url in Django TEMPLATES
have created a folder templates in my project's main folder and am trying to set a url for django to look for templates in and I am getting the following error: 'DIRS': [BASE_DIR / 'templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' In my settings.py file I have inserted the following code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The version of django is 3.1.3 -
SMTPRefused error while trying to send forgot-password emails using Sendinblue SMTP
Im trying to build a blog website using django and configure my email host using sendinblue, but I'm getting an error saying (530, b'Error: authentication Required', 'webmaster@localhost') Settings.py #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.sendinblue.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '########@gmail.com' EMAIL_HOST_PASS = os.environ.get('sendinblue_smtp_pass') Traceback Environment: Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 3.1.2 Python Version: 3.8.6 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\myenv\django\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\myenv\django\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\myenv\django\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\contrib\auth\views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\myenv\django\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\myenv\django\lib\site-packages\django\contrib\auth\views.py", line 235, in form_valid form.save(**opts) File "C:\myenv\django\lib\site-packages\django\contrib\auth\forms.py", line 323, in save self.send_mail( File "C:\myenv\django\lib\site-packages\django\contrib\auth\forms.py", line 273, in send_mail email_message.send() File "C:\myenv\django\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\myenv\django\lib\site-packages\django\core\mail\backends\smtp.py", line 109, in send_messages sent … -
first item adding properly but 2nd item is not adding
I am making a commerce website using django. I used session to fetch all the request in my project, but I am facing an issue. The problem is when I add a product to my cart it added successfully but whenever I try to another in the same time it shows 0 product in cart. I can't even add the amount but when I remove the first product the quantity automatically added to the second product. Really confusing, and for that reason I am providing screenshots. Screenshot Here is my Views.py: class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) def post(self, request): product = request.POST.get('product') print(product) cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart … -
DJANGO - How to show "Nothing Found for your seach" If no data found
I would like to know if there is a way to show a div, or at least "Nothing found" in django when there is no match for the user search. views.py class TaskSearchView(LoginRequiredMixin, ListView): template_name = 'task_app/task_search.html' model = Task def get_queryset(self): query = self.request.GET.get('q') usr = self.request.user if query: object_list = self.model.objects.filter(Q(title__icontains=query) & Q(is_public = True) | Q(title__icontains=query) & Q(author = usr) | Q(title__icontains=query) & Q(responsable = usr)) else: object_list = self.model.objects.none() return object_list task_search.html <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Seach Results for: {{ request.GET.q }}</h6> </div> .... {% for query in object_list %} </thead> <tbody> <tr> {% if query.importance == "H" %} <th scope="row" data-toggle="tooltip" data-placement="top" title="HIGH"><i style="color: red" class="fas fa-bookmark"></i></th> {% endif %} {% if query.importance == "M" %} <th scope="row" data-toggle="tooltip" data-placement="top" title="Medium"><i style="color: orange" class="fas fa-bookmark"></i></th> {% endif %} ..... </tr> {% endfor %} If the query is empty or there is no result I get this: but I would like to show a new form, or a message "nothing found..", is that possible? I tried with: {% if object_list != None %} show results {%else%} show not found, form, div... {% endif %} But it didn't work Any advice/answer … -
Where to Perform Additional Operations When Using Django Rest Framework
I have a CustomUser model and am using Django Rest Framework. I have several needs before/after saving a user object. For example: Adding the user's email, first/last name to a mailchimp list using mail chimp's API. Hashing a user's password before saving. I successfully do this in the UserSerializer class thus: class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' def create(self, validated_data): groups = validated_data.pop('groups', None) password = validated_data.pop('password', None) user_permissions = validated_data.pop('user_permissions') u = CustomUser.objects.create( password=make_password(password), **validated_data) u.groups.set(groups) u.user_permissions.set(user_permissions) return u However, let's say I want to also create a user in the admin tool and not repeat this logic? Doesn't it make more sense to add this logic by overriding the CustomUser's save method, or is that problematic? What's the best solution for this use-case? -
What permissions should be given to socket files or its parent folder?
What permission should be given to a .sock file and the folder containing it ? Is permission 777 mandatory for it to work ? If not, is it still risk free to do so ? If not, what should be the ideal permission [standard practice / best practice] ? BONUS --> Any other good practices associated with socket files [e.g never keep socket file in same folder as app] POSSIBLY REQUIRED INFO: Current Permissions: drwxrwxrwx 2 root root 4096 Nov 15 14:44 folder-containing-socket-files As you can see current permissions given are drwxrwxrwx or 777. Does having permissions set to 777 have any security implications here is my primary concern. Assume Django application - gunicorn - nginx Nginx is serving to a gunicorn socket in my case. My system has the following - USERS --> root , dev1 , dev2 GROUPS --> root , www-root , developers It has folder structure as follows: all_projects ├── all_apps ├── folder-containing-socket-files ├── django_proj_1 └── django_proj_2 {django_proj_1 , django_proj_2 are folders which contain the manage.py file} -
Staging and Production Environment on Digitalocean
I was wondering what the best practise is of having a staging and a production environment on digitalocean. Goal is to test the website with the same environment (with same libs, nginx configs etc.) as in the production environment, before finally taking the project to production. One solution for me would be to create a copy of the existing droplet (shut down of current droplet, take a snapshot and then copy the image-snapshot to new droplet) and then using this staging environment for testing. My questions are: Is this considered a good practise? Are there any alternatives and tools that could make it easier? Are two GitHub instances necessary? What else should I consider, when having two droplets with two IP addresses (performance, costs, safety etc.)? Also, FYI I am using Django as my web framework and Ubuntu 18.04.3 (LTS) x64 as my server. What is more, a local environment exist too. Thank you. -
Accessing nested values in Django
I am trying to access values in my Django template (using Jinja2) from an API and am struggling quite a bit. I'm new to Python/Django/programming and am having a hard time navigating through this complex nested structure of lists/dicts. Here is a snippet of the API response for a single flight (the response contains a total of 250 flights): { "meta": { "count": 2 }, "data": [ { "type": "flight-offer", "id": "1", "source": "GDS", "instantTicketingRequired": false, "nonHomogeneous": false, "oneWay": false, "lastTicketingDate": "2020-11-20", "numberOfBookableSeats": 2, "itineraries": [ { "duration": "PT22H40M", "segments": [ { "departure": { "iataCode": "GIG", "terminal": "2", "at": "2020-12-01T16:30:00" }, "arrival": { "iataCode": "CDG", "terminal": "2E", "at": "2020-12-02T07:45:00" }, "carrierCode": "AF", "number": "443", "aircraft": { "code": "77W" }, "operating": { "carrierCode": "AF" }, "duration": "PT11H15M", "id": "3", "numberOfStops": 0, "blacklistedInEU": false }, { "departure": {... For each flight I would like to extract the following key/values: id duration iataCode Below is what I have tried so far... id (successful) {% for flight in data %} {{ flight.id }} {% endfor %} iataCode (unsuccessful) {% for flight in data %} {% for itinerary in itineraries %} {% for segment in segments %} {{ departure.iataCode }} {% endfor %} {% endfor … -
How to get data from nested field in Django Raw Query?
I have problem to fetch the foreign key data from a field with my raw queryset in django This is my Raw Queryset: query = "SELECT * FROM assets WHERE MBRContains(ST_GeomFromText('Polygon((%s))'), point(lat, lon));" % polygon asset = Asset.objects.raw(query) and the result is like this: { owner: "c9e35046-ec42-4264-a72c-b4258a0be586" point_of_interests: ["acc0df64-f9c4-41b5-b54e-236bbfc9d446", "66cb6541-6cc8-40c0-b91d-a8f410626cb1",…] 0: "acc0df64-f9c4-41b5-b54e-236bbfc9d446" 1: "66cb6541-6cc8-40c0-b91d-a8f410626cb1" } I want to get the point_of_interest data such name and etc, not just the id of the point_of_interest. How can I achieve that ? -
How to display image in django using HttpResponse
I am trying to display the image of python script output using below lines but instead of displaying in browser, code downloading the file instead of displaying this is the function i have created in views.py: def adc(request): file = "C:\Users\TheBoss\Downloads\New_test.xlsx" df = pd.read_excel(file, sheet_name='Graph') plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding') #plt.plot(df['Date'], df['30th Apr'], 'b', label = '30-Apr') plt.xticks(rotation=45) plt.tick_params(axis='x', which='major', labelsize=6) # naming the y axis plt.ylabel('Condition Count') # giving a title to my graph plt.title('Condition') # function to show the plot plt.legend() #plt.show() plt.savefig('C:\\Users\\TheBoss\\Downloads\\test.png') image_data = open("C:\\Users\\TheBoss\\Downloads\\test.png", "rb").read() return HttpResponse(image_data, content_type="test/png") -
Safari only CORS origin django issue - Origin is not allowed by Access-Control-Allow-Origin - django-cors-headers
[Error] Origin https://www.rrrroll.com is not allowed by Access-Control-Allow-Origin. [Error] XMLHttpRequest cannot load https://www.backend.rrrroll.com/upload/ due to access control checks. [Error] Failed to load resource: Origin https://www.rrrroll.com is not allowed by Access-Control-Allow-Origin. (upload, line 0) Having CORS issues with Safari only - Firefox, Chrome OK. Works in development for Safari but not production. Any help? Only difference is the backend is served on a subdomain in prod rather than just a different localhost port in dev. Django as backend for Next.js frontend, the GraphQL POST endpoint works fine on Safari, but the POST /upload endpoint gives the errors above. Using the django-cors-headers package and the CORS_ALLOWED_ORIGINS is correctly set. I previously did have a similar error earlier with another project and Safari this year and setting the CORS_ALLOW_ALL_ORIGINS and explicitly stating the default allowed headers worked. Not working in this case. Worth noting that a preflight OPTIONS request is run with 200 response when I press the upload the button I believe Nov 15 00:32:19 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[16665]: - - [15/Nov/2020:00:32:19 +0000] "OPTIONS /upload/ HTTP/1.0" 200 0 "https://rrrroll.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15" See the massive difference in requests on Safari vs Chrome, for some … -
Django - Enter a list of values - ForeignKey
For a M2O relation what field should I be using in forms? models.py class Studio(models.Model): name = models.SlugField(max_length=100) rating = models.CharField(max_length=10, default=None) def __str__(self): return self.name class AnimeDetail(models.Model): title_japanese = models.CharField(max_length=250) studio = models.ForeignKey(Studio, on_delete=models.CASCADE, default=None) ... forms.py from .models import AnimeDetail class AnimeDetailForm(forms.ModelForm): class Meta: model = AnimeDetail fields = ['icon', 'image', 'title_japanese', 'title_english', 'studio', 'genre', 'total_episodes', 'posted_episodes', 'season', 'date_started', 'date_finished', 'status', 'type_anime', 'age', 'source'] widgets = { 'title_japanese': forms.TextInput(attrs={'class': 'form-control'}), 'studio':forms.Select(attrs={'class': 'form-control'}), ... } 'studio':forms.Select(attrs={'class': 'form-control'}) -> Select doesnt work properly in this situiation but in other project worked without problems. Error: What is wrong? -
psycopg2.OperationalError: could not translate host name 'db' (While name 'db' is pingable in container)
There's a lot of dated information out there on similar issues, which I all went through. I'm running docker-compose file version 3.8. My issue is that: psycopg2 or Django can not resolve my database's container name. However, I can after a docker-compose up: gerard@solace ~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 21bcbcc35083 project_web "/app/entrypoint.sh …" 6 seconds ago Up 6 seconds 0.0.0.0:8006->8000/tcp project_web_1 a92e3e98477f postgres:12.0-alpine "docker-entrypoint.s…" 7 seconds ago Up 6 seconds 0.0.0.0:5432->5432/tcp project_db_1 gerard@solace ~$ docker exec -it project_web_1 ping -c 2 db PING db (172.25.0.2): 56 data bytes 64 bytes from 172.25.0.2: seq=0 ttl=64 time=0.078 ms 64 bytes from 172.25.0.2: seq=1 ttl=64 time=0.302 ms --- db ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.078/0.190/0.302 ms``` Also, my entrypoint.sh connects before continuing, and does continu so host and port seems accessible: Entrypoint snippet: while ! nc -z $SQL_HOST $SQL_PORT; do sleep 1 done What am I missing? -
Why django records test data into the database
I need to record some data within my test module to use it during my unit tests. After tests, I notice that these records remain within the database even if I get the following message after tests: Destroying test database for alias 'default'... I am currently using sqlite engine, would it explain such behavior? What would be the best practice here? -
dynamic appointment-pricing with django
I have an appointment app that allows clients to create doctor appointments. An admin would then award the appointment to available doctors. Part of the app reads as follows: class Appointment(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) appointment_day = models.DateField(validators=[present_or_future_date]) appointment_time = models.TimeField() service_needed = MultiSelectField(choices=MEDICAL_SERVICES_CHOICES, null=True, blank=True) With MEDICAL_SERVICES_CHOICES, clients can choose between: radiology appointments, dentist appointments, etc.. CHALLENGE: I need to be add a system-defined pricing attribute. The problem is that each appointment is created by the client & not the hospital. Furthermore, I need to establish different prices for each of the MEDICAL_SERVICES_CHOICES. QUESTIONS How do I automatically add a service-cost/price field on each appointment? Is there a better way to do this? (I've considered going with an e-commerce model except with services rather than products: Not sure if this would be better though!) -
How to add an object to a manytomany field in django
I have two models (Group and Contact). A Group can have many Contacts and a Contact can be in many Groups. I can create contacts but I can´t create groups right now. When I validate form.is_valid() it returns false and the error I'm getting is {'contacts': [ValidationError(['Enter a list of values.'])]} What am I missing here? models.py class Contact(models.Model): # Fields first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=32) contacts = models.ManyToManyField(Contact, related_name='groups') forms.py class CreateGroupForm(ModelForm): class Meta: model = Group fields = ["name", "contacts"] widgets = { 'name': TextInput(attrs={ "placeholder" : "", "class": "form-control" }), 'contacts': Select(attrs={ "placeholder" : "", "class": "form-control" }) } class CreateContactForm(ModelForm): class Meta: model = Contact fields = "__all__" widgets = { 'first_name': TextInput(attrs={ "placeholder" : "Nombre", "class": "form-control" }), 'last_name': TextInput(attrs={ "placeholder" : "Apellido", "class": "form-control" }) } views.py def create_group(request): if request.method == "POST": form = CreateGroupForm(request.POST) if form.is_valid(): group = form.save(commit=False) group.save() else: print(form.errors.as_data()) form = CreateGroupForm() return render(request, 'create-group.html', {'form':form}) elif request.method == "GET": form = CreateGroupForm(request.POST or None) return render(request, "create-group.html", { 'form' : form}) -
Django app on Heroku: migrations reset "relation already exists" error
I have a Django app running on Heroku. I deploy it via Github. I had to return to a previous commit and now I get the following error when I try to update Heroku: django.db.utils.ProgrammingError: relation "catalog_productosbase_image_gallery" already exists Tryied reseting migrations I tried to reset all migrations: Removed all migration files from app folder (except init) Removed the db.sqlite3 file Ran makemigrations Ran migrate --fake-initial Ran migrate Localy everything goes fine, then I did: git add -A git commit -m "name" git push origin master git push heroku master Here is where I get the relation already exists error. Procfile The Procfile inlcudes: release: python manage.py migrate Also tryied release: python manage.py migrate --fake-initialwith the same resut. Local showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions catalog [X] 0001_initial [X] 0002_auto_20201115_0948 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name covid (no migrations) fulberg (no migrations) sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique stockbucket [X] 0001_initial website (no migrations) Server showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null … -
product is not adding to cart properly
I am making a commerce website using django. I used session to fetch all the request in my project, but I am facing an issue. The problem is when I add a product to my cart it added successfully but whenever I try to another in the same time it shows 0 product in cart. I can't even add the amount but when I remove the first product the quantity automatically added to the second product. Really confusing, and for that reason I am providing screenshots. Here is my Views.py: class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None cats = Category.get_categories() brands = Brand.get_brands() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands } return render(request, 'Home/index.html', args) def post(self, request): product = request.POST.get('product') print(product) cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart print('cart', … -
JS always loads default view
I'm taking the CS50 course "Web Programming with Python and Javascript", so I'm pretty new to all this stuff, especially to Javascript. In one of the projects that need to be done, one have to implement a social network plattform where users can post some texts, like and dislike them and follow other users. There are 3 routes a user can go: All posts, Following and users posts. I've been trying to solve this with js front end. I've a function "view_posts", that takes an argument that specifies what posts should be fetched and rendered to the html page. Consider the folling part of my js file: document.addEventListener('DOMContentLoaded', function() { username = document.getElementById('username').innerText document.querySelector('#posts').addEventListener('click', () => view_posts('all')); document.querySelector('#username').addEventListener('click', () => view_posts(username)); document.querySelector('#following').addEventListener('click', () => view_posts('followers')); document.querySelector('#post-form').style.display = "none"; view_posts('all') }); Fetching the data is basically working, but js is always displaying the default view "view_posts('all')". Meaning, even if I click on the element whose id is #post, calling the very same function including the same argument, the function is called without displaying anything, before it calls the default view again (this time it will display the data correct). Here is the function: function view_posts(selector){ // document.querySelector('#post-form').style.display = "none"; if (selector …