Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap Modal popup and Django
I'm new to django/bootstrap and currently i'm practising by using an html/css/js template which i downloaded from the internet. I rendered the template with django successfully by following a tutorial. Now i want to configure Login/Register to learn Django authentication. Now when i press Login/Register button (picture1) a popup is displayed. I tried to render loginregister page. <li class="list-inline-item list_s"><a href="{% url 'loginregister' %}" class="btn flaticon-user" data-toggle="modal" data-target=".bd-example-modal-lg"> <span class="dn-lg">Login/Register</span> I've created a views.py file, configured the urls.py file and created an html file in order to display my page and not the popup but unsuccessfully the popup is always displayed. I've configured the following: index.html file <!-- Responsive Menu Structure--> <!--Note: declare the Menu style in the data-menu-style="horizontal" (options: horizontal, vertical, accordion) --> <ul id="respMenu" class="ace-responsive-menu text-right" data-menu-style="horizontal"> <li> <a href="#"><span class="title">Manage Property</span></a> </li> <li> <a href="#"><span class="title">Blog</span></a> </li> <li class="last"> <a href="{% url 'contact' %}"><span class="title">Contact</span></a> </li> <li class="list-inline-item list_s"><a href="{% url 'loginregister' %}" class="btn flaticon-user" data-toggle="modal" data-target=".bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a></li> <li class="list-inline-item add_listing"><a href="#"><span class="flaticon-plus"></span><span class="dn-lg"> Create Listing</span></a></li> </ul> </nav> </div> </header> <!-- Main Header Nav Ends --> <!-- Login/Register Starts --> <!-- Modal --> <div class="sign_up_modal modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div … -
changing models.integerfield() using ajax
it doesn't work even when i put a number for testing in front of device.degree in views.py. its my input and submit button : <div class="col-log-7 px-5 pt-7"> <p>Rooms tempreture:</p> <input type="number" placeholder="degree"> <button type=submit text="submit degree" onclick=update_degree()> </div> ajax : function update_degree() { if (window.XMLHttpRequest) { // code for modern browsers xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("POST", "degree", true); xhttp.send(); }; urls.py : path('degree',views.degree_views,name='degree'), views.py : @csrf_exempt def degree_views(request): device = Device.objects.get(id=1) device.degree = 10 device.save() return HttpResponse() can anyone tell me what should i do ? -
Django migrate showing Operations to perform instead of performing migration in Django v3.1
I had started to upgrade an old web application from django v2.7 to django v3.1 for my academic purpose. manage.py migrate. Then it showed some successful migration. Then I created a super user by manage.py createsuperuser and tried to login to admin. But after entering the successful credential, it showed an 500 server error. I found that admin migration not yet performed. Then I tried manage.py migrate admin,Then the output like this Operations to perform: Apply all migrations: admin Running migrations: No migrations to apply. I tried many result mentioned in different blogs and forums, but did not work. So I am wondering whether it is applicable to django v3.1. Could anyone help me. -
Django: Pass arguments from other form to submit button
I'm building a simple Django app that lets users track stuff for specific days: It records entries with a name and a date using the upper form. <form action="" method="post" style="margin-bottom: 1cm;"> {% csrf_token %} <div class="form-group"> {{ form.entry_name.label_tag }} <div class="input-group"> <input type="text" class="form-control" id="{{ form.entry_name.id_for_label }}" name="{{ form.entry_name.html_name }}" aria-label="new entry field"> {{ form.entry_date }} <div class="input-group-append"> <button type="submit" class="btn btn-primary">Add</button> </div> </div> <small id="{{ form.entry_name.id_for_label }}Help" class="form-text text-muted">This can be anything you want to track: An activity, food, how you slept, stress level, etc.</small> </div> </form> Below the form, there are quick add buttons that let users quickly add a new entry with a specific name. In addition, I'd like to use the date selected in the form above. I.e., if a user sets a date in the upper form but then clicks one of the suggested buttons, it should still use the selected date for adding the new entry. This is what the code for the suggested buttons currently looks like: {% if entry_counts and entry_dict|length > 0 %} <div class="card" style="margin-bottom: 1cm;"> <div class="card-body"> <div class="card-title">Suggested entries</div> {% for name, count in entry_counts.items %} <form method="post" action="{% url 'app:add_entry_with_date' name form.entry_date.value %}" style="display: inline-block;"> {% … -
Django - Selenium - How to brake connection after one iteration of task?
I have simple Django app with integrated Selenium websrcraping. Purpose of app - to fetch images from Reddit and save URLs in database. Task is performed in intervals. My problem is following: First iteration of webscrapping task goes well, but all next are raising error. I am assume that is because previous connection is not aborted. I am using driver.quit() command, but it doesn't seem to work, apparently example of errors in console: urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x00000289D7ADF8B0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=62138): Max retries exceeded with url: /session/6a45df20c47126554c5ef365df554676/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022678CE5D90>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) scrapping script: from selenium import webdriver from selenium.webdriver.chrome.options import Options from .models import Post from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler url2 = 'https://www.reddit.com/r/memes/new/' chrome_driver_path = 'C:/Dev/memescraper/memescraper/static/chromedriver' chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument(" - incognito") webdriver = webdriver.Chrome( executable_path=chrome_driver_path, options=chrome_options ) driver = webdriver def fetch_reddit(): driver.get(url2) meme = driver.find_elements_by_css_selector('[alt="Post image"]') memes = list() for m in meme: memes.append(m.get_attribute("src")) print(m.get_attribute("src")) driver.quit() for m in range(len(memes)): image = … -
Setting Django Allauth as ForeignKey
I'm building an online e-commerce using Django. I want to have my user to log in using social media ( like Facebook and Google). I'm already done doing this using Django Allauth. But the problem is, how can I make it to be foreignkey when placing an order ? Here is my code so far , views.py from django.db import models from django.contrib.auth import get_user_model from products.models import Products User = get_user_model() class Cart(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, verbose_name = 'Customer') item = models.ForeignKey(Products, on_delete = models.CASCADE, verbose_name = 'Item') quantity = models.IntegerField(default=1) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.item.title}' def get_total(self): return self.item.price * self.quantity class Meta: db_table = 'cart' class Order(models.Model): orderitems = models.ManyToManyField(Cart) user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username def get_totals(self): total = 0 for order_item in self.orderitems.all(): total += order_item.get_total() return total It gives me an error when adding items to cart. So how can I do this that wetehr the user is using the default django authentication or their 3rd party accoutn like facebook and google, it will work. -
Add cropper js to django template
I am new to web development. I am trying to learn django. I have managed to come so far. I want my user to upload picture and also be able to crop the picture while uploading. I dont have any problem with img uploading but the results i found for croping is too advanced for me i dont know how to implement them. I have found below example made in django but still couldnt understand the way it works to be able to add to my own project. Any help is appreciated. Please explain to me like i am 5. I am very new to Jquery, css and everything except python. Thanks https://github.com/adriancarayol/django-cropperjs -
nginx serve both django static files and react static files
Im recently trying to impement nginx to link up my django based backend and react based frontend. Here is my nginx config file: upstream api { server backend:8000; } server { listen 8080; location /api/ { uwsgi_pass backend:8000; include /etc/nginx/uwsgi_params; } location /admin/ { uwsgi_pass backend:8000; include /etc/nginx/uwsgi_params; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri /index.html; } location /static { alias /vol/static; } location /static/rest_framework/ { alias /vol/static; } } However, the issue is that my manage.py collect static will place the django static files into /vol/static however, my react build is in /var/www/frontend/ therefore when I try accessing the default / url, it returns a blank page. However, if i remove the location /static { alias /vol/static; } location /static/rest_framework/ { alias /vol/static; } It will serve my my django admin page without any css. How do i resolve this easily without putting both static files in the same directory? -
Heroku: R15 Error Memory quota vastly exceeded when loading large files
So I am new at deploying Heroku applications. I have built a django application that basically reads from a Machine Learning model (1.3GB). This model is stored as a variable via the pickle.load function: model = pickle.load(url_path) I need this model to be accessed frequently in the application. For example, each user has a the possibility to do a prediction over some stocks. When he uses the prediction functionality we will do basic operations on this ML model. After deploying the django application via Heroku, I receive the Heroku: R15 Error Memory quota vastly exceeded, that corresponds in time with the 'model=pickle.load(url_path)' operation. I believe it is expected since the model that will be stored as variable is 1.31GB and the dyno used has 512MB. I would need a way to use this variable frequently (maybe through a third party or anything else) without having to upgrade to Advanced/Enterprise dynos. This would be really appreciated. Kind regards, Marvin -
Struggling to get Django server to run in virtual environment
I'm new to using Django & Python and am having some difficulty trying to get my manage.py application to run in a virtual environment. I am receiving the following errors at the top of my models.py file: I initially thought that this was an issue with pylint not pointing at the right environment (when I switch my Python interpretter to the one outside of the virtual environment, the pylint errors disappear); however, whenever I try to run my server, I get the following error: (.venv) tjmcerlean@LAPTOP-RKLCBQLO:/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce$ python manage.py runserverTraceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce/.venv/lib/python3.8/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? This error appears to suggest that the virtual environment is not activated. However, I activated it using the location of the virtual environment (.venv/bin/activate) and … -
How do I solve a None error in a translation website
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): self.phrase = request.POST.get('letter') translation = self.phrase context = { 'translation': translation } return render(request,self.template_name, context ) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
Genrating django admin and foreignkey error
Here is my model.py : class MireilleUser(models.Model): created = models.DateTimeField( blank=True, editable=False,default=timezone.now) modified = models.DateTimeField( blank=True,default=timezone.now) uuid = models.CharField(blank=True, max_length=48,default='') firebase_id = models.CharField(max_length=256) def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.id: self.created = timezone.now() self.modified = timezone.now() if not self.uuid: self.uuid = str(uuid.uuid4().hex) + str(random.randint(1000, 9999)) return super(MireilleUser, self).save(*args, **kwargs) class MireilleAppSubscription(models.Model): ACTIVE = 'AC' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' STATUS_VALUE = [ (ACTIVE, 'Active'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ('GR', 'Graduate'), ] STRIPE = 'ST' GOOGLE = 'GO' APPLE = 'AP' PLATFORM_VALUE = [ (STRIPE, 'STRIPE'), (GOOGLE, 'GOOGLE'), (APPLE, 'APPLE'), ] created = models.DateTimeField( blank=True, editable=False,default=timezone.now) modified = models.DateTimeField( blank=True,default=timezone.now) uuid = models.CharField(blank=True, max_length=48,default='') mireille_user = models.ForeignKey(MireilleUser,on_delete=models.PROTECT) date_begin = models.DateTimeField(blank=True, editable=True, default=timezone.now) stripe_client_id = models.CharField(blank=True, max_length=48,default='') platform = models.CharField(blank=True, max_length=2,choices=PLATFORM_VALUE) expected_end_time = models.DateTimeField(blank=True, editable=True, default=(timezone.now()+timezone.timedelta(days=8))) is_free = models.BooleanField(default=False) is_vip = models.BooleanField(default=False) promo_code = models.CharField(blank=True, max_length=128, default='') status = models.CharField(max_length=2, choices=STATUS_VALUE, default=ACTIVE) def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.id: self.created = timezone.now() self.modified = timezone.now() if not self.uuid: self.uuid = str(uuid.uuid4().hex) + str(random.randint(1000, 9999)) return super(MireilleAppSubscription, self).save(*args, **kwargs) And here is my admin.py : class MireilleUser_Admin(admin.ModelAdmin): list_display = [field.name for field … -
Populating Django SQL Database
I would like create a database for my images that I could access using django. For the model I want to create something along these lines of class Images(models.Model): Image_loc = models.CharField(max_length = 200) Image_year = models.CharField(max_length = 200) Image_date = models.DateTimeField('date taken') Where image_loc is the image file location and image_year is the year that the image was taken. I would like to populate the database with multiple images. I am new to website design and django and was wondering if anyone knew how would I go about doing this? -
How to select time on my chart js graph on Django?
I'm trying to do a selection on what only will be displayed on my chart, but I don't know what it's called hehe. please help my views.py look like this. class ResView(LoginRequiredMixin, ListView): model = Rainfall template_name = 'home.html' context_object_name = 'res' paginate_by = 8 queryset = Rainfall.objects.all().order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"] = Rainfall.objects.all() return context my chart look like this. <script> (function () { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in qs %}'{{i.timestamp}}',{% endfor %}], datasets: [{ label: 'Rainfall Graph', data: [{% for i in qs %}'{{i.amount}}',{% endfor %}], lineTension: 0, backgroundColor: 'transparent', borderColor: '#c9c5c5', borderWidth: 2, pointRadius: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: false } }] }, legend: { display: false } } }) }()); Now I want to select what to display on my chart. something like a dropdown like this. That I have an option. <select> <option value="hour">Hour</option> <option value="day">Day</option> <option value="month">Month</option> </select> -
Fail to deploy Django application with standard environment to Google Cloud Compute Engine
I deployed my Django app last Wednesday and everything was ok. On the next day, I tried to deploy changes, and the Compute Engine ran into an error: INTERNAL: Internal error encountered. Also, I ran the deployment command today using the same app.yml config and nothing has changed. The same error has occurred. My app.yml: runtime: python37 instance_class: F1 env: standard entrypoint: gunicorn -b :$PORT MyProject.wsgi --timeout 600 beta_settings: cloud_sql_instances: "<project-name>:<region>:<database-name>" handlers: - url: /.* script: auto secure: always redirect_http_response_code: 301 Here are the logs: DEBUG: Running [gcloud.app.deploy] with arguments: [--quiet: "True", --verbosity: "debug", DEPLOYABLES:1: "[u'app.yaml']"] DEBUG: Loading runtimes experiment config from [gs://runtime-builders/experiments.yaml] INFO: Reading [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>] DEBUG: Traceback (most recent call last): File "/opt/hostedtoolcache/gcloud/290.0.1/x64/lib/googlecloudsdk/api_lib/app/runtime_builders.py", line 269, in _Read with contextlib.closing(storage_client.ReadObject(object_)) as f: File "/opt/hostedtoolcache/gcloud/290.0.1/x64/lib/googlecloudsdk/api_lib/storage/storage_api.py", line 303, in ReadObject object_=object_ref, err=http_exc.HttpException(err))) BadFileException: Could not read [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>]. Please retry: HTTPError 404: No such object: runtime-builders/experiments.yaml DEBUG: Experiment config file could not be read. This error is informational, and does not cause a deployment to fail. Reason: Unable to read the runtimes experiment config: [gs://runtime-builders/experiments.yaml], error: Could not read [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>]. Please retry: HTTPError 404: No such object: runtime-builders/experiments.yaml Traceback (most recent call last): File … -
Django-apscheduler fully working example with steps
I was wondering if there’s a fully working ( simple ) example with steps on how to use django-apscheduler?the documentation is really poor. I managed to use apacheduler library but what i like with the django specific one is that it has admin integration. Thanks in advance -
Django image not loading Page not Found Error
I'm new to Django and I'm facing a problem of loading a static file (image). I got 127.0.0.1/:1707 GET http://127.0.0.1:8000/static/css/static/images/background/1.jpg 404 (Not Found) I'm pretty sure that the problem is on the path but I can't understand where this /static/css/ comes from. Could you please help me? My settings.py file: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'evillio/static') ] My index.html file: <!-- First Page with Picture and Search Starts --> <section class="home-one home1-overlay **home1_bgi1**"> <div class="container"> <div class="row posr"> <div class="col-lg-12"> <div class="home_content"> <div class="home-text text-center"> <h2 class="fz55">Find Your Dream Home</h2> <p class="fz18 color-white">From as low as $10 per day with limited time offer discounts.</p> </div> My CSS file: home1_bgi1{ background-image: url('static/images/background/1.jpg'); -webkit-background-size: cover; background-size: cover; background-position: center center; height: 960px; -
How to Solve 'LeadForm' object has no attribute 'save' error in Django?
I am trying to submit data through form, but it's showing me thsi error 'LeadForm' object has no attribute 'save', Please let me know how I can Solve this issue. I am stuck in this from last 4 hours, but still did not find the solution. I have another page in my website where a product page is opens, and there are a form, When user submit the form then his/her information should be store in my database, But i am stuck in this, I submitted lots of forms but I am still unable to resolve this error. Here is my forms.py file... class LeadForm(forms.Form): class Meta: model = Leads exclude = ['lead_for','property_type','status','source','message','user'] fields = ['customer_name', 'customer_email', 'customer_phone'] here is my views.py file code... def leads(request): if request.method == 'POST': form = LeadForm(request.POST) if form.is_valid(): form.save() else: form = LeadForm() return HttpResponse('Fail') here is my urls.py file... path('query/sendquery', views.leads, name='leads'), here is my leads.html file... <form action="{% url 'panel:leads' %}" id="queryform" method="POST"> {% csrf_token %} <div class="chat-group mt-1"> <input class="chat-field" type="text" name="name" id="customer_name" placeholder="Your name" required=""> </div> <div class="chat-group mt-1"> <input class="chat-field" type="number" name="customer_phone" id="customer_phone" placeholder="Phone" required=""> </div> <div class="chat-group mt-1"> <input class="chat-field" type="text" name="email" id="customer_email" placeholder="Email" required=""> </div> <div … -
Django Validators
I have an Order model where I want to verify that every order's quantity doesn't exceed the actual product quantity of the product required, and I wanna achieve this by Django validators.. all of my validators for each app are being saved in a sperate file called valditaors.py now the problem, is how to pass the product model object that the Order model is referring to trough a foreign key field to the validator specified on the quantity field to verify that the product required has enough quantity and that instead of passing actual quantity field value alone. My Order model: class Order(models.Model): product = models.ForeignKey('Product', on_delete=models.RESTRICT, related_name='orders') # I want to pass this product to the same validator((check_quantity_available)) specified on the next field. quantity = models.PositiveIntegerField(validators=[MinValueValidator(1), check_quantity_available]) # in addition to this field value as well My Validator: def check_quantity_available(value): pass # how to get the product instance here throuh the Order model so I may check if it has enough quantity or not -
NoReverseMatch in Django Web application
I have been having a tough time debugging my code as to what mistakes i could have made in my urls.py or views.py or templates but can't figure it out, i would be glad if any could kindly help me out or provide suggestion that could help me out of this. Thanks. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\StaffViews.py", line 450, in question_add return redirect('staff_quiz_update', quiz.pk, question.pk) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\shortcuts.py", line 41, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /staff_quiz_question_add/4/question/add/ Exception Value: Reverse for 'staff_quiz_update' with arguments '(4, 5)' not found. 1 pattern(s) tried: ['staff_quiz_update/(?P<pk>[0-9]+)/$'] VIEWS.PY def question_add(request, pk): # By filtering the quiz by the url keyword argument `pk` and # by the owner, which is the logged in user, we are protecting # this view at the object-level. Meaning only the owner of # quiz … -
User filtering in Django, how to return specific user's data?
Been trying to figure this out for a long time(as in days), but can't understand what to use to return one users "events". A bit new and unfamiliar so would love any help I could get. At the moment I return all users events into the calendar so everyone can go in and see/change other users events. Was therefor wondering if there is any way I can return only the logged inn user's events. All the code I believe is necessary can be seen below. Custom user model (in my account app) Models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) brukernavn = models.CharField(max_length=30, unique=True) telefon = models.CharField(max_length=10) date_joined = models.DateTimeField(verbose_name="dato skapt", auto_now_add=True) last_login = models.DateTimeField(verbose_name="siste innlogging", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['brukernavn', 'telefon'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Models.py class Event(models.Model): butikk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="event", null=True) telefon = models.CharField(max_length=12, default=None) navn = models.CharField(max_length=100) type_service = models.CharField(max_length=200, default=None) beskrivelse = models.TextField() start_time = models.DateField() def __str__(self): return self.navn @property def get_html_url(self): url = reverse('event_edit', args=(self.id,)) return f'<a href="{url}"> {self.navn} </a>' Utils.py: class Calendar(HTMLCalendar): def … -
Django CBV how to handle different pk value on 2 models?
Having difficulty Django CBV DetailView to be able to incoporate with Create,Update& Delete View: I have two models, the 2nd model have a ForeignKey from the first one: How can I differentiate their pk value on their urls.py. I encounter error:404 when trying to detailView of the pk on the 2nd model. Thank you very much. Models: class Rtana(models.Model): rsc_name = models.CharField(max_length=128,unique=True) rsc = models.PositiveIntegerField(unique=True) cc = models.CharField(max_length=32,unique=True) def __str__(self): return '%s %s' % (self.rsc_name , self.rsc) def get_absolute_url(self): return reverse("app7_cbv:details",kwargs={'pk':self.pk}) class Rt(models.Model): rt_name = models.CharField(max_length=128,unique=True) rsc_no = models.ForeignKey(Rtana,related_name="route",on_delete=models.CASCADE,) rt_no = models.PositiveIntegerField(unique=True) def __str__(self): return self.rt_name def get_absolute_url(self): return reverse("app7_cbv:rtdetails",kwargs={'pk':self.pk}) Urls: app_name = "app7_cbv" urlpatterns = [ url(r'^list$',views.Rtana_List_View.as_view(),name="list"), url(r'^(?P<pk>\d+)/$',views.Rtana__Detail_View.as_view(),name="details"), url(r'^create/$',views.Rtana_Create_View.as_view(),name="create"), url(r'^update/(?P<pk>\d+)/$',views.Rtana_Update_View.as_view(),name="update"), url(r'^delete/(?P<pk>\d+)/$',views.Rtana_Delete_View.as_view(),name="delete"), url(r'^rtlist$',views.Rt_List_View.as_view(),name="rtlist"), url(r'^(?P<pk>\d+)/$',views.Rt_Detail_View.as_view(),name="rtdetails"), url(r'^rtcreate/$',views.Rt_Create_View.as_view(),name="rtcreate"), ] views.py: def index(request): return render(request,"index.html") class Rtana_List_View(ListView): model = models.Rtana context_object_name = "rtana_list" class Rtana__Detail_View(DetailView): model = models.Rtana context_object_name = "rtana_detail" template_name = "app7_cbv/rtana_detail.html" class Rt_List_View(ListView): model = models.Rt context_object_name = "rt_list" class Rt_Detail_View(DetailView): model = models.Rt context_object_name = "rt_detail" template_name = "app7_cbv/rt_detail.html" class Rtana_Create_View(CreateView): model = models.Rtana fields = ('rsc_name','rsc','cc') class Rtana_Update_View(UpdateView): model = models.Rtana fields = "__all__" class Rtana_Delete_View(DeleteView): model = models.Rtana success_url = reverse_lazy("app7_cbv:list") class Rt_Create_View(CreateView): model = models.Rt fields = "__all__" -
Django Translation (Translate Database Values)
I'm working on a project and they asked me to make the project multilingual. but they don't have specific languages, and I want to handle this in the simplest and smarter way so I thought if I use django-modeltranslation package it will be good for me. things to know: 1- there are a lot of fields that need to translate into a lot of models and columns. 2- I Im working on drf, the front end in another language. things to do : 1- I want to make dynamic serializers to handle the columns that contain translation. ex(name_en, name_fr, name_ar ...etc.) so the serializer should return the "name" key always, not "name_en" or "name_fr". I made some code and worked fine with me but it will be a headache for me and hard to cover all cases and fields that I need to translate. example code : models.py name = models.CharField(max_length=250, blank=True, null=True) translation.py from modeltranslation.translator import translator, TranslationOptions from .models import Category class CategoryTranslationOptions(TranslationOptions): fields = ('name', 'description') translator.register(Category, CategoryTranslationOptions) request_helper.py def check_language(language): if language: return language else: return "en" def check_accept_language_header(headers): is_lang = False if "Accept-Language" in headers.keys(): is_lang = True if is_lang: return check_language(headers["Accept_Language"]) else: return "en" … -
unique=True always raises exception when used with save(commit=False)
I have a model with two fields f1 and f2. f1 has a unique constraint. I have 2 ModelForms, MF1 and MF2, one for each field. In my view, I render & process the two ModelForms. is_valid() calls on both my_MF1 and my_MF2 are fine. When I save my_MF1.save(commit=False) my_MF2.save() I get a "UNIQUE constraint failed" exception on the second save call. The second call considers that the first one has already created a record with some f1 value. When I save my_MF2.save(commit=False) my_MF1.save() everything works fine. Is this the expected behavior or is this a bug? If it is not a bug, it would be impossible to have both f1 and f2 unique. I am using SQLite. -
djnago Api is Not Working in my Flutter App
My django API is not working flutter App !!! this link is working - 'https://jsonplaceholder.typicode.com/photos' but this link is not working - 'https://shopking24.herokuapp.com/api/products' Error: XMLHttpRequest error. C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 894:28 get current packages/http/src/browser_client.dart 84:22 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1450:54 runUnary C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 143:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 696:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 725:32 _propagateToListeners C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 519:7 [_complete] C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58 at Object.createErrorWithStack (http://localhost:53511/dart_sdk.js:4353:12) at Object._rethrow (http://localhost:53511/dart_sdk.js:37968:16) at async._AsyncCallbackEntry.new.callback (http://localhost:53511/dart_sdk.js:37962:13) at Object._microtaskLoop (http://localhost:53511/dart_sdk.js:37794:13) at _startMicrotaskLoop (http://localhost:53511/dart_sdk.js:37800:13) at http://localhost:53511/dart_sdk.js:33309:9 Please solve my problem...