Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changing Arrow Color for users
iam a Django BackEnd Developer and i have created a Blog i just want to know how to color slected Arrow after user Vote for specific Post and save it this is Arrow Html: <a href="{% url 'home:post-vote-up' id=posts.id %}"><i class="fas fa-arrow-up"></i></a> <p class="lead">{{posts.votes}}</p> <a href="{% url 'home:post-vote-down' id=posts.id %}"><i class="fas fa-arrow-down"></i> </a> -
How to get only month name and total in Django
I am trying to get only month name and count number from Data = QuerySet [{'month': datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Dhaka' +06+6:00:00 STD>), 'count': 2 }] If I use Data[0]['month'] result is showing like (2021, 3, 1,0,0, ...) but I need to see only as March How can I view the month? Thanks in advance. -
Pip freeze > requirements doesn't work well with anaconda
I am trying to create a virtual environment based on another, for this, I want to extract the information from the libraries for a Django environment with pip freeze> requirements.txt But the output is asgiref @ file:///tmp/build/80754af9/asgiref_1605055780383/work certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.7 cycler==0.10.0 Django @ file:///tmp/build/80754af9/django_1613762073373/work django-clear-cache==0.3 djangorestframework==3.12.4 idna==2.10 kiwisolver==1.3.1 matplotlib==3.4.1 numpy==1.20.2 Pillow==8.2.0 psycopg2 @ file:///C:/ci/psycopg2_1612298766762/work pycparser==2.20 PyMySQL==1.0.2 pyparsing==2.4.7 PyQt5==5.15.4 PyQt5-Qt5==5.15.2 PyQt5-sip==12.8.1 python-dateutil==2.8.1 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.25.1 six==1.15.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.4 wincertstore==0.2 When I try pip install -r requirements.txt doesn't work. Output Processing c:\tmp\build\80754af9\asgiref_1605055780383\work ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\tmp\\build\\80754af9\\asgiref_1605055780383\\work' So I need a way to extract info with pip and install it with pip in another environment. -
Django | Why are my added fields to my CreateView not saved to the database/ or aren't rendered?
For a couple of days I'm stuck on a part of my Django project, where I want to add some extra fields for the user to fill in when they create a post. The problem is that the extra fields are not showing up on the page, or are saved in the database. I'm seeing these added fields on the create post template, so they are showing up and I can use them in the form (I'm using Cripsy forms), but after submitting, its not being saved (or something?) I'm using the CreateView and use a ModelForm to add those fields. I've followed all of the steps from the Django documentation but I can't solve it. I'm still a beginner, but I've looked everywhere for answers but nowhere I can find a specific solution to this problem. Please take a look at my code. I'm using the Django Post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=300) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I've added a forms.py file where my ModelForm is located which holds the extra fields: class AddPostCreateForm(forms.ModelForm): # forms.ModelForm i.p.v. forms.Form omdat ik gebruik maak … -
When I open the model, one field value is replaced automatically
everyone! Have a stupid issue: When I open the employee model (in django admin), one field (employee_type) value is replaced automatically, idk why... Example: I create employee, define employee type as manager, save. In DB value is manager. After that, I open employee and see employee type as sewer and if I save, that value will saved in DB. I created text choices for this field, and In DB field is defined as enum. I tried to research the issue, value isn't used from DB, always first value from text choices is used. By the way, I created same fields (enum in DB and text choices in the model) in other model. And all works properly. How can I fix it??? Models.py with the issue: class Employee(models.Model): class EmployeeType(models.TextChoices): SEWER = 'SEWER', _('Sewer') MANAGER = 'MANAGER', _('Manager') UNDEFINED = 'UNDEFINED', _('Undefined') id = models.OneToOneField(User, models.CASCADE, db_column='id', verbose_name=_('User'), primary_key=True) employee_type = models.CharField(db_column='Employee type', verbose_name=_('Employee type'), max_length=9, choices=LabourIntensity.choices, default=LabourIntensity.MEDIUM) phone = models.CharField(db_column='Phone', verbose_name=_('Phone'), max_length=255) work_xp = models.IntegerField(db_column='Work XP', verbose_name=_('Work XP'), blank=True, null=True) Another one models.py. With same fields but without issues: class Order(models.Model): class OrderStatus(models.TextChoices): CREATED = 'Created', _('Created') CANCELLED = 'Cancelled', _('Cancelled') IN_PROGRESS = 'In progress', _('In progress') COMPLETED = 'Completed', … -
Framework, front-end, back-end, full stack? Or not to learn a framework?
I have several questions. I am a student and am training in web development. I have practically finished developing my first site which uses HTML, CSS, Javascript, PHP and MySQL. I want to acquire a certain ease in web development, but in theory this will not become my job, nor my daily life. I am about to start a bigger project (several months of development to be expected) because I am starting to be confident and have the capacities of my ambitions (not crazy either). Basically I'm more Python, not web development. So I would like to know if it is important to learn a framework? Especially since not wishing to be professionalized, therefore not specialized in front-end or back-end, I would prefer to solidify myself in full-stack knowledge for the moment. I have heard of Symfony (PHP), Node.js (JS), Bootstap (JS), etc ... But these are specialized front or back frameworks. If I have to learn a framework I would prefer it to be full-stack. And I ask myself the question if Django will not be what I need since it is a Python web framework. But is it good? Is it "full-stack" or just back-end? Isn't it a … -
Django querryset annotate and aggregation
I have a few models for which I am trying to create custom managers and query sets. In this example, I want to get the total paid amount throughout all the orders for each customer. But unfortunately, I will keep getting the wrong values, why?! Here is an example of some of my models: class customer(models.Model): name = models.CharField(max_length=100, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="customer") objects=CustomerManager() #My customer manager class order(models.Model): paid = models.DecimalField(default=0.00, max_digits=30, decimal_places=2) customer = models.ForeignKey(customer, on_delete=models.CASCADE, related_name="order") class order_item(models.Model): quantity = models.PositiveIntegerField(default=0, null=False) price = models.DecimalField(decimal_places=2, max_digits=30, default=0.00) product = models.ForeignKey(product, on_delete=models.CASCADE, related_name="order_item") order = models.ForeignKey(order, on_delete=models.CASCADE, related_name="order_item") Here is my manager: class CustomerManager(models.Manager): def get_queryset(self): return CustomerManagerQuerry(self.model, using=self.db) def get_customer_stats(self): return self.get_queryset().customer_stats() Querryset: class CustomerManagerQuerry(models.QuerySet): def customer_stats(self): table = self.annotate(total_paid=Sum('order__paid', output_field=FloatField())) return table.values('total_paid') My goal is to get the summation of paid attributes throughout the orders for the customer. When the order object includes only one order_item the querryset outputs the correct value, But when the order object contains more than one order_item I will get the wrong result. For example when I run the code customer.objects.get_customer_stats() for only one customer who has only one order with the paid amount of 10.0, I will … -
How to send excel file as a download link button by email using celery?
I need to send an excel file as a download link button in html template by Email using celery my question: do I need to use a field to save the file and use it as a url ? or can I send the export data directely to the html template button as a file ? can I : send the file with generate http so can the user download it ? the target: the data is huge and limit of gmail is 20mb for a file attached,for this need to make it as a download link button not send it as an attached file task.py dataset = OrderResource().export(queryset=queryset) export_data = format_type.export_data(dataset) # Send E-mail start here NotificationSender.send(user, SalesReportEmail(file_name, export_data, content_type)) the celery here is for send the file and email and it doesn't return any thing to the views.py and for that I think I can't use http response the process : the user select the file format then the function send this format to celery "task.py" to collect data and send it by email as a file download link, the funcion here "in views.py " only shows pop up message say that "Please allow few minutes, the report … -
Django dj-rest-auth + react: What is the best way to activate your email when ACCOUNT_EMAIL_VERIFICATION = 'mandatory'?
I'm currently building a django & dj-rest-auth + react project and have my allauth ACCOUNT_EMAIL_VERIFICATION = 'mandatory'. Currently and by default, the email activation link can only make a GET request to dj_rest_auth.registration.views.VerifyEmailView (source code) that only accepts a POST request with the activation key as a body param: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [example.com] Please Confirm Your E-mail Address From: webmaster@localhost To: firstlast@email.com Date: Sun, 04 Apr 2021 09:56:05 -0000 Message-ID: <161753016543.13016.12022069896332406678@DESKTOP-LFBEG3D> Hello from example.com! You're receiving this e-mail because user firstlast@email.com has given your e-mail address to register an account on example.com. To confirm this is correct, go to http://localhost:8000/users/registration/account-confirm-email/MjQ:1lSzUD:OVzw0T279ufU2FyzHhKbWo2oilnya9x9vfQLJ6WgEzw Thank you for using example.com! example.com [04/Apr/2021 02:56:05] "POST /users/registration/ HTTP/1.1" 201 18797 And I don't know how to make a POST request through a link that's embedded in an email sent by Django. My current solution is to modify the get_email_confirmation_url method by replacing the absolute_uri with my frontend react route. Then from there I'll make a POST request to VerifyEmailView so that the user doesn't have to look at my backend views. Is there a good or standard way to dynamically add my frontend domain instead of hardcoding http://localhost:5000 and https://production.com into my … -
Django Subdomains
I want to create a mutitenant site with subdomains. Meaning, users will sign up with email, password and company name. Although, I am still experimenting with the email. Upon register, they will be redirected to a subdomain like company_name.domain.com. Right now, I am using the package Django-Subdomains I have setup as specified in their doc. But I dont quite get how to set up the views. For instance, my register view is this class RegisterStaff(View): template = 'account/register.html' def get(self, request, ): register_form = StaffRegisterationForm() context = { 'register_form': register_form, } return render(request, template_name=self.template, context=context) def post(self, request): register_form = StaffRegisterationForm(request.POST) if register_form.is_valid(): staff = register_form.save() password = register_form.cleaned_data['password1'] email = register_form.cleaned_data['email'] print(dir(request)) my_user = authenticate(request, email=email, password=password) login(request, my_user, ) request.subdomain = request.user.email print(request.subdomain) return redirect('account:dashboard', subdomain=request.subdomain) else: print(register_form.errors) return HttpResponse('form is invalid') and I have my dashboard vies below. class Dashboard(View): template = 'account/dashboard.html' def get(self, request): try: staff = Staff.objects.get(email=request.subdomain) except Staff.DoesNotExist: raise Http404 Normaly, I would thought that after registration, I should be redirected to email.domain.com. But I get a 404 instead. Please help if you are familiar with this package. my Url from Django.urls import path from .views import RegisterStaff, Dashboard, LogoutUser,LoginUser app_name = 'account' … -
property field is not shown in api call in django rest framework
I am trying to add a property field to my serializer while creating Order objects creating the OrderItem objects at the same time. But it is not shown in the result while calling the post api. There is no price filed in the result as shown here. My models: class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True #orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property def price(self): return self.quantity * self.item.varaints.price # return total_item_price My serializers: class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 Here I have put price in the serializer field, there is no error, but it doesnt show the price in the api in postman. class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Order fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price','billing_details'] # depth = 1 def create(self, validated_data): user = self.context['request'].user if not user.is_seller: order_items = validated_data.pop('order_items') billing_details = validated_data.pop('billing_details') order = … -
unable to read .replit: unable to decode .replit: Near line 5 (last key parsed 'run'): Key 'run' has already been defined
so effectively I am tryinning to run a Django website that i can share the link. The issue is the RUN file with the .replit file. I need to pip install crispy forms then run the server. How can this be accomplished in the .replit file? tried the following: language = "python3" run = "pip install django-crispy-forms" run = "python manage.py runserver 0.0.0.0:3000" -
Django Redirect to previous page, if user is not allowed to access page
I have created a custom decorator to restrict access to a view based on an user's group. If a user is not allowed to access the view he/she gets redirected to my landing page '/' (in code below)... How can I redirect the user to the site he/she was coming from? I am close but I don't know how to fix this. Thank you so much Please see: def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = '' if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponseRedirect(request.META.HTTP('HTTP_REFERER', '/')) return wrapper_func return decorator Thanks a lot -
How to send veriables using redirect and use in other views
Im working on project and im sending data/veriable while redirecting flow from one view to another(first view/empty view) def index(request,a=False): if request.method=='POST': return render(request,'chart-chart-js.html',{'a':True}) return render(request,'chart-chart-js.html',{'a':a}) def login(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): if form.cleaned_data['username']=='Unknown' and form.cleaned_data['password']=='Unknown': return redirect(index,a=True) -
Apache with mod_wsgi not serving on port 80
I'm actually facing some weird issue. I have a Linux based server with two Django app installed and I want to serve them using mod_wsgi. The problem, when I set the vhost to listen to port 80, in the browser it's just showing me directories and files. When I set it to listen to 8080 it works but only if I'm behind a VPN (or proxy). Here is my httpd.conf Listen 80 <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess 0.0.0.0 (my IP adress) python-home=/usr/local/apache/htdocs/env python-path=/usr/local/apache/htdocs/myapp/myapp/ request-timeout=12000 WSGIProcessGroup my_ip WSGIScriptAlias /myapp /usr/local/apache/htdocs/myapp/myapp/wsgi.py process-group=my_ip <Directory /usr/local/apache/htdocs/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess my_ip python-home=/usr/local/apache/htdocs/env python-path=/usr/local/apache/htdocs/myapp2/ request-timeout=12000 WSGIProcessGroup my_ip WSGIScriptAlias /myapp2 /usr/local/apache/htdocs/myapp2/myapp2/wsgi.py process-group=my_app <Directory /usr/local/apache/htdocs/myapp2/myapp2> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Does anyone know how to figure this out ? -
login_required does not work with firebase auth
I have a login page with authenticates the user using the built in Django authentication. However when I use firebase authentication to authenticated a user, the @login_required decorator for my other pages does not allow the user to access those pages (even the user is logged in using the correct credentials). I followed a tutorial from here https://www.youtube.com/watch?v=8wa4AHGKUJM My login views.py using django authentication: email=request.POST.get('email') passw=request.POST.get('pass') user = authenticate(request, username=email, password=passw) if user is not None: login(request, user) return render(request,"pick.html") else: message="Invalid credentials. Try again." return render(request,"login.html", {"msgg":message}) My login views with firebase authentication: email=request.POST.get('email') passw=request.POST.get('pass') user=auth.sign_in_with_email_and_password(email,passw) usercheck = auth.get_account_info(user['idToken']) usercheckjson=json.dumps(usercheck['users']) userjsonload=json.loads(usercheckjson) if userjsonload[0]['emailVerified'] == False: message="Please verify your email before login!" return render(request,"login.html", {"msgg":message}) else: #login(request, user) <-- this does not work session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") Any suggestions on how i can get this to work, or should i just use the built in Django authentication? -
Django channels + Daphne + Nginx, path not found only for wss, not ws
A summary of my question: I am deploying websocket with django channels. When I use ws (without SSL), everything works well. But when I request using wss (with nginx re-configed), it shows the error Not Found: /ws/rider/mission/ Here are some details: I have added path /ws/ for both 80 and 443 ports From the console of Daphne, I can see both requests, as shown in the figure below. Therefore, I think my Nginx is correctly forwarding both 80 and 443 requests. But from this figure, I can find that, for this same route "/ws/rider/mission/", the wss request cannot be found, but ws request runs well. Here is my aswi config application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": Oauth2AuthMiddleware( URLRouter( websocket_urlpatterns = [ url(r'ws/rider/mission/', consumers.RiderConsumer.as_asgi()), ] ) ), }) I don't know where the bug comes from, it is between Nginx to Daphne, or Daphne to Django channels or in Django channels itself. Thanks! -
AJAX return 500 Internal Server Error on POST :DJANGO
i have a program which should post formdata to another HTML page , in DJANGO , but it throws me Internal Server Error . . so here is my code : AJAX CALL: $("[name=ButtonSubmit]").click(function() { var myarrayServer = []; $(".form-check-input0:checked").each(function() { var opeartions = [] //for inner array var row = $(this).closest("tr"); //get servername var server_name = row.find("td:eq(1)").text().trim(); var components = row.find("td:eq(2)").text().trim(); var PID = row.find("td:eq(3)").text().trim(); var State = row.find("td:eq(4)").text().trim(); opeartions.push(server_name) //push in array opeartions.push(components) opeartions.push(PID) opeartions.push(State) //get checkboxes which is checked in same row row.find("input[type=checkbox]:checked:not(:first)").each(function() { opeartions.push($(this).val()) }) myarrayServer.push(opeartions) //push values in main array }); var formdataD = new FormData(); formdataD.append('myarrayServer', myarrayServer); formdataD.append('csrfmiddlewaretoken', $("[name=csrfmiddlewaretoken]").val()); $.ajax({ url: 'secondtableonDashboard', //replace with you url method: 'POST', data: formdataD, processData: false, contentType: false, success: function(data) { alert(data.message); alert("Success"); }, error:function(request, status, error){ alert(error); } }); }); So here i gave alert for formdata and myarrayserver , both gave me alert with the correct data . Views.py : if 'ButtonSubmit' in request.POST: print("Inside Button") print(list(request.POST.items())) user_lists = request.POST.getlist('myarrayServer') print(user_lists) cmddata = {'customerserver':result} return render(request,'side-menu-light-tabulator.html',cmddata) So here i am able to print "inside Button" , but rest print give me an empty list [] , I don know where i did mistake Can someone help … -
Problem sending data with ajax to django server
I'm trying to send some ajax data to my Django server but encounter an error that I have difficulties debugging : raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). This is my script and part of my django view. function UpdateUserResponse(productId, action, count) { $.ajax({ url: "/updateitem/", method: "post", headers: { 'Content-Type':'application/json', "X-CSRFToken": csrftoken }, dataType: "JSON", body: JSON.stringify({ productId : productId, action: action, count: count }), success: response => { console.log("not relevant to this problem"); } }); } and how i try to receive the data in my view def updateitem(request) : data =json.loads(request.body) productId=data['productId'] action = data['action'] count = data['count'] Thanks a lot for your help -
How to bind a django form to an object instance
I come from DRF background so please already assume that I might be getting something wildly wrong here. I am trying to use Django Form as a sort of proxy for DRF serializers. As in, when I fetch an object, I can quickly render it back, and I can of course accept POST requests and store them. What I can't seem to find is how do I use my object instances to process them with forms. Here's my form: class ProfileForm(ModelForm): class Meta: model = UserProfile fields = ('name', 'profile_pic') The actual model: class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to='profile_image', null=True, blank=True) def __str__(self): return str(self.user) Now, in my view, I'm doing something like this: from django.forms import model_to_dict profile = request.user.userprofile form = ProfileForm(model_to_dict(profile)) return render(..., form) Is this even the right approach? Besides, the problem is that my form doesn't seem to handle the profile_pic field properly (i.e. the img src field in the from html is just __). Ideally I would want to build the form from the object instance itself, but that also doesn't work. form = ProfileForm(instance = profile) is nethier bound, nor valid form = ProfileForm(UserProfile.objects.all()[0]) is … -
How to apply django-filter after SerializerMethodField modified values?
I feel stuck with the following issue: I added django-filter to my django-rest project to allow filtering by contract's signing status field. The problem is that my contract_signing_status has only 2 possible DB values: SIGNED, NOT_SIGNED. However, I use a SerializerMethodField which internally accesses a user model from the request and returns different values, eg: "WAITING_FOR_ME", "WAITING_FOR_OTHRS". The problem is that the django-filter works on the query-set. As a result, if I set those values: "WAITING_FOR_ME", "WAITING_FOR_OTHRS" as my query params, I keep getting an empty response list, because my model does not define those values... I would like to apply django-filtering on the serializer.data, not on the query-set, because values are modified after the serializer serialized that query set. Is it possible? I thought about creating a property in my model. But properties can't accept additional arguments, like User for example. -
wagtail custom locale file
i integrate Wagtail into my Django project and my language is persian ( fa ) i use multilang in django project and wagtail admin panel words translation to persian works and is perfect but in wagtail admin panel some words not translated and i want to add this words i found this words in wagtail/admin/locale/en/LC_MESSAGES/django.po but in wagtail/admin/locale/fa/LC_MESSAGES/django.po does not exists how can i use my custom locale file for wagtail admin panel? how can i fix this? -
data isn't importing in mysqldb using django import export
I am new in Django. I am trying to use Django import-export to import excel sheet into MySQL dB table. I followed the documentation on import. while trying to Test the data import it gives error. Here are my views: from django.shortcuts import render from pathlib import Path import os from .resources import ProductsResource from tablib import Dataset def home(requests): dataimport() return render(requests,'dbapp/index.html') def dataimport(): products_resource = ProductsResource() dataset = Dataset() dirname = Path(__file__).resolve().parent.parent file_name = 'Price.xlsx' file_location = os.path.join(dirname, file_name) df = pd.read_excel(file_location, header=1, usecols='A:F') result = products_resource.import_data(dataset, dry_run=True) # Test the data import print(result.has_errors()) if not result.has_errors(): products_resource.import_data(dataset, dry_run=False) # Actually import now Resource.py: from import_export import resources from .models import Products class ProductsResource(resources.ModelResource): class Meta: model = Products Models.py: from django.db import models from django.db.models.fields import DateField class Products(models.Model): date = models.DateField(auto_now_add=False,auto_now=False) salt = models.FloatField() oil = models.FloatField() honey = models.FloatField() butter = models.FloatField() milk = models.FloatField() My csv file looks like this: Date Salt Oil Honey Butter Milk 2020-1-1 26.5 106.5 281 387.5 83 2020-1-2 26.2 106.2 279.8 386 82.4 2020-1-3 26 106 279 385 82 2020-1-4 25 105 275 380 80 2020-1-5 26.2 106.2 279.8 386 82.4 2020-1-6 26.1 106.1 279.4 385.5 82.2 output of … -
django_host raising 'accounts' is not a registered namespace error
I implemented django_hosts in my project and followed all the basics as documented here, everything seemed perfect until I started using the {% load hosts %} and {% host_url 'accounts:login' host 'accounts' %} template tags to reverse URLs just as it would normally be done with the default URL tag like {% urls 'accounts:login' %}. And now, I am getting the following errors. NoReverseMatch at /en/auth/signup/personal/ 'accounts' is not a registered namespace` I have taken a closer look at my code again and again, but I can't find any issue with it. Has anyone experienced this kind of issue before? sample HTML {% extends 'base.html' %} {% block content %} {% load hosts %} <form class="form" method="post" enctype="multipart/form-data" role="form" action="{% host_url 'accounts:login' host 'accounts' %}"> {% csrf_token %} {% bootstrap_messages %} {% bootstrap_form form show_label=False %} <button class="btn block-btn" type="submit" role="button">{% trans 'Sign in' %}</button> </form> <!--redirect--> <span class="text-center d-block"> <a href="{% url 'password_reset' %}" class="form-footer-link centered-form-link"> {% trans "Can't login?" %} </a> <span class="middot">&bull;</span> <a href="{% host_url 'accounts:personal_signup' host 'accounts' %}" class="form-footer-link centered-form-link"> {% trans "Sign up for an account" %} </a> </span> {% endblock content %} hosts.py host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'auth', 'accounts.urls', name='accounts'), ... ) … -
Uploaded Document Version Control
I have a Django web app for uploading and sharing files. I am looking for good library that can assist with document version control. Maintain copies of the same document. Has anyone ever encountered such a use case?