Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my individual Tweet ID number changing last few digits to "0" when retrieving tweets though Tweepy?
Background: I'm using Tweepy python library to access the twitter API to retrieve cryptocurrency tweets. My application uses a Django backend and a ReactJs frontend. While my web-app will show the retrieved tweet itself, I intend to also have a clickable link available, to re-route to the original on Twitter. My Django Rest Framework API is retrieving the correct Tweet ID number in full when returning a JSON. However, when I'm retrieving from the Rest Framework API to my Frontend, the last few digits of the Tweet ID number is changed to "0". I wonder if this is a default protection measure that Twitter uses? Thanks in advance for all your help! Please see below for more clarity under "bitcoin_tweet_link": Django Rest API: Front-End of Website: App.js: <div className="center-column-tweet"> <div className="item-row-tweets"> <div className="left"> <span><b>@{tasks.bitcoin_tweet_user}</b><br/><br/>"{tasks.bitcoin_tweet}"<br/><b>Link:</b> https://twitter.com/twitter/statuses/{tasks.bitcoin_tweet_link}</span> </div> </div> </div> -
Django add fields to createsuperuser command
I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the createsuperuser command to query once for the user table and once for the residence table. This could then look like this: C:\Users\Project>python manage.py createsuperuser username: input firstname: input lastname: input password: ***** country: input city: input street: input -
How do I validate that a user is at least 13 years old?
I have created a login and registration app in Python for use with Django and I have been using it in a few different projects. My only problem trying to apply it to some projects is I can't figure out how to make sure a user can only register if they are at least 13 years old. This is my models.py and what I have imported for the validations. from django.db import models from datetime import date, datetime import re import bcrypt class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=150) birthday = models.DateField() password = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() This is the only validation I have accompanying the birthday input so far. I have other validations, but this is the only one pertaining to birthday. def registration_validator(self, post_data): errors = {} user_birthday = datetime.strptime(post_data['birthday'], '%Y-%m-%d') if user_birthday > datetime.today(): errors["release_date"] = "User birthday must be in the past!" return errors_login My views.py that handles processing the registration. def process_registration(request): errors = User.objects.registration_validator(request.POST) if len(errors) > 0: for key, value in errors.items(): messages.error(request, value, extra_tags='register') return redirect('/') else: first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] birthday = request.POST['birthday'] pw_hash = … -
How to solve from django.utils.importlib import import_module ImportError: No module named importlib
Currently I am upgrading my old Django project from django 1.8 to django 1.9 and current my python version is 2.7.12 and i am getting this error File "/home/projectfolder/myproject/local/lib/python2.7/site-packages/social_auth/models.py", line 4, in <module> from django.utils.importlib import import_module ImportError: No module named importlib The same errors i am getting in different paths.For example File "/home/projectfolder/myproject/local/lib/python2.7/site-packages/social_auth/utils.py", line 4, in <module> Now my doubt is should we replace this line - "from django.utils.importlib import import_module " as "from django.utils.module_loading import import_module" in all the paths Or is there any other alternative to get rid of this issue ? -
Make add_action visible to only one model in Django
This is my models.py from app named article from django.contrib import admin from .models import Article, Group from django.contrib import messages class ArticleAdmin(admin.ModelAdmin): def publish_selected_articles(modeladmin, request, queryset): queryset.update(publish_status=True) messages.success(request, "Selected Record(s) Marked as Published") admin.site.add_action(publish_selected_articles, "Publish selected articles") admin.site.register(Article, ArticleAdmin) This code adds action of Publish selected articles to all models. Well, the docs says the same. See here What I want is to have Publish selected articles action button visible only to this this class (i.e. ArticleAdmin). I could also use disable_action as docs shows. I have 5 action buttons and about 10 Apps. So writing disable_action about 50 times does not seem to be a good idea. And what if I some other developer develops more apps in future. Is there a easy solution for this? How can I make add_action visible to specific class in Django model ? Any help is appreciable. Thanks in advance. -
Why django remove GET params from Url? [closed]
I have '^(?P<slug>[\w-]+)/$' url pattern. When I visit page localhost/app/example_slug/?aaa=bbb, I can access parameter inside my class based view via self.request.GET.get('aaa'), but in browser's address bar all GET params are removed. Can't understand the reason. -
Django queryset with Q gives wrong length
I'm struggling with or query. It give me weird output. In models file i have as shown below: class Server: addres_ip=models.GenericIPAddressField() class Interface: addres_ip=models.CharField(max_length=15,default='127.0.0.1',blank=True) server=models.ForeignKey(Server,default=None,blank=True,null=True,on_delete=models.CASCADE) In db i have added a Server object with addres_ip='10.0.10.11' and with his Interface with addres_ip='10.1.1.2'. When i query: Server.objects.filter(addres_ip='10.0.10.11') I get 1 result and it's correct Interface.objects.filter(addres_ip='10.0.10.11') I get 0 results and it's correct as well but when I query: Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11')) i get 7 results........ Am i missing something ? there should be 1 result ..I think but not sure right now ? Thank you in advance -
Check if request.POST field is empty
I have a form that may be submitted with some fields as blank/empty values, but when I run: if request.POST['field']: it always returns true, even if the field has not been filled in, how can I check if a field has been completed or left blank? -
I'm following Python Fullstack by Perrian data facing error with Faker libararies
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from faker import Faker import os os.environ.setdefault('DJANGO_SETTINGD_MODULE','first_project.settigs' ) import django django.setup() # rand numbers import random from first_app.models import AccessRecord,WebPage,Topic error :- facing django.setup() error file structure:- file Structure total code:- code -
fetching specific data from JSON with python
I want to fetch specific data form JSON . Right now I can fetch all of the data and convert it into JSON format. But I only want to fetch "home_team" and "away_team" of all the sets. My code to fetch all of the data is:` import json import requests reap = requests.get('https://app.sportdataapi.com/api/v1/soccer/matches?apikey=64572f90-88d6-11eb-8a43-7106c933e99d&season_id=496&date_from=2020-09-19&fbclid=IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4') data = reap.json() print(data) And my JSON data is: {'query': {'apikey': '64572f90-88d6-11eb-8a43-7106c933e99d', 'season_id': '496', 'date_from': '2020-09-19', 'fbclid': 'IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4'}, 'data': [{'match_id': 139415, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, 'name': 'Regular Season'}, 'group': {'group_id': 222, 'group_name': 'Bundesliga'}, 'round': {'round_id': 18564, 'name': '1', 'is_current': None}, 'referee_id': 433, 'home_team': {'team_id': 3993, 'name': '1. FC Union Berlin', 'short_code': 'UNI', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2819.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'away_team': {'team_id': 4075, 'name': 'FC Augsburg', 'short_code': 'FCA', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2814.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'stats': {'home_score': 1, 'away_score': 3, 'ht_score': '0-1', 'ft_score': '1-3', 'et_score': None, 'ps_score': None}, 'venue': {'venue_id': 1870, 'name': 'An der alten Forsterei', 'capacity': 22012, 'city': 'Berlin', 'country_id': 48}}, {'match_id': 139451, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, … -
post function is called twice django python
I am facing problem wherein post function of class view in django is called twice. I am doing a long operation in one of the sub functions. So after some time, post is again called. Please help me. How can I make it run once only. Thanks. -
i have a dynnamic html table so how can i add multiple rows with same name and id+1 in django database its only added first row in database
i have javascript to increment id as a +1 so how can i add those html rows into database i am trying to add those dynamiclly rows which is genrated by javascript but i am not able to add those rows please help me models.py class New_Order(models.Model): sno = models.AutoField(primary_key=True) hscode = models.CharField(max_length=50) Product_Category = models.CharField(max_length=50) Finish = models.CharField(max_length=50) Edge = models.CharField(max_length=50) Product_Name = models.CharField(max_length=50) Product_Nomenclature = models.CharField(max_length=50) Product_Type = models.CharField(max_length=50) Length = models.CharField(max_length=50) Breadth = models.CharField(max_length=50) Thickness = models.CharField(max_length=50) Patio_Pack = models.CharField(max_length=50) Crate = models.IntegerField() Measure = models.IntegerField() Measure_Unit = models.IntegerField() Pcs_or_Crate = models.IntegerField() Crate_Start = models.IntegerField() Crate_End = models.IntegerField() Crate_Buffer = models.IntegerField() Container_Qty = models.IntegerField() Percentage = models.IntegerField() Desc = models.CharField(max_length=50) Price = models.IntegerField() def __str__(self): return self.hscode i am trying through name but all name are same in dynamiclly table so those values not adding in database can you all please guide me how its possible views.py def pro(request): prod = Product_Catagory.objects.all() any = Finishe.objects.all() edg = Edge.objects.all() prodn = Product_Name.objects.all() prodnn = Product_Nomenclature.objects.all() prodt = Product_Type.objects.all() len = Length.objects.all() bre = Breadth.objects.all() thick = Thicknes.objects.all() pat = Patio_Pack.objects.all() context = {'prod':prod, 'any':any, 'edg':edg, 'prodn':prodn, 'prodnn':prodnn, 'prodt':prodt, 'len':len, 'bre':bre, 'thick':thick, 'pat':pat} if request.method == "POST": hscode = … -
How to use JQV map in Django?
I want to create a JQV country web for my dashboard. I have a Customer model and this model has a country field. This field is connected with a foreign key and I can get country codes and JQV map is accepting country codes. I created an array in my views and when I print it works. But when I put in the data field of the map chart, does not show anything. How can I fix it? models.py class Customer(models.Model): ... country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) class Country(models.Model): ... country_code = models.CharField(max_length=5) views.py def approval_context_processor(request): ... countries_iso = Customer.objects.values_list('country__country_code', flat=True).distinct() ... for cn in countries_iso: arr.append(cn) print(arr) // it works truely. else: pend_list = 0 submit_list = 0 context = { ... 'arr': arr } return context dashboard.html ... <div class="mapcontainer"> <div id="map-example" class="vmap" style="height: 400px"></div> </div> <script> var country_list = [] {% for country in arr %} country_list.push( '{{ country }}' ) {% endfor %} window.alert(country_list) //It works truely $('#map-example').vectorMap( { map: 'world_en', backgroundColor: 'transparent', borderColor: '#fff', borderWidth: 2, color: '#e4e4e4', enableZoom: true, hoverColor: '#35cd3a', hoverOpacity: null, normalizeFunction: 'linear', scaleColors: ['#b6d6ff', '#005ace'], selectedColor: '#35cd3a', selectedRegions: [country_list], showTooltip: true, onRegionClick: function(element, code, region) { return false; }, onResize: … -
Django Template comparing two lists of equal size
I have two lists of equal sizes like so: change_list = ['none', 'M', 'D', 'none] print_list = ['examples', 'app.py', 'list.fr', 'template'] I pass them through the view and I need to know what the value is on the first list so I can display the elements of the second one with a different color according to what's on the first list. For example, I need to display 'app.py' as orange in the template due to the 'M' in the first list. I've searched around and I have no idea how to do this. I tried to pass the len of the list as a range to the view like this: {% for i in len%} {% if changes_list.i == "M" %} <p style="color:orange;"> {{print_list.i}}</p> {% endif %} {% endfor %} But it didn't work. I'm not sure if I formulated the question correctly but I wasn't exactly sure how to explain this. Thank you in advance. -
django Rest Framework - extending user model
halo i'm having issue using django-restframework to extend user model with OneToOnfield, below is my codes and error message i'm getting a TypeError: _create_user() got an unexpected keyword argument 'school_name' shool when i try to create the user ###profile-serializer class schoolProfileSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='pk', read_only=True) parser_classes = (MultiPartParser, FormParser, ) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) date_established = serializers.DateField(format=None,input_formats=None) class Meta: model = Profile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'level', 'motto') def create(self, validated_data): if 'profile' in validated_data: user_data = validated_data.pop('profile') user = CustomUser.objects._create_user(**validated_data) Profile.objects.update_or_create(user=user, **validated_data) return user ###profile-view class CreateProfileView(generics.CreateAPIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = Profile.objects.all() permission_classes = [permissions.AllowAny] profile-model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) school_name = models.CharField(max_length=255) address = models.TextField() school_phone_number = models.CharField(max_length=25) school_email = models.EmailField() motto = models.CharField(max_length=255) @receiver(post_save, sender=CustomUser) def create_school_profile(sender, instance=None, created=False, **kwargs): if created: Profile.objects.get_or_create(user=instance) errorr-msg Traceback (most recent call last): File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) … -
How to validate a request with nested json objects in django rest framework using serializers?
I have following request. { "customer_details": { "id": 6, // either id or below fields should be present to create new customer in database "name": "Name", "email": "email@example.com", "mobile": "1234567890", "company": "Company Name" // not mandatoy }, "delivery_address": { "id": 7, // either id or below fields should be present to create new address in database "title": "Delivery Address Title 1", "street": "Delivery Address Street 1", "suite": "Delivery Address suite 1", // not mandatoy "city": "Delivery Address city 1", "zipcode": "zipcode1", "county": "Dade", "state": "Delivery Address state 1" }, "billing_address": { "id": 8, // either id or below fields should be present to create new address in database "title": "Billing Address Title 1", "street": "Billing Address Street 1", "suite": "Billing Address suite 1", // not mandatoy "city": "Billing Address city 1", "zipcode": "zipcode2", "county": "Billing Address county 1", "state": "Billing Address state 1", "payment_method": "Cheque" } } How can I validate the above request using django serializers? -
Upvote action is performing for all the cards django
I am implementing a upvote/downvote system for my website. But while upvoting a particular project all the projects are getting upvoted. html code <div style="margin-left: 10px;margin-right: 10px;"> <div class="card-columns" > {% for marking in marking_maestro %} <div class="card "> <img class="card-img-top" src="" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" name="title">{{marking.product_title}}</h5> <h5 class="card-title" name="title">{{marking.id}}</h5> <p class="card-text">Random text</p> <br> <div class="row" > <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-modal-lg-1">View more</button> &emsp; <a href="{% url 'invest' pk=marking.id %}";><button type="submit" class="btn btn-primary" data-toggle="modal" >Invest</button></a> </div> <br> <form method="POST" id="post-invest"> {% csrf_token %} <div class="row" > <input class="btn btn-outline-secondary" id="upvote_button" type="submit" name="upvote" value="upvote"> </div> </form> </div> <!-- for upvote --> <script> // upvote $(document).on('submit', '#post-invest',function(e){ e.preventDefault(); // amount = $('input[name="amount"]').val(); console.log("Upvote initiated="); var comment = "upvote"; $.ajax({ type:'POST', url:"{% url 'upvote' pk=marking.id %}", data:{ comment : comment, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(xhr, errmsg, err){ window.location = "brand" }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } }); }); </script> </div> <div class="modal fade bd-modal-lg-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <center><h4>Title</h4></center> <img class="img-fluid" src="{% static 'assets/img/about/about.png' %}"> <br> <center><h4>Branding Video</h4></center> <div … -
How can a call a postgresql function from Django for live server?
Here is my postgresql function in server. CREATE OR REPLACE FUNCTION test.fn_wallet_statement(wallet text, s_date date, e_date date, p_table_name text, b_name text DEFAULT 'unknown'::text) RETURNS void LANGUAGE plpgsql AS $function$ declare v_sql_bank text :=''; v_sql1 text :=''; v_sql2 text :=''; v_sql_tmp text :=''; v_sql2_v2 text :=''; v_sql3 text :=''; ---------------------------------- v_bank text:=''; v_account_id numeric; v_closed_date date; v_closed_date_tmp date; v_closed_balance numeric; v_wallet varchar(12) := wallet; v_start_date timestamp := s_date; v_end_date timestamp := e_date; v_table_name text := p_table_name; v_excute_ind boolean; -- EXCEPTION v_error_msg text; begin v_excute_ind := true; v_end_date := v_end_date + interval '1 day'; --***********************************TESTING******************************************* raise notice 'DONE 1'; insert into test.test_user (username, wallet, current_balance) values ('user15', '01011991', 999999); raise notice 'DONE 2'; --****************************************************************************** EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS v_error_msg = PG_EXCEPTION_CONTEXT; END; $function$ ; Here is my python code in Django Portal. # POINTER @login_required(login_url = 'login') def wallet_statement(request, submit_type): run_proc_query = '''select * from test.fn_wallet_statement('017XXXXXXXXX','2020-11-11','2021-03-12','test.wallet_statement_portal_017XXXXXXXXX_007','BANK');''' run_proc_cursor = connection.cursor() run_proc_cursor.execute(run_proc_query) result = run_proc_cursor.fetchall() run_proc_cursor.close() I am unable to call the postgresql function from django. I checked that the function is not calling. But normal select query from a table working fine. Note: the same query in the DBeaver (IDE) is working and calling the function perfectly. -
different number of records in django pagination pages
I'm trying to paginate with different things to maximize elements, on the first page (5) and on all the others (maximum 6). I do like in this answer class MyPaginator(Paginator): def __init__(self, **kw): self.deltafirst = kw.pop('deltafirst', 0) Paginator.__init__(self, **kw) def page(self, number): number = self.validate_number(number) if number == 1: bottom = 0 top = self.per_page - self.deltafirst else: bottom = (number - 1) * self.per_page - self.deltafirst top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.object_list[bottom:top], number, self) from django.core.paginator import Paginator from django.core.paginator import EmptyPage from django.core.paginator import PageNotAnInteger class NewsView(ListView): model = News template_name="mysite/news.html" paginate_by = 5 def get_context_data(self, **kwargs): context = super(NewsView, self).get_context_data(**kwargs) all_news = News.objects.all().order_by("-date_news") paginator = MyPaginator(all_news, self.paginate_by,deltafirst=1) page = self.request.GET.get('page') try: file_exams = paginator.page(page) except PageNotAnInteger: file_exams = paginator.page(1) except EmptyPage: file_exams = paginator.page(paginator.num_pages) context['all_news'] = file_exams return context But I get an error and I can't figure out what I'm doing wrong. The error itself paginator = MyPaginator(all_news, self.paginate_by,deltafirst=1) TypeError: __init__() takes 1 positional argument but 3 were given -
How Does Django Manager Orchestrate QuerySet?
This is a follow-up question from this post. For the sake of completeness and self-containment, I will include all necessary bits in this question. Consider a very simple example: # Models class Cart(models.Model): name = models.CharField(max_length=20) class Item(models.Model): name = models.CharField(max_length=20) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) # Execution class Test(TestCase): @classmethod def setUpTestData(cls): # Save a new cart c = Cart(name="MyCart") c.save() # Save two items to the cart t = Item(name="item1", cart=c) t.save() Item.objects.create(name="item2", cart=c) def simpleTest(self): i = Item.objects.get(id=2) # <--- breakpoint # Do something, but not important for this question I am using PyCharm to try to understand the inner workings of Django. If we put a breakpoint at the marked line and step into the method call get(). After we get a Manager from __get__ in ManagerDescriptor (due to .objects), the execution now goes to this class method in BaseManager: @classmethod def _get_queryset_methods(cls, queryset_class): def create_method(name, method): def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) # <--- Starts here manager_method.__name__ = method.__name__ manager_method.__doc__ = method.__doc__ return manager_method The execution stops at the marked line above. If we step into it, get_queryset() is first called, which returns a new QuerySet object, as expected. Note that the new QuerySet … -
How do I allow only the owner of a an item to do something with it?
Could anyone explain to me how to do it? I've been trying for a while without managing to do it. I am just trying to restrict permissions so that not anyone with the right link can edit/delete a particular object models.py: class Items(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=256) description = RichTextField(blank=True, null=True) url = models.URLField(null=True, blank=True) image = models.ImageField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name and views.py class SiteList(ListView): model = Items class SiteUpdate(LoginRequiredMixin, UpdateView): model = Items form_class = SiteUpdateForm success_url = reverse_lazy('portfolio:sitelist') class SiteDelete(DeleteView): model = Items success_url = reverse_lazy('portfolio:sitelist') -
django template tag add double quotes to the url generated
In index.html : <a href={% url 'clm:clmmap' %}" class="button">Empezemos</a> A click in the button "Empezemos" generates a URL http://localhost:8001/clm/map/%22 (not found error is launched) when it should be http://localhost:8001/clm/map/ , without the %22 (double quote). the urls.py: urlpatterns = [ path('map/', CLMMapView.as_view(), name='clmmap'), and the views.py: class CLMMapView(TemplateView): template_name = 'clm.html' def get_context_data(self, **kwargs): ... so, why a double quote is added to the URL? -
No module named '_pywrap_tensorflow_internal' and website does not work
I try to import Tensorflow, but I get this error: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(file)]) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper import _pywrap_tensorflow_internal ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#1>", line 1, in import tensorflow File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow_init_.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python_init_.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(file)]) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line … -
Merge two redundant models in Django
I'm working on an online shop at the moment. The shop is written in Django, and was programmed by another person, so I spent days trying to make sense of what he did. At the moment the shop sells only two articles, on two different pages (meaning they have to be bought separately), so the shop is heavily oriented towards this situation. The problem is, the shop's owner expressed his interest in selling everything in one page in the near future, and in adding more products. And that's where my problems start. The model structure was something like this (extremely simplified): class Category1(BaseModel): name = models.CharField(max_length=32) class Category2(BaseModel): name = models.CharField(max_length=64) class Price1(BaseModel): category = models.ForeignKey(Category1, on_delete=models.CASCADE) price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class Price2(BaseModel): category = models.ForeignKey(Category2, on_delete=models.CASCADE) price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class Order1(BaseModel): [personal information fields] class Order2(BaseModel): [personal information fields] class Article1(BaseModel): price = models.ForeignKey(Price1, on_delete=models.CASCADE) order = models.ForeignKey(Order1, on_delete=models.CASCADE, related_name='articles') class Article2(BaseModel): price = models.ForeignKey(Price2, on_delete=models.CASCADE) order = models.ForeignKey(Order2, on_delete=models.CASCADE, related_name='articles') There is much more than this, of course, but this should be enough to show the relationships between the models. The complete structure of course makes more sense than this one. … -
Bootstrap modal not showing (taken from the official website) using Django
I have the following HTML code in Django template. I used the example from Boostrap website to create a button that shows a modal ,however, when I press the button, nothing happens. I'm not sure why nothing happens and also no error shows in the console. My 'static' folder contains: bootstrap.min.css and bootstrap.min.css.map. <!doctype html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Dashboard</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/"><img src="{% static "img/logo.png" %}" style='max-width:100px'></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link" href="{% url 'admin:logout' %}?next=/" tabindex="-1" aria-disabled="true">Instances</a> </div> </div> </nav> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> New Instance </button> <button type="button" class="btn btn-danger">Delete Instance</button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> This is a test! </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </body> </html>