Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i make more beautifull looks of form in forms.py in django?
default looks of form is so old, how can i make more nice looked form in tamplate from forms.py i made a form.py: class chg_pass(ModelForm): class Meta: model = Teacher_login_informa fields = ['Teacher_pass'] then views.py: from .forms import chg_pass def update_change_password(request): form = chg_pass() context = {'form':form} return render(request, 'change_password.html', context) in change_password.html tamplate: <form class="container pt-5" action="" method="POST">{% csrf_token %} {{form}} <button type="submit" class="btn btn-outline-success btn-sm">Submit</button> </form> -
Unable to open netsuite odbc on server
I have deployed the django project on ubuntu 20.04, nginx , gunicron. A part of the code is not able to run on the server it gives error ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/netsuite/odbcclient/lib64/ivoa27.so' : file not found (0) (SQLDriverConnect)") While the file is available :- xxxx@XXXXXX:/opt/netsuite/odbcclient/lib64$ ls ddtrc27.so ivmgan27.so ivmghu27.so ivoa27.so libicudata.so.42 libivoa27m.so libodbc.so openssl810.so ivldap27.so ivmgapi27.so ivoa27.ini libddicu27.so libicuuc.so.42 libodbcinst.so odbccurs.so It is working fine in the local server. And even in the Server terminal. But it gives error after starting nginx, gunicron service on the domain url. Everything else is working fine. Below output is from the server terminal ```usingh@NC-PH-0940-24:~$ python3 Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pyodbc >>> host = 'xxxxx' >>> uid = "xxxxx" >>> role_id = 'xxxxx' >>> pwd = "xxxxx" >>> account_id = "xxxxx" >>> pyodbc.connect('DRIVER={NetSuite};Host='+host+';Port=1708;Encrypted=1;Truststore=/opt/netsuite/odbcclient/cert/ca3.cer;SDSN=NetSuite.com;UID='+uid+';PWD='+pwd+';CustomProperties=AccountID='+account_id+';RoleID='+role_id+'') <pyodbc.Connection object at 0x7f920414e2d0> >>> ``` The same code has been used inside the django project and it gives error when checking on domain(URL) after starting the nginx, gunicorn services. I have tried checking the available drivers using ```odbcinst -j`` the driver is available. Given +777 permission to the directory … -
How do i use the same email for user and profile model
I have two forms, one for signup and another for creating users. The difference is that the one for signup uses email verification while the one for adding patient does not. I noticed that whenever ii add patient the email that is saved to only my profile model and not my user model. This problem allows another user to use the same email address. i notice the same problem If i add users through the authorization section in the admin panel, the first name, last name and email field only save to the user model and not the profile model. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from django.utils.text import slugify from django.contrib.auth.models import AbstractBaseUser get_user_model().objects.filter(is_superuser=True).update(first_name='Super', last_name='User') # superusers = User.objects.filter(is_superuser=True) class Profile(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) last_name = models.CharField(max_length=100, blank=True) first_name = models.CharField(max_length=100, blank=True) middle_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) next_of_kin = models.CharField(max_length=100, blank=True) dob = models.DateField(max_length=10, blank=True,null=True) state = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) address = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) phonenumber = models.CharField(max_length=20, null=True) appointment_with = models.ManyToManyField(User, related_name='appontment_with', … -
Pass variable through social authentication url
Before authenticating an user with Google in my page, I have an input that users can fill in with a special name, let's call this name variable nombrelink. When the user fills in the input and clicks submit, I send a fetch post request to the server to check wether that name is already taken or not. The problem is: when the person completes that input and THEN tries to sign up with google, I can't find a way to insert nombrelink into the database of the recently google created user. This is what happens on the server, to check wether the input name (nombrelink) is already taken or not. def landing(request): if request.method == "POST": content = json.loads(request.body) creator = Creador.objects.filter(url_name=content['nombrelink']).first() if not creator: content.update({"nadie": "nadie"}) return JsonResponse(content) else: return JsonResponse(content) return render(request, 'app1/landing.html') So in summary what the code should be doing is: The user fills in the input with a name that gets stored in nombrelink If nombrelink is not taken, then the user can register via google allauth nombrelink gets added to my google created user model I'm failing to implement point 3 -
Django writing custom upload handler to upload folder
Currently Django only supports uploading of files, but I would like to upload folders / subdirectories. I searched around and read that I would need to write a custom upload handler to support this. But I am not sure how to achieve this. I have read that Django doesn't support uploading of folder due to the way it takes the base name: def set_name(self, name): # Sanitize the file name so that it can't be dangerous. if name is not None: # Just use the basename of the file -- anything else is dangerous. name = os.path.basename(name) # File names longer than 255 characters can cause problems on older OSes. if len(name) > 255: name, ext = os.path.splitext(name) ext = ext[:255] name = name[:255 - len(ext)] + ext self._name = name -
combining multiple queryset based on conditions Django
I am using Djangofilterbackend and DjangoRestFramework. I am using url parameters to get the value and use it for my condition of which field should I filter. I have 30 possible parameters that a user can use. I am trying to combine filters based on if - else condition. This is the only solution I can think of. If you have any solution for this. please help me. U am just new to django This is my code. class NumberInFilter(filters.BaseInFilter, filters.NumberFilter): pass class ProductFilter(filters.FilterSet): manufacturer__in = NumberInFilter(field_name='manufacturer', lookup_expr='in') class Meta: model = Products fields = ['category', 'product_partnumber'] class ProductsView(viewsets.ModelViewSet): queryset = Products.objects.all() serializer_class = ProductsSerializers filter_backends = [filters.DjangoFilterBackend] filterset_class = ProductFilter def get_queryset(self): queryset = Products.objects.all() freq = self.request.query_params.get('specs', None) inloss = self.request.query_params.get('inloss', None) if freq is not None: queryset = queryset.filter(specifications__specification_id__exact=18, specifications__value__exact=freq) if inloss is not None: queryset = queryset.filter(specifications__specification_id__exact=28, specifications__value__exact=inloss) return queryset def create(self, request, *args, **kwargs): many = True if isinstance(request.data, list) else False serializer = ProductsSerializers(data=request.data, many=many) if serializer.is_valid(): serializer.save() product=serializer.data else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(product, status=status.HTTP_201_CREATED) my queryset are not combining. it just getting the last true on if statement. This is my model class Products(models.Model): product_partnumber = models.CharField(max_length=255) image_link = models.URLField(default=None, blank=True, null=True) … -
Related model cannot be resolved. Django, Djoser
I'm trying to extend the default Django User model and add custom fields in my authentication app, but when I try to run py manage.py migrate it prompt's an error saying it cannot find the 'authentication.User model. Btw I am using Djoser for my authentication. I get this error: >py manage.py migrate Operations to perform: Apply all migrations: admin, auth, authentication, authtoken, contenttypes, sessions Running migrations: Applying authentication.0001_initial...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 "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards schema_editor.create_model(model) File "D:\DJANGO-PROJECTS\chat_app\chat_app_env\lib\site-packages\django\db\backends\base\schema.py", line 322, in create_model sql, params = self.table_sql(model) File … -
Vue - turning off requests to /sockjs-node/info
I run Django and Vue together and the combination works fairly well. Django runs on http 8000 and webpack dev server chugs along on port 3000, JS or Vue changes get compiled automatically and I just have to reload the page (this is not an SPA app). Life is good. The only annoying bit is repeat requests like this: http://localhost:8000/sockjs-node/info?t=1607750560606 Now, Django doesn't find that resource so its log clutters up with 404. I actually coded a 410 instead, but, no Vue is just going to ping that 410 #urls.py url("^sockjs-node/info", views.nodeinfo), #views.py def nodeinfo(request): return HttpResponseGone() Now, I have tried to look for this. The answers on the Vue forum are multiple and most involve changing to vue.config.js, located next to package.json. After trying 2 or 3 of the suggestions, most of which don't seem to make much sense (a localhost question ends up with a "fix" consisting of a devserver entry pointing to 0.0.0.0 for example), none of them work. None of the threads I have seen seem to hold very authoritative answers. Or, more likely, I can't find the correct answer in all the noise that is being posted. I won't be running node in production, will … -
Why Is Django Not Serving My Static Folder In Development?
I am trying to serve some files from the static folder so a js script that runs in one of my templates can require it. Unfortunately, it seems to be picking which files to serve. (or something) It is not serving my js file, breaking my app. Another problem is that sometimes the favicon becomes missing before the first request is cached. I’ve noticed before in a deployed version of this app that I had to refresh the page after the first load. This is the output from the first request in the current development version: (python terminal output from the first request) ]09/Dec/2020 23:31:19] "GET /requestmap/ HTTP/1.1" 200 390 [09/Dec/2020 23:31:19] "GET /static/main.js HTTP/1.1" 404 1748 Not Found: /favicon.ico [09/Dec/2020 23:31:19] "GET /favicon.ico HTTP/1.1" 404 5727 (chrome conosole log from the first request): GET http://localhost:8000/static/main.js net::ERR_ABORTED 404 (Not Found) favicon.ico:1 GET http://localhost:8000/favicon.ico 404 (Not Found) ...and the output from the second request: (in the python console) [12/Dec/2020 04:05:53] "GET /requestmap/ HTTP/1.1" 200 390 [12/Dec/2020 04:05:54] "GET /static/main.js HTTP/1.1" 404 1761 (in the browser console) http://localhost:8000/static/main.js net::ERR_ABORTED 404 (Not Found) When I get the admin page all of the CSS and images seem to load fine, but any file that … -
Creating Proper Django Paths
Each group needs its own url in order to view, however, my understanding of constructing URL paths seems incomplete. What I currently have for each path containing "slug" does not work. I am attempting to make the final URL look along the lines of ".../groups/posts/in/group_name". urls.py app_name = 'groups' urlpatterns = [ path('', views.ListGroups.as_view(), name='all'), path('new/', views.CreateGroup.as_view(), name='create'), path('posts/in/<slug:groups>', views.SingleGroup.as_view(), name='single'), path('join/<slug>', views.JoinGroup.as_view(), name='join'), path('leave/<slug>', views.LeaveGroup.as_view(), name='join'), ] views.py from .models import Group, GroupMember # Create your views here. class CreateGroup(LoginRequiredMixin, generic.CreateView): fields = ['name', 'description'] model = Group class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug':self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group, slug=self.kwargs.get('slug')) try: GroupMember.objects.create(user=self.request.user, group=group) except IntegrityError: messages.warning(request, 'You are a already a member') else: messages.success(request, 'You are now a member') return super().get(request, *args, **kwargs) class LeaveGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug':self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): try: membership = GroupMember.objects.filter( user=self.request.user, group__slug=self.kwargs.get('slug') ).get() except GroupMember.DoesNotExist: messages.warning(request, 'You are not in this group') else: messages.success(request, 'You have successfully left this group') return super().get(request, *args, **kwargs) models.py User = get_user_model() register = template.Library() # Create your models here. class Group(models.Model): name = … -
Display particular data fields according to condition if there is data in the list in Django?
I am working on a project where the customer can order online for printing service on the product page I am providing all data about the product. And on the product page, I want to display the list of options if the data related to that product is available otherwise I want to hide that section if there is no data related to that product is available. *views.py def product(request, id): products = Product.objects.get(prod_ID=id) # initializing empty list sizeslist = [] AqutousCoatingProductlist = [] try: #trying to fetch data if it is available for that product sizesmap = SizeProductMapping.objects.filter(prod_id=id) sizeslist = [data.size_id.prod_size for data in sizesmap] except AttributeError as e: pass try: #trying to fetch data if it is available for that product AqutousCoatingProductmap = AqutousCoatingProductMapping.objects.filter(prod_id=id) AqutousCoatingProductlist = [data.aqutous_coating_id.prod_size for data in AqutousCoatingProductmap] except AttributeError as e: pass # sizeslist = SizeProductMapping.objects.filter(prod_id=id).values('size_id__prod_size') return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist, "AqutousCoatingProductlist": AqutousCoatingProductlist}) product.html <div class="col-8"> <div class="card mx-2 my-2 border border-secondary"> <div class="row my-2"> {% if sizeslist is not null %} <!--trying to display this section if the sizelist is not null--> <div class="col-4 ml-4 mt-2"> <h4>Sizes : </h4> </div> <div class="col-4 mr-4 mt-2"> {% for s in sizeslist %} <input … -
Changing "extra" value in modelformset_factory using django form
Inside my views.py I have got a line of code, that has an extra value, that tell us a number of image fields, that I am able to use. ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3) Is there a way to change that extra fixed value from the form view? So when I click button add more it would change the value to +1. -
Keep duplicates when merging query sets (Django)
queryset = Profile.objects.none() for num in temp1: queryset |= Profile.objects.filter(subjects_key__contains='-'+str(num)+'-').exclude(user=self.request.user) So currently this code queries every value in the given temp1 array. Essentially I want to build a dynamic or query functionality regardless of the length of this array. It works well, but the only problem is I want to preserve the duplicates as I will need to access the count of them later. Thank you! TLDR: How can I keep duplicates when merging a query set? -
solve data in django
Iam try to write a for with data:[{'type': 'vSmart', 'name': 'vSmart', 'image': 'images/vsmart.png', 'count': 1, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', 'count': 1}, {'status': 'new', 'name': 'Discovered device', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vsmart&status=new', 'color': '7c8afa', 'icon': 'images/device/device-new.png', 'count': 0}]}, {'type': 'vbond', 'name': 'vbond', 'image': 'images/vbond.png', 'count': 1, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', 'count': 1}, {'status': 'new', 'name': 'Discovered device', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vbond&status=new', 'color': '7c8afa', 'icon': 'images/device/device-new.png', 'count': 0}]}, {'type': 'vEdge', 'name': 'vEdge', 'image': 'images/vedge.png', 'count': 4, 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge', 'statusList': [{'status': 'error', 'name': 'Error', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=error', 'color': 'fa7c7d', 'icon': 'images/device/device-error.png', 'count': 0}, {'status': 'warning', 'name': 'Warning', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=warning', 'color': 'f2ce60', 'icon': 'images/device/device-warning.png', 'count': 0}, {'status': 'normal', 'name': 'Normal', 'detailView': 'dialog', 'detailsURL': '/dataservice/device?personality=vedge&status=normal', 'color': 'b0e276', 'icon': 'images/device/device-normal.png', … -
Django datetime missing on edit page
i make a datetime input, but the problem when i make edit page, the datetime field empty.. views.py #update vechile armada def edit_vechile(request, no_pol): armada = Vechile.objects.get(no_polisi=no_pol) vechileform = VechileForm(instance=armada) if request.method == 'POST': vechileform = VechileForm(request. POST,request.FILES, instance=armada) if vechileform.is_valid(): vechileform.save() return redirect('arm-list') else: print(vechileform.errors) context = { 'vechileform': vechileform } return render(request, 'store/edit_arm.html', context) . models.py class Vechile(models.Model): no_polisi = models.CharField(max_length=10, unique=True) tanggal_stnk = models.DateField(null=True) . forms.py class VechileForm(forms.ModelForm): class Meta: model = Vechile fields = ['no_polisi','tanggal_stnk'] widgets = { 'no_polisi': forms.TextInput(attrs={'class': 'form-control', 'id': 'no_polisi'}), 'tanggal_stnk': forms.DateInput(attrs={'type': 'date', 'required':'true'}), . here my template edit_arm.html <form action="#" method="post" novalidate="novalidate" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group row"> <label for="tanggal_stnk" class="col-sm-2 col-form-label">Tanggal STNK<a style='color:red'>*</a></label> <div class="col-sm-10"> {{ vechileform.tanggal_stnk }} </div> </div> </form> And here screenshoot of my edit page : Other field are return to edit page.. but why datefield missing on edit page ? Thanks -
Django sometimes does not cascade on delete
I have the following relevant models class GameOddORM(models.Model): game = models.ForeignKey(GameORM, on_delete=models.CASCADE, related_name='odds') # ... objects = GameOddQuerySet.as_manager() class Meta: constraints = [ models.UniqueConstraint(fields=['game', ...], name='unique_game_odd_idx') ] db_table = 'game_odds' class GameOddDifferenceORM(models.Model): game_id = models.BigIntegerField(null=False) left_odd = models.ForeignKey(GameOddORM, on_delete=models.CASCADE, related_name='left_odd_diff') right_odd = models.ForeignKey(GameOddORM, on_delete=models.CASCADE, related_name='right_odd_diff') value = models.FloatField() class Meta: constraints = [ models.Index(fields=['game_id'], name='diff_by_game_idx') ] db_table = 'game_odds_difference' Sometimes calling GameOddORM.objects.filter(...).delete() (there are no subqueries) results in the following exception django.db.utils.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`betsbot_db`.`game_odds_difference`, CONSTRAINT `game_odds_difference_left_odd_id_1043dadb_fk_game_odds_id` FOREIGN KEY (`left_odd_id`) REFERENCES `game_odds` (`id`))') That error is telling me a row of game_odds can't be deleted because there is a foreign key in game_odds_difference referencing it. Well I set ON DELETE CASCADE in GameOddsDifferenceORM model, so that error should not happen, in fact it happens just sometimes. That makes me think it's a concurrency issue because GameOddORM insertions and deletions are concurrent. Is Django failing to emulate ON DELETE CASCADE because after deleting the rows of game_odds_difference new rows may be added in between? The database has no triggers and I am not making raw queries. I am using Django 2.2.12, mysqlclient 1.4.6, MySQL 8.0.21, InnoDB database engine and Python … -
Ideas on how I can plot points in leaflet map near my location
I am trying to develop a web app that gets the users location and plots shops within a certain radius. I've hit a wall with how I can plot more points over just the users location. I will show some files I feel are the most relevant. I am using Leafletjs and I have a model called Shop that is populated with data I generated on https://overpass-turbo.eu/. I was following this tutorial (https://realpython.com/location-based-app-with-geodjango-tutorial) but im not sure how I would plot these points on the map, it suggests using the GeoLocation API but im curious if there is another way views.py from world.forms import LoginForms from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegistrationForm from django.http import JsonResponse from django.contrib.auth.decorators import login_required from . import models from django.contrib.gis.geos import Point def index(request): template = 'base.html' user = LoginForms() if user.is_valid(): user.save() render(request, "registration/login.html", {'form': user}) return redirect(template) else: return render(request, "registration/login.html", {'form': user}) def register(request): if request.method == 'POST': # if the form has been submitted form = UserRegistrationForm(request.POST) # form bound with post data if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegistrationForm() return render(request, 'registration/register.html', {'form': … -
Django server reload doesn't work for every .py file
I'm starting the django server with python manage.py runserver The output is following Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). In my django app I have a file named services.py and one is called schedules.py. When I make changes in the services.py file the reload works as expected, in schedules.py file changes do not lead to a server reload. Why is that? As a further information in my schedules.py file I have a schedule, which is not working: from django_q.tasks import schedule schedule('api.shared.tasks.send_order_reminder', schedule_type='I', repeats=-1) Having the same code in the services.py file creates a schedule -
django object destructuring and delete
I'm making an ecommerce web app with django. My issue is on the payment, I'm trying to remove the product or change a boolean field on that product. Usually handling shopping carts stock has been easier, but these products are cards and need to be unavailable asap. Please take a look, anything helps! I'm not doing a good job of destructuring these objects, theres a manytomany field on Payment. So they're accessible Models class Payment(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='payments') payment_method = models.CharField(max_length=20, choices=( ('Paypal', 'Paypal'), )) timestamp = models.DateTimeField(auto_now_add=True) successful = models.BooleanField(default=False) amount = models.FloatField() raw_response = models.TextField() stocks = models.ManyToManyField(Product) def __str__(self): return self.reference_number def out_stock(self): return self.stocks - 1 @property def reference_number(self): return f"PAYMENT-{self.order}-{self.pk}" def get_price(self): return self.product.price views class ConfirmOrderView(generic.View): def post(self, request, *args, **kwargs): order = get_or_set_order_session(request) body = json.loads(request.body) payment = Payment.objects.create( order=order, successful=True, raw_response=json.dumps(body), amount=float(body['purchase_units'][0]['amount']["value"]), payment_method='Paypal' ) order.ordered = True order.ordered_date = datetime.date.today() order.save() tick = payment.stocks print(tick) products = Product.objects.filter() return JsonResponse({"data": "Success"}) -
Django filter objects foreign key from another table
Two tables: post and rating. rating contains column - post (FK) that is post table's primary ID. I'm trying to filter table rating by columns user and ratingtype to get post (FK) value that I could use to filter post table by. Post.objects.filter(pk__in=Rating.objects.get(post=post).filter(Rating.objects.filter(user = self.request.user, ratingtype='like'))) -
getting queryset based on attributes from manytomanyfield in referenced object
I have the following models: class ModelOne(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class ModelTwo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_visible = models.BooleanField(default=False) modelones = models.ManyToManyField(ModelOne, blank=True) In a view, I want to get a queryset of ModelOnes based on attributes of ModelTwo. For instance, how might I get a queryset of ModelOnes that have a ModelTwo with is_visible set to True referencing them? To provide an example: one_one = ModelOne.objects.create() one_two = ModelOne.objects.create() two_one = ModelTwo.objects.create() two_two = ModelTwo.objects.create(is_visible=True) two_three = ModelTwo.objects.create() two_two.modelones.add(one_one) two_two.save() two_three.modelones.add(one_two) two_three.save() queryset = [????] queryset would only contain one_one because two_two has a reference to one_one and also has is_visible True. -
Django: NOT NULL constraint failed: wishlist_wish.user_id
I have a wishlist app with a custom user model. I added the user as the foreign key to each wishlist item. However, I am only able to add the foreign key by specifying a default user, even after deleting the existing db files and running makemigrations and migrate. The default user is associated with the wishlist item regardless of which user is logged in, and if I don't include a default user I get the "NOT NULL constraint failed: wishlist_wish.user_id" error. How can I update the code so that the wishlist item is associated with the logged-in user creating the item? A related question is whether I need to include a user id in my custom user model? I tried doing this as well and ran into the same problem. Thanks in advance. Wish Model: class Wish(models.Model): name = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) def __str__(self): return self.name Wish View: def add_wish(request): user = request.user wishes = Wish.objects.filter(user=request.user) if request.method == 'POST': form = WishForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = WishForm() context = {'form' : form, 'wishes' : wishes} return render(request, 'wishlist/add_wish.html', context) Wish Form: class WishForm(ModelForm): class Meta: model = Wish fields = ('name', … -
(gcloud.app.deploy) Error Response: [9] Cloud build 3913ab4b-4a10-4205-8d84-a0a809bfab00 status: FAILURE
CLI ERROR when deploying strong text -
How can I fix my Django model to store multiple lists of strings inputted by the user. Which can then be retrieved in the future as an object?
I'm trying to make this simple app that retrieves a list of string(s) entered by the user, which is then stored in an object. The idea is for users to create a list of movies for each of their favorite genres. A "user-created-dictionary" sort of speak... Like so in Python: UserMovies = { Scary : ['A','B','C'], Funny : ['D'], Sad : ['E','F], Thriller : ['G','H','I','J'] } Using the example above, the ideal Model.py would store user created dictionary keys, followed by storing values for keys, in a list. I'm trying to replicate the same in my Django model, but I'm not sure how to create a many-to-many relationship that stores data in a list. Here is the syntax I'm trying to follow from django.db import models, UserModel class Genres(models.Model): user = model.UserModel(UserModel.username) genres = models.CharField(max_length=1000) class Movies(models.Model): genres = models.ForeignKey(genres, on_delete=models.CASCADE) title = models.TextChoices(max_length=1000, choices = IMDBmoviesTuple) What I'm striving for is being able to store the genres for each user, including the movies within the genres. All of this being a CRUD app. Given the info, what would be the best way to structure the model? currently struggling with this one. -
Django is only extending the base.html template in 1 html file
I run into an extremely annoying problem that no one has nearly a solution for. I've lost hours on it and unfortunately I can't get it working. This is the problem: I am trying to extend a base.html file into 2 different html files. For some reason it is possible to extend it in home.html but not in pakbon.html. Below you can see my folder structure (It also doesn't work if I put the files into the same folder): Below you can see my urls.py: urlpatterns = [ path("", views.home, name="home"), path("pakbon/", views.pakbon, name="pakbon") ] Below you can see my views.py: def index(request): return render(request, "main/base.html", {}) @login_required def home(request): return render(request, "main/home.html", {}) def pakbon(request): return render(request, "pakbonsysteem/pakbon.html", {}) My base.html: <html lang="en"> <head> --- Some HTML </head> <body data-background-color="{{info.mode}}"> --- Some HTML {% endfor %} {% if user.is_authenticated %} {% block content %} {% endblock %} {% else %} <meta http-equiv="refresh" content="0; url=/login"> {% endif %} </body> </html> My home.html: {% extends 'main/base.html' %} {% block content %} --- Some HTML {% endblock %} My pakbon.html: {% extends 'main/base.html' %} {% block content %} --- Some HTML code {% endblock %} Image from home.html: Image from pakbon.html: They …