Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin script not installed to PATH
I'm on a new computer, and have to install Django again, so I typed the pip install Django command in my VSCode terminal to install it. However, after it downloads, I get this message: WARNING: The script django-admin.exe is installed in 'C:\Users\Xiaow\AppData\Roaming\Python\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Because of this, I can't start any new projects. How would I install this script to PATH? Is there a command I have to do or something? There also seems to be a .vscode folder in 'C:\Users\Xiaow' but I don't know if this is what is making Django not install the admin script to PATH. Everything else works, like I can go to my existing projects (copied over from my old computer) and runserver, and can access all the databases. However, it's just this admin script that is causing problems. I also tried uninstalling and reinstalling Django to no avail. Full terminal message: PS C:\Code> pip install Django Defaulting to user installation because normal site-packages is not writeable Collecting Django Using cached Django-3.1.4-py3-none-any.whl (7.8 MB) Requirement already satisfied: pytz in c:\users\xiaow\appdata\roaming\python\python39\site-packages (from Django) (2020.4) Requirement already satisfied: … -
filter model objects by filed and save it to new model in viewset
I am trying filter and get all objects from one model and save it new model with same fields. how to do this right way? models: class PunchRawData(models.Model): PUNCH_TYPES = [("in", "Punch IN"), ("out", "Punch Out")] employee = models.ForeignKey(Employee, related_name="punch_employee", on_delete=models.CASCADE) shift = models.ForeignKey(WorkShift, on_delete=models.CASCADE) work_location = models.ForeignKey(HRMLocation, blank=True, on_delete=models.CASCADE, null=True, related_name="punch_work_location") punch_type = models.CharField(max_length=255, null=True, blank=True, choices=PUNCH_TYPES) user = models.ForeignKey("useraccounts.User", on_delete=models.CASCADE) actual_clock_datetime = models.DateTimeField(null=True, blank=True) emp_photo = models.ImageField(upload_to="selfies/%Y/%m/%d/%I/%M/%S/") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): strl = "{emp_id} [{shift_id}]".format(emp_id=self.employee.emp_id, shift_id=self.shift.shift_id) return strl class Meta: verbose_name = "Punch Raw Data" verbose_name_plural = "Punch Raw Data" class PunchRawDataProcess(models.Model): PUNCH_TYPES = [("in", "Punch IN"), ("out", "Punch Out")] employee = models.ForeignKey(Employee, related_name="punch_employee_process", on_delete=models.CASCADE) shift = models.ForeignKey(WorkShift, on_delete=models.CASCADE) work_location = models.ForeignKey(HRMLocation, blank=True, on_delete=models.CASCADE, null=True, related_name="punch_work_location_process") punch_type = models.CharField(max_length=255, null=True, blank=True, choices=PUNCH_TYPES) user = models.ForeignKey("useraccounts.User", on_delete=models.CASCADE) actual_clock_datetime = models.DateTimeField(null=True, blank=True) emp_photo = models.ImageField(upload_to="selfies/%Y/%m/%d/%I/%M/%S/") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): strl = "{emp_id} [{shift_id}]".format(emp_id=self.employee.emp_id, shift_id=self.shift.shift_id) return strl class Meta: verbose_name = "Punch Raw Data Process" verbose_name_plural = "Punch Raw Data Process" serializers.py: class PunchRawDataProcessSerializer(serializers.ModelSerializer): class Meta: model = PunchRawDataProcess fields = ['employee', 'shift', 'work_location', 'punch_type', 'actual_clock_datetime', 'emp_photo', 'created_at', 'updated_at'] viewset: here i'm trying to query and filter PunchRawData and trying to save in … -
Can't use get_queryset in combination with context data in Django
I have a class that fetching data from DB based on form value filled by user on previous page. I'm able to access the first page, but when I click on paginator <- next page I'm getting this error: TypeError at ... object of type 'HttpResponse' has no len() context = super().get_context_data(**kwargs) # HERE this is my code class DbTotsugoLook(LoginRequiredMixin, ListView): template_name = 'totsugo_app/db_totsugo_list.html' context_object_name = 'totsugo_data' paginate_by = 5 def get_queryset(self, *args, **kwargs): file_type = self.request.GET.get('fileType', None) if file_type == "hikari": queryset = Hikari.objects.all() elif file_type == "hikan": queryset = Hikanshou.objects.all() elif file_type == "hikarihikan": queryset = HikariHikan.objects.all() elif file_type == "kokyaku": queryset = Kokyaku.objects.all() else: messages.error(self.request, 'DB error') return render(self.request, self.template_name) self.queryset = queryset return self.queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) list_exam = self.queryset #Kaoiro.objects.all().order_by("-id") paginator = Paginator(list_exam, self.paginate_by) page = self.request.GET.get('page') try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['totsugo_data'] = data context['title'] = "MyPage" return context -
Django Admin stuck meanwhile DB disk size explode, on object change-view admin panel
I have the following model: class ActionModel(models.Model): identifier = models.BigIntegerField( _("identifier"), null=True, blank=True) # target ig id username = models.CharField(_("ClientUsername"), max_length=150, null=True, blank=True) # username of the client account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True) # account name of the client date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) # action date target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action keyword = models.CharField(_("Keyword"), max_length=150, null=True, blank=True) # the source where this target found is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False ) # django user that performed the action class Meta: verbose_name = _("Action") verbose_name_plural = _("Actions") unique_together = [ ['account_name','date','target'], ] def __str__(self): return self.target.username And the following Admin.py: # Custome Admin model for ActionModel Model class ActionModelAdmin(admin.ModelAdmin): # Override queryset method to add count's def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.filter(user=request.user) return qs change_list_template = 'admin/model_history_index.html' list_display = [ 'target', 'account_name', 'date', 'keyword', 'is_followed_back', ] search_fields = ( 'account_name', 'keyword', ) def has_add_permission(self, request, obj=None): return False And have really no Idea why when clicking on: action admin The database free-space is going from 100GB to 0GB !! adding many .temp files on the postgres db folder. … -
Django creates default db tables in all db
I have three databases in my Django project. When I make migration, models from default db gets created in other two databases. But models from other two dbs (which are not default) are not getting in created in any database. Is it possible to tell Django not to create default db tables in other databases? Here is my code router.py class CheckerRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'customers': return 'customerdb' elif model._meta.app_label == 'userchecking': return 'usersdb' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'customers': return 'customerdb' elif model._meta.app_label == 'userchecking': return 'usersdb' return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'customers' or obj2._meta.app_label == 'customers': return True elif 'customers' not in [obj1._meta.app_label, obj2._meta.app_label]: return True elif obj1._meta.app_label == 'userchecking' or obj2._meta.app_label == 'userchecking': return True elif 'userchecking' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return False def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'customers': return db == 'customerdb' elif app_label == 'userchecking': return db == 'usersdb' return None Settings.py DATABASES = { 'usersdb': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'usersdb', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', }, 'customerdb': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'customerdb', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', }, 'default': … -
sending array data with multipart/form-data post request in Axios vue.js
I'm sending a post request from vue.js project using Axios and it contains a file upload, which requires me to use FormData, I found a nice answer that helped me with FormData: const getFormData = object => Object.keys(object).reduce((formData, key) => { formData.append(key, object[key]); return formData; }, new FormData()); and for the headers: headers: { 'Content-Type': 'multipart/form-data'}. The POST call looks like this: axios.post("http://127.0.0.1:8000/api/document/", getFormData(this.documentData), { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log("Successfully uploaded: ", response.data) }) .catch(err => { console.log("error occured: ", err) }) This is the data I'm sending: documentData: { name: '', file: '', version: '', company: '', author: '', category: [] } When sending the data with single category id, it works fine, but when I send multiple category ids the following error shows: "category": [ "Incorrect type. Expected pk value, received str." ] How can I solve this problem? -
Hey why am i not able to make a raq query in django with non primary key fields it is giving no such table found
I made the models as below this is defined in home/models.py class likes(models.Model): like_id=models.AutoField(primary_key=True) post_id=models.ForeignKey(post,on_delete=models.CASCADE) liker_user=models.ForeignKey(User,on_delete=models.CASCADE) date_liked=models.DateField(default=datetime.date.today) In search I made search/views.py as below and getting error def search_query(request): print(request.POST['search_query']) x=likes.objects.raw("Select Like_id,Post_id from home_likes") # Operational Error: No column found Post_id print(x) print(len(x)) return render(request,'search/search_query_page.html') -
Is it possible to convert an output image url from django backend back to an image file for upload/reupload?
I have an application preview and a console down below Edit Existing Post Instance The first 2 console logs are images of an existing django post instance that are about to be modified in a form of a URL The third console log is an image file when I added a third image with a file input. e.target.files[0] The behavior that I put in the django rest api for updating existing files in a nested relation is to flush out all images and reupload images in whatever it is in the current edit images preview. The question is that is it possible to convert the first two console logs in a form of a third console log for image reupload that will go through axios? -
Django auth password reset not working using on localhost
I am trying to add a password reset functionality to my website. I can only open localhost:8000/password-reset. When I try to enter valid email address to reset the password I get 500 Internal Server Error. I am using Django-3.0. I am using sendgrid's email account for sending emails. Any idea what I am doing wrong? I tried following many tutorials online but no luck. urls.py: . . . urlpatterns = [ . . . path('password-reset/',auth.PasswordResetView.as_view(template_name='user/password_reset_form.html'), name='password_reset'), path('password-reset/done/', auth.PasswordResetDoneView.as_view(template_name='user/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth.PasswordResetConfirmView.as_view(template_name ='user/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth.PasswordResetCompleteView.as_view('template_name ='user/password_reset_complete.html'), name='password_reset_complete'), ] password_reset_form.html: {% extends "user/index.html" %} {% load crispy_forms_tags %} {% block start %} <div class="container"> <div class="center"> <h4 class="card-title">Password Recovery</h4> <p>Enter your registered email address and we will send you a link to reset your password.</p> <form method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-primary btn-block">Reset</button> </form> <br> <a href="{% url "login" %}" style="text-decoration: none; color: blue; padding:3%; cursor:pointer;">Have an account? Go to login</a> </div> </div> </div> {% endblock start %} password_reset_done.html: {% extends "user/index.html" %} {% load crispy_forms_tags %} {% block start %} <div class="container"> <div class="center"> <p>An email has been sent with instructions to reset your password.</p> <p>Dont forget to check … -
Django online users with rest framework
I had used django-online-users to get online users and it worked fine. But the problem is that i am not able to get online users in django rest framework i.e. users making api calls from react to backend server. I am only getting direct logged in users log in admin panel. Please suggest a way to use it with django rest framework. Thanks. -
Django model- How to use filter through related models
I was trying to build an application in Django. see my requirements. The company will have multiple branches, and staff also work for one more branches in different roles. For example, they may work in branch-A as a sales manager and branch -b as a Branch Manager, I was trying to implement that by Django Group and Permission, ( I use custom permissions instead of Group permission). Please see my model classes #Branches class Branch(models.Model): branch_code=models.CharField(max_length=100,unique=True) address=models.CharField(max_length=200) delete_status=models.IntegerField(choices=BRANCH_CHOICES,default=LIVE) published_date = models.DateTimeField(blank=True, null=True) # Roles on Branch class BranchRole(models.Model): owner_branch = models.ForeignKey(Branch,on_delete=models.CASCADE,related_name='available_groups') available_group = models.ForeignKey(Group,on_delete=models.CASCADE) class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class StaffUser(models.Model): staff_id=models.CharField(max_length=100,null=True,) name=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs') class RoleInBranch(models.Model): branch_role=models.ForeignKey(BranchRole,on_delete=models.CASCADE,related_name='assigned_role') permissions=models.ManyToManyField(Permission,related_name='allowed_staffs_in_branch') role_owner=models.ForeignKey(StaffUser,on_delete=models.CASCADE,related_name='roles',null=True) Here I am getting permission id and staff object, but I need to find all branches which are having that particular permission (for that requested staff object). I tried this Branch.objects.filter(available_groups__assigned_role__permissions=permission_obj,available_groups__assigned_role__role_owner=staff_obj) please help me to find the exact solution -
how to send datetime dataframe to django template and plot it in js using plotly
I have a data-frame and I want to send it in my Django template. dummy code in views.py: def graphs(request): df_new = pd.read_excel("/home/cms/cms/static/Sensorik.xlsx") times = df_new.loc[:, df_new.columns[0]].to_json(orient='records') # columns[0] contains datetime values data_color = df_georgian.loc[:, df_georgian.columns[2]] color = data_color.to_json(orient='records') context = { 'times': times, 'data_color': color, ... } return render(request, 'graphs/graphs.html', context) In my template, I get these data like the following: <script> var times = {{ times|safe }}; console.log('index: ', typeof(index)); var color = {{ data_color|safe }}; </script> the color variable is totally ok but the times variable when get to JSON format turns from 2018-05-29 08:09:00 format to something like it: element: 1528108200000 I want to be able to plot the color based on times to get a line graph with plotly. i.e. I want to show times as x-ticks of my plot. any suggeston on 1- how to send datetime dataframe to django template? or 2- how to convert element: 1528108200000 into a datetime in js to plot it as x-ticks? -
Can't getting total when a product has discount price
I am trying to get total amount. Like when a product has discount price the total will be discount_price * quantity = total For that i have this model: class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.FloatField() discount_price = models.FloatField(null=True, blank=True) date = models.DateField(datetime.datetime.today, null=True) status = models.CharField(choices=STATUS_S, blank=True, null=True, max_length=255) payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.FloatField(null=True, blank=True) def save(self, *args, **kwargs): if self.discount_price: self.total = self.discount_price * self.quantity else: self.total = self.price * self.quantity return super().save(self, *args, **kwargs) Here i tried this method to override: def save(self, *args, **kwargs): if self.discount_price: self.total = self.discount_price * self.quantity else: self.total = self.price * self.quantity return super().save(self, *args, **kwargs) But its not working as i want. Here is my view.py where i also tried: class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) for product in products: if discount_price: order = Order(customer=Customer(id=customer['id']),product=product,fname=fname, discount_price=product.discount_price,phone=phone, address=address, quantity=cart.get(str(product.id))) else: order = Order(customer=Customer(id=customer['id']),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') -
Как изменить пароль кастомного юзара в джанго админке?
model date_joined = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_organizer = models.BooleanField(default=False) def __str__(self): return self.username это модель. Когда заходишь в админку джанго, нету возможности изменить пароль.... как можно решить эту проблему помогите плз enter image description here -
Python oops concept, how to use abstract in my case?
To answer my question django is not required but oops is. I have created may api's in django, every api's has two function in common: class UserViewset(viewsets.ViewSet): def create(self, request, format=None): ... def update(self,pk=None, request, format=None): .... create and update are common in every class api's. How can i use oops concept here.Like how can i create abstract class such that i can reduce code lines and reuse these function. I need good suggestion. -
'ManagementForm data is missing or has been tampered with' error at Django 3.1.3 occured to me
there. I'm getting in the following trouble. I had wrote a CRUD form app which can upload multiple images optionally in Django. But, I tried to create a post, Django told me below error, ValidationError at /ads/ad/create ['ManagementForm data is missing or has been tampered with'] What's happenig on my app? So as to solve this error, I read Formsets chapter in Djangodoc, and then tried to use formset in forms.py, tried to change post func in views, JQuery code to increment count pictures, etc...but all of them didn't help my app works fine. I'll show the some codes which seems to be a cause below, models.py 18 class Ad(models.Model) : 19 title = models.CharField( 20 max_length=200, 21 validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] 22 ) ~ ~ ~ 38 # Shows up in the admin list 39 def __str__(self): 40 return self.title 41 42 class Adfiles(models.Model): 43 ad = models.ForeignKey('Ad', on_delete=models.CASCADE, related_name='files') 44 picture = models.BinaryField(null=True, editable=True) 45 content_type = models.CharField(max_length=256, null=True, help_text='The MIMEType of the file') views.py 93 class AdCreateView(LoginRequiredMixin, View): 94 template_name = 'ads/ad_form.html' 95 success_url = reverse_lazy('ads:all') ~ ~ ~ 110 def post(self, request, pk=None, *args, **kwargs): 111 FilesFormSet = formset_factory(FilesForm) 112 data = … -
How do I show images related to product from a list to popup Django?
Here I am trying to display all the images related to a particular product in a popup. Here I am getting all the product template images list from the template table through the templateproductmapping table. models.py # this is the product table class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", upload_to='productImage/', null=True) # this is the imageTemplate table where I am storing template images class ImageTemplate(models.Model): temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True) temp_img = models.ImageField("Template Image",upload_to='Template Images/', null=False) # here in this table I am storing mappings of images to a product, so I can identify which image belongs to which product so I can use all the images related to a single product. class ImageTemplateProductMapping(models.Model): imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True) template_img_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE, verbose_name="Image Template ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") views.py def product(request, id): products = Product.objects.get(prod_ID=id) ImageTemplateProductslist = [] try: ImageTemplateProductsmap = ImageTemplateProductMapping.objects.filter(prod_id=id) #here i am getting all the images related to a single product. ImageTemplateProductslist = [data.temp_id.temp_img for data in ImageTemplateProductsmap] except AttributeError: pass context = {"ImageTemplateProductslist": … -
Redirect to View based on value in Form (Django)
I'm getting value from user in form like this #views.py class DbTotsugoForm(LoginRequiredMixin, FormView): form_class = DbTotsugoForm template_name = 'totsugo_app/db_totsugo_chose.html' # success_url = reverse_lazy('<app-name>:contact-us') def form_valid(self, form): file_type = form.cleaned_data['file_type'] # here I have a value from user (book, folder) return super(DbTotsugoForm, self).form_valid(form) and I would like to redirect user to list view - a data from DB based on the value above like this class MYLook(ListView): template_name = 'totsugo_app/db_totsugo_list.html' # So based on `file_type` variable above I want to change `Book` to `Folder` here queryset = Book.objects.all() How could I pass there that value, without creating MYLook two times for both values? -
how update one table without update all page in Django?
try with signals but i think that is for the database or no? well i have a this table please help me also i have pluggins for pagination and search when i delete i used .load() for delete the register but in pagination the row keep counting, how if i don't would have delete nothing <table id="tabla_libros" class="table"> <tr> <th>ID</th> <th>Titulo</th> <th>Autor</th> <th>Acciones</th> </tr> </thead> <tbody id="table_libros_body"> {% for libro in libros %} <th>{{ libro.id }}</th> <td>{{ libro.titulo }}</td> <td>{{ libro.autor }}</td> <td> <button type="button" onclick="Elimina({{ libro.id }})" title="elimina">Eliminar </button> </td> % endfor %} </tbody> </table> Views.py def Libros(request): try: libros = Libreria.objects.filter(es_activo=True) data = { 'articulos': articulos } return render(request, 'librero/libros.html', data) except Exception as e: print(e) data = { 'msg': 'error' + str(e.__str__()) } return JsonResponse(data, safe=False) -
'ManagementForm data is missing or has been tampered with' at Django3.1.3
there. I'm getting in the following trouble. I had wrote a CRUD form app which can upload multiple images optionally in Django. But, I tried to create a post, Django told me below error, ValidationError at /ads/ad/create ['ManagementForm data is missing or has been tampered with'] What's happenig to my app? So as to solve this error, I read Formsets chapter in Djangodoc, and then tried to use formset in forms.py, tried to change post func in views, JQuery code to increment count pictures, etc...but all of them didn't help my app works fine. I'll show the some codes which seems to be a cause below, models.py 18 class Ad(models.Model) : 19 title = models.CharField( 20 max_length=200, 21 validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] 22 ) ~ ~ ~ 38 # Shows up in the admin list 39 def __str__(self): 40 return self.title 41 42 class Adfiles(models.Model): 43 ad = models.ForeignKey('Ad', on_delete=models.CASCADE, related_name='files') 44 picture = models.BinaryField(null=True, editable=True) 45 content_type = models.CharField(max_length=256, null=True, help_text='The MIMEType of the file') views.py 94 template_name = 'ads/ad_form.html' 95 success_url = reverse_lazy('ads:all') ~ ~ ~ 110 def post(self, request, pk=None, *args, **kwargs): 111 FilesFormSet = formset_factory(FilesForm) 112 data = { 113 'form-TOTAL_FORMS': '1', … -
Django - I want to select all value about a model through multiple models
Now in file view.py I want to get all data Booking model belong to Location model What I have to do ? models.py class Location(models.Model): DISTRIC = ( ... ) user = models.ForeignKey(User, on_delete = models.CASCADE) name = models.CharField(max_length=255) phone = models.CharField(max_length=15) address = models.CharField(max_length=255) district = models.CharField(max_length=255, choices=DISTRIC) description = RichTextUploadingField() class Yard(models.Model): TYPE = ( ... ) location = models.ForeignKey(Location, null=True, on_delete = models.CASCADE) code = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=TYPE) class Time(models.Model): TIME = ( ... ) yard = models.ForeignKey(Yard, null=True, on_delete=models.CASCADE) time = models.CharField(max_length=255, choices=TIME) cost = models.CharField(max_length=255) class Booking(models.Model): STATUS = ( ... ) time = models.ForeignKey(Time, on_delete = models.CASCADE) user = models.ForeignKey(User, on_delete = models.CASCADE) status = models.CharField(max_length = 255, choices=STATUS, default="M") note = models.TextField(null=True, blank=True) -
how can i write view for this issue models?
everyone. actually, I'm new to the Django rest framework and also React.js I have a project which is managing EXTRA SHIFTS. issue : users want to take extra shifts from some other users who want to cancel shifts. So this is part of my models in django : class Dealers(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User,on_delete=models.CASCADE) language_id = models.ForeignKey(Languages,on_delete=models.CASCADE) shift_id = models.ForeignKey(Shifts,on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now_add=True) #profile_pic = models.ImageField() def __unicode__(self): return self.user class ExtraShifts(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) slug = models.SlugField() shift_id = models.ForeignKey(Shifts,on_delete=models.CASCADE) language_id = models.ForeignKey(Languages,on_delete=models.CASCADE) ExtraShift_Date = models.DateField() # which day ? thay need people to take an extra Time_List=(('now','NOW'),('10','10am to 6pm'),('6','6pm to 2am'),('2','2am to 10am')) ExtraShift_Time = models.CharField(choices=Time_List,max_length=50) # what time ? thay need people to take an extra create_at = models.DateTimeField(auto_now_add=True) # when this extra created update_at = models.DateTimeField(auto_now_add=True) # when this extra updated priority_list=(("Normal","Normal"),("Urgent","Urgent")) priority = models.CharField(choices=priority_list,default='Normal',max_length=12) quantity = models.IntegerField(default=1) def __str__(self): return self.title class ExtraShiftsOrder(models.Model): id = models.AutoField(primary_key=True) shift = models.ForeignKey(ExtraShifts,on_delete=CASCADE) dealer = models.ForeignKey(Dealers,on_delete=models.CASCADE,null=True) create_at = models.DateTimeField(auto_now_add=True) # when this extra was take it ordered = models.BooleanField(default=False) def __int__(self): return self.id I wanna pass some rolls to the user can take extra and then send it to APIVIEW: for … -
Immediately sending messages using Django Channels
I have a long-running operation that is kicked off by a message from a websocket and I would like my server to send a confirmation to the client with when the operation was started and when it was ended. This is essentially the same as this question but there was no useful answer. I tried await self.send(data, immediately=True) but got an error because it seems immediately is either no longer supported or doesn't work in the async version or something. I really do not want to screw around with setting up channel layers and Redis and having yet another thing to configure that will inevitably break, or worse, have to set up Celery in WSL and deal with all my testing happening in a separate VM. If this isn't possible with just Channels, I am perfectly happy with that so no need to explain how to set it up using a third-party library (if you think others might find it useful, by all means go ahead). -
Use Django REST API and Django Templating
I'm just starting to use Django for my backend services, but I'm a bit confused about the usage of Django REST framework, see I'm building an iOS app as a front-end, to the best of my knowledge Django REST is the best library to perform my backend tasks, however, I would eventually like to build a regular web front-end. I've seen tutorials on Django and Django REST, and they never talk about using both. My question is how to use Django REST to feed the iOS App, and be able to use Django's templating engine for a web front-end using the DRY principle. I did read on the Django REST framework's website, that you can use class based views with the framework, so can I use this same class to feed by web front-end and my ios app efficiently? class SnippetDetail(APIView): def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 -
How to create logic for users to follow and unfollow in twitter clone
hy, I'm creating a twitter clone using django. I have a problem creating the follow and unfollow button.First, I want the unfollow button to show if the current user is already following a particular user else the follow button should show. Secondly, how can I check if the logged in user is following a particular user. Models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.TextField(null=True,blank=True) profile_pic = models.ImageField(default='default.png',upload_to="images/profile/") following = models.ManyToManyField("self",symmetrical = False,blank=True) followers = models.ManyToManyField('self',symmetrical = False,blank=True,related_name='followers_profile_test') def __str__(self): return str(self.user) @property def profile_picURL(self): try: url = self.profile_pic.url except: url = " " return url def get_absolute_url(self): return reverse("home") Views.py def FollowView(request,pk): user = User.objects.get(id=pk) profile = Profile.objects.get(user=user) following=False if profile.followers.filter(id=request.user.id).exists(): profile.followers.remove(request.user.profile) request.user.profile.following.remove(profile) following=False return redirect('home',{'following':following}) else: profile.followers.add(request.user.profile) request.user.profile.following.add(profile) following = True return redirect('home',{'following':following}) return render(request,'registration/show_profile.html') show profile.html page This part of the html deal with the logic. The page is big so I don't want to bore you.However i can provide it if it will be helpful <div class="column3"> <div class="colum2-title cl3"><h3 class="text-white">People to Follow</h3></div> <div class="people-to-follow"> {% for user in users %} {% if not user.is_superuser%} <h6><h5 class="fullname">{{user.first_name}} {{user.last_login}}<h5 class="username">@{{user.username}}</h5></h6> <h5 class="username">{{request.user.is_superuser}}{{user.id}}{{request.user.profile.following.count}}</h5> <form action="{% url 'follow' user.id %}" method="POST"> {% csrf_token %} {% if following %} <button …