Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if record with multiple fileds exists in database before saving the form
I have this model: class Venue(models.Model): venue_name = models.CharField(max_length=50) venue_city = models.CharField(max_length=50) and I have a form where users input the venue name and city. I'd like to check if a record already exists in the database, with both fields already taken in the same record. There could be the same venue name in different cities for example. I've added a check in my forms.py: class VenueForm(forms.ModelForm): class Meta: model = Venue fields = ['venue_name', 'venue_city', 'venue_country'] def save(self, commit=True): venue = super(VenueForm, self).save(commit=False) venue_name = self.cleaned_data['venue_name'] venue_city = self.cleaned_data['venue_city'] if Venue.objects.filter(venue_city=self.cleaned_data['venue_city']).exists() and Venue.objects.filter(venue_name=self.cleaned_data['venue_name']).exists(): # I know this doesn't work: it's as far as I can get. logger.error(venue_name + ' already exists') if commit: venue.save() return venue and, finally, my view.py: def venue_add_view(request): form_venue = VenueForm(request.POST or None) if form_venue.is_valid(): form_venue.save() context = { 'form_venue': form_venue, } return render(request, "venue-add.html", context) As it is now it successfully checks if name or city already exist. What I want to do is ask the database if they exist in the same record. How can I do that? -
Creating a QuerySet manually in django from list of ids
Let's say I have a model My_model and I have a list of ids for this model; my_ids = [3,2,1,42] Now I want to get a QuerySet with the My_model.objects of the ids. I already found this solution, but it doesn't work for me, because I want to have the objects in the QuerySet in the same order as the ids in my_ids. How can I turn a list of ids in a QuerySet in Django,Python? thx for your help and stay healthy! -
Django Rest Framework : string return b'' string
I am using Django Rest Framework and I create few API calls. API calls return primarily data from model objects. All other API work normally but one parameter in JSON in one API return b'' string instead of a normal string. I can't found a difference between others and this one. What could be the problem? class ApiVisit(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) @logging__time def get(self, request, pk, call_type): r = {} user = self.request.user ... notes = .... r['notes'] = notes return Response(r) From Postman I get -
InvalidQueryError: Cannot resolve field "point" MongoEngine
I am using below code to fetch nearest location from PointField using MongoEngine restra = ResLocation.objects(point__near=[lat, lon], point__max_distance=distance) all_res = [] for res in restra: all_res += [ { "res_name": res.res_name, "res_address": res.res_address } ] While I am getting below error InvalidQueryError: Cannot resolve field "point" How can I solve this please suggest -
How to update template variable in Django
I want to update value of 'log_data_full' from django template, i have extracted updated value in json from AJAX, i dont' want to refresh the page . i just want to update table view with updated value. Is that possible? <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>=Id</th> <th>Category</th> <th>Fee</th> <th>Search</th> </tr> </thead> <tbody> {% for log in log_data_full %} <tr> <td>{{ log.Id }}</td> <td>13</td> <td>100</td> <td>{{ log.search }}</td> </tr> {% endfor %} </tbody> </table> AJAX query $.ajax({ url: "/filter", type: "POST", data: { from_date:from_date, to_date:to_date, csrfmiddlewaretoken: '{{ csrf_token }}', }, success : function(json) { debugger if(json != 'error'){ var res = JSON.parse(json); } else{ alert('Server Error! Could not get data'); } }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); How to update value by of template variable 'log_data_full'? -
Django get_current_site and build_absolute_uri always say the site is localhost
This is a Django website being tested via the little server that comes with Django: python manage.py runserver 8080 The testing client comes in from a browser running on a machine on an external network. I.e. the browser is not running on the server, but rather is running on a desktop and the requests come in over the Internet. A request would have a typical form of https://sub.awebsite.com/path An ajax POST view incorporates a vendor call that you might recognize: class view_class ... def post(self, request) ... new_session = stripe.checkout.Session.create( api_key=djstripe.settings.STRIPE_SECRET_KEY ,line_items=[item] ,payment_method_types=['card'] ,success_url='https://a.awebsite.com/path?session_id={CHECKOUT_SESSION_ID}' ,cancel_url='https://a.awebsite.com/other_path' ) Note the last two arguments are embedding literal URI strings into the website. To python and Django those do not have any special meaning. They are just strings. However later the client will use them to redirect back to awebsite. This literal encoding is really a problem because the site changes depending on who is testing it or if it has been released. I would much rather use the functions build_absolute_uri, or get_current_site, to build those strings. However these functions just print 'localhost'. E.g. I put these two print statements just above the function call to stripe.checkout.Session.create: print("get_current_site: ", get_current_site(request)) print("post absolute uri: ", … -
Chart function suggestions
hope you are doing well ! I want to create Charts based on my models , I want you to advice me some chart ideas , I couldn't figure out what should I put in my view function can you help me out PS : I already used some simple models and the charts was quite easy but those models are so hard I hope you can advice me from django.db import models # Create your models here. class Country(models.Model): Country = models.CharField(max_length=100) def __str__(self): return '{} '.format(self.Country) class Reason(models.Model): Reason_cd = models.IntegerField(blank=True) Reason_NM = models.CharField(max_length=100, blank=True) def __str__(self): return '{}'.format(self.Reason_NM) class Mesure(models.Model): Mesure_cd = models.IntegerField(blank=True) Mesure_NM = models.CharField(max_length=100,blank=True) def __str__(self): return '{}'.format(self.Mesure_NM) class Client(models.Model): last_name = models.CharField(max_length=250) first_name = models.CharField(max_length=250) Adresse = models.CharField(max_length=560) city = models.CharField(max_length=100) code_postal = models.IntegerField() phone number = models.IntegerField(blank=True,null=True) mail = models.CharField(max_length=100) def __str__(self): return '{}, {}'.format(self.last_name,self.first_name) class Delivery_Agent(models.Model): last_name = models.CharField(max_length=250) first_name = models.CharField(max_length=250) def __str__(self): return '{}, {} '.format(self.last_name,self.first_name) class Office(models.Model): office_cd = models.CharField(max_length=10) office_NM = models.CharField(max_length=50) def __str__(self): return '{}, {} '.format(self.office_cd,self.office_NM) class Mail_item_Event(models.Model): mail_item_fid = models.CharField(max_length=36) Event_cd = models.IntegerField(auto_created=True,unique=True) #Event code office_Evt_cd = models.ForeignKey(Office, on_delete=models.CASCADE, related_name='office_Evt') Date_Evt = models.DateTimeField() Date_Capture = models.DateTimeField() Next_office = models.ForeignKey(Office, on_delete=models.CASCADE, related_name='Next_office') def __str__(self): return '{}'.format(self.Event_cd) … -
Upload files from Host Django application to the Apache server on virtual box
I want to upload encrypted file from Django application which is running on my windows 10 machine to the Apache server created on Ubuntu in virtual box. So as to make it a cloud server for my project. so how i can achieve it and other ideas for related to the creating cloud server are also appreciated. As of my project is to compare the encryption algorithm for cloud computing , so i want to upload those file on Ubuntu server.Any ideas related to implementation of this are also appreciated. -
TypeError :ModelBase object argument after ** must be a mapping, not list
I'm trying to make embedded models using djongo framework that help me to connect to mongodb and it gives me error when i want to add it in admin views This is my models in tests.py from djongo import models from django import forms class Logauth(models.Model): date = models.CharField(max_length=50) name = models.CharField(max_length=50) server = models.CharField(max_length=50) message = models.CharField(max_length=50) class Meta: abstract = True class LogauthForm(forms.ModelForm): class Meta: model = Logauth fields = ( 'date', 'name', 'server', 'message' ) class Serveruser(models.Model): host = models.CharField(max_length=50) port = models.CharField(max_length=10) userServer = models.CharField(max_length=50) pwdServer = models.CharField(max_length=50) logs = models.EmbeddedField( model_container=Logauth, model_form_class=LogauthForm ) class Meta: abstract = True class ServeruserForm(forms.ModelForm): class Meta: model = Serveruser fields = ( 'host', 'port', 'userServer', 'pwdServer', 'logs' ) class UserSv(*models.Model): usernameSv = models.CharField(max_length=50) pwdSv = models.CharField(max_length=50) emailSv = models.CharField(max_length=50) servers = models.EmbeddedField( model_container=Serveruser, model_form_class=ServeruserForm ) and this is my admin.py from django.contrib import admin from p01.tests import UserSv admin.site.register(UserSv) when i try to add, it gives me this error TypeError at /admin/p01/usersv/add/ ModelBase object argument after ** must be a mapping, not list -
Apache2.4.43/mod_wsgi4.7.1/Python3.7/Django2.2.9 Windows10 infinite loope
This issue appeared when I upgraded my Django app to Python3.7/Django2.2.9: I'm no more able to get it loaded by Apache => I have no errors, only an infinite "waiting for server". I checked for 2 days all Apache, wsgi & Django settings. I compared the Apache log file with the old one, every thing is OK. It seems to me that mod_wsgi module doesn't load the Django APP, but I don't understand why??? The server responds only When I insert an error in the Django settings (for exp. a false ALLOWED_HOSTS), in this case I can get the Django debug interface. I'will be grateful if you can help NB: OS => Windows10 -
select tag is shown with a scroll bar
I am using select as a language switcher for my website but it is not shown correctly and whatever I do in the css file nothing seems to work. I want it to show as a regular select and I can't use drop-down button as it will redirect me to another html page which I don't want... Can any one please tell me what should I do document.getElementById("selectLanguage").onclick = function () { document.getElementById("languageForm").submit(); }; .nice-select { overflow-y: visible; -webkit-tap-highlight-color: transparent; background-color: #fff; border-radius: 5px; border: solid 1px #e8e8e8; box-sizing: border-box; clear: both; cursor: pointer; display: block; float: left; font-family: inherit; font-size: 14px; font-weight: normal; height: 42px; line-height: 40px; outline: none; padding-left: 18px; padding-right: 30px; position: relative; text-align: left !important; -webkit-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; white-space: nowrap; width: auto; } .nice-select:hover { border-color: #dbdbdb; } .nice-select:active, .nice-select.open, .nice-select:focus { border-color: #999; overflow-y: scroll; } .nice-select.disabled { border-color: #ededed; color: #999; pointer-events: none; } .nice-select.disabled:after { border-color: #cccccc; } .nice-select.wide { width: 100%; } .nice-select.wide .list { left: 0 !important; right: 0 !important; } .nice-select.right { float: right; } .nice-select.right .list { left: auto; right: 0; } .nice-select.small { font-size: 12px; … -
Need help accessing the pk for a category_count title please help dango
So I have a category widget that uses a view function to count the number of posts under a certain category and list the titles and the count. I have the title as a link and want to link to my category detail page but since its just a title and not the actual category object I can't seem to figure out what to put in the href in the html. Please help. Model: class Category(models.Model): title = models.CharField(max_length=20) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title View: def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset HTML: {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="????????????????" class="ntd"> {{ cat.categories__title }} </a> <span>{{ cat.categories__title__count }}</span> </div> <hr/> {% endfor %} -
how to create query to list categories in django
i got this in my view.py and want to list all categories def home(request): category = Category.objects.all() context = { 'category': category, } return render(request, 'courses/index.html', context) model.py class Category(models.Model): title = models.CharField(max_length=30, null=True) slug = models.SlugField(max_length=30, unique=True) class Course(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=30) slug = models.SlugField(max_length=30, unique=True) but im getting this output from print : <QuerySet [<Category: Courses>, <Category: Computers>]> can someone help me with this -
Losing data when overriding post method in UpdateView
I wanted to use the same UpdateView with two different templates for 2 separate tasks: Update couple of CharFields Delete instances of related model I pass it different templates in urls.py and override post method like this: def post(self, request, *args, **kwargs): self.object = self.get_object() uploads = Upload.objects.filter(press=self.object) marked_uploads = request.POST.getlist('marked_upload', None) if marked_uploads is not None: for upload_id in marked_uploads: upload = uploads.get(id=upload_id) upload.file.delete(save=True) upload.delete() return super(PressUpdateView, self).post(request, *args, **kwargs) The problem is this: because i don't render CharFields in second template every time i call POST function from my second template, the values in them get erased. How do i correctly override post method so it doesn't happen. PS I know i can simply add <div style="display:none;">{{ form.as_p }}</div> to the form in my second template, but i want to know how to do it in post. -
My live Django website works fine, but my local repo is broken
DM Why does my working website not work from local clone? 0 Daniel Mark · Lecture 56 · 7 minutes ago Hi there, So I have my website running and am generally happy with it. I want to do some updates (add commenting to my blog app and also fix the link from main page to blog). However the website pulled from git does not work locally (error messages at bottom of message). I have had this problem since deleting some image files from the local media (these were my dummy images "uploaded" via the admin page) I have checked using git push from the website and git pull locally (and even with a fresh git clone locally to another folder). The live website on the server is running the latest code (I restarted nginx and gunicorn and even the whole server using sudo reboot). I tried python manage.py flush to blitz the local database, but I cannot recreate one locally. I created a new directory on my local machine and did a git clone, made a virtual env and did a pip install of my requirements. So my question is why is this happening? I don't want to start … -
Is there anyway to upload multiple image in my blog?
''' views.py ''' I can upload single image in my db. I want to upload multiple image. Is their anyway to solve the problem.helphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelp class IndexView(View): def get(self, request, *args, **kwargs): slide = Slider.objects.all() blogslide = BlogSlider.objects.all() post_form = PostForm() paginator = Paginator(blogslide, 3) page = request.GET.get('page') blogslide = paginator.get_page(page) return render(request, 'index.html', {'slide': slide, 'blogslide': blogslide, 'post_form': post_form}) def post(self, *args, **kwargs): post_form = PostForm(self.request.POST, self.request.FILES or None) if post_form.is_valid(): title = post_form.cleaned_data['title'] sub_title = post_form.cleaned_data['sub_title'] description = post_form.cleaned_data['description'] image = post_form.cleaned_data['image'] p = BlogSlider( description = description, image = image, title = title, sub_title = sub_title, user = self.request.user, ) p.save() #return JsonResponse({'newcomic': model_to_dict(p)}, status=200) return redirect('/') ''' forms.py This is my form help help help help help help help help helphelp ''' class PostForm(ModelForm): image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = BlogSlider fields = ('title', 'sub_title', 'description',) ''' models.py this is model.helphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelphelp ''' class BlogSlider(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField() title = models.CharField(max_length = 100) sub_title = models.CharField(max_length = 20) description = models.TextField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.sub_title) super(BlogSlider, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('blog-details', kwargs={ 'slug':self.slug }) class Meta: ordering = ['-id'] -
Design Patterns for Integrating External Data with Django's Database-Backed Models
I'm building a Django web application that maintains both relational data in a MySQL database as well as loosely coupled (by reference ID) full-text data in ElasticSearch (for optimized search). When a new object is created, I leverage Django signals + Celery tasks to asynchronously index the full-text data into Elasticsearch via elasticsearch-py, which works nicely. I had originally started with more tightly-coupled approaches (haystack and django-elasticsearch-py), but I quickly realized that I lost flexibility and decided to de-couple a bit. Well, now I've come full circle as I begin to develop my views/templates (where I largely leverage Model Querysets and the like) and I'm faced with decisions on how to best "fold-in" my loosely-coupled external data. For example, if my homepage by default displays a list of the 50 most recent objects, but then a user conducts a full-text search, how do I best replace the objects (via Ajax) on the page with the ES search result while also linking corresponding database data? And then revert to the Model Queryset data when a filter is pressed and the search is cleared? In other words, what are best practice implementations and design patterns for integrating external data with Django ORM/database-backed … -
Django should I use select_for_update in my view?
Imagine these two cases: First case A website where users can rent cars with each other, so the view that handle the reservation should be something like this: def reservations(request, id): deal = Deal.objects.filter(id=id, available=True) # if not exist return error ... if request.method == 'POST': form = ReservationDealForm(request.POST) if form.is_valid(): reservation = ReservationDeal() with transaction.atomic(): reservation.check_in = form.cleaned_data['check_in'] reservation.check_out = form.cleaned_data['check_out'] # ... reservation.deal = deal[0] reservation.save() deal.update(available=False) # We make the deal not available return redirect('index') Second case An e-commerce website with the view that handle the add to cart feature should be something like this: def add_to_cart(request, id): # ... quantity_request = form.cleaned_data.get('quantity') item = Item.objects.filter(id=id) with transaction.atomic(): # decrease the stock item.stock -= F('stock') - quantity_request item.save() # create an order item for the user or if # he has an order item we update only the quantity order_item = OrderItem.objects.create(user=request.user, item=item, quantity=quantity_request) # ... My questions are: For the first case, what happens if two people in the website click "reserve car" simultaneously for an available car ? It could happen that both requests are valid ? the transaction.atomic guarantee that this cannot happen or should I use select_for_update ? For the second case same … -
Having trouble extending UserDetailSerialzer in django-rest-auth
The project I am currently working on requires allowing the user to update their user info along with their user profile info. I followed the instructions on the django-rest-auth faq page for how to extend the UserDetailSerializer to allow this https://django-rest-auth.readthedocs.io/en/latest/faq.html but when I test the update methods locally I get the following error: (0.005) QUERY = 'SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > %s AND "django_session"."session_key" = %s)' - PARAMS = (datetime.datetime(2020, 5, 8, 1, 44, 9, 588358), '2f8sxtig4ajxjvylyl4naa6bv6ibjk49'); args=(datetime.datetime(2020, 5, 8, 1, 44, 9, 588358), '2f8sxtig4ajxjvylyl4naa6bv6ibjk49') (0.003) QUERY = 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = %s' - PARAMS = (1,); args=(1,) Bad Request: /rest-auth/user/ "PUT /rest-auth/user/ HTTP/1.1" 400 73 My code for the serializer is: from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User class UserSerializer(UserDetailsSerializer): dob = serializers.CharField(source="profile.dob") bio = serializers.CharField(source="profile.bio") profile_link = serializers.URLField(source="profile.profile_link") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('dob', 'bio', 'profile_link') def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) dob = profile_data.get("profile.dob") bio = profile_data.get("profile.bio") profile_link = profile_data.get("profile.profile_link") instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.profile if profile_data and dob: profile.dob = dob profile.save() if profile_data and … -
Django Pagination - how to reduce number of displayed links?
How to display this << 1 2 3 4... 11 12 >> instead of this << 1 2 3 4 5 6 7 8 9 10 11 12>> in my site on Django using pagination ? Thank you in advance !!! My html code: <div class="row"> <div class="col-md-12"> {% if jokes.has_other_pages %} <ul class="pagination"> {% if jokes.has_previous %} <li class="page-item"> <a href="?page={{jokes.previous_page_number}}" class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in jokes.paginator.page_range %} {% if jokes.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} {% if jokes.has_next %} <li class="page-item"> <a href="?page={{jokes.next_page_number}}" class="page-link">&raquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&raquo;</a> </li> {% endif %} </ul> {% endif %} </div> </div> -
Django default entries on model creation
I'm sure this has been asked before, but I cannot find the answer. In django, if I have this model from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) How would one populate this model with a default Person entry when the first migrating the field? I'm not talking about default values for the fields, but for default entries in the database. thanks -
Insert String Into Django URL in JQuery Load
I'm new to JQuery, Django and web development in general. I'm trying to figure out how to insert a string into the URL in the JQuery load function based on HTML data, but I'm getting reverse URL errors. I have view that returns a rendered HTML table from a file given a search query: urls.py urlpatterns = [ ... path('database/<search>', views.db_search, name='db_search'), ... ] views.py def db_search(request, search): return render(request, 'app/Content/database.htm', {'context': context}) This works fine when I hard-code the search string in JQuery as: $(".filterBtn").click(function(){ $("#mainpanel").load("{% url 'db_search' 'str_param' %}"); }); The problem is that there are multiple filter buttons which are dynamically generated by Django based on the state of the database. I don't want to hard-code the search parameters (nor should I). What I want to do is something like: $(".filterBtn").click(function(){ $("#mainpanel").load("{% url 'db_search' this.innerText %}"); }); but Django throws reverse URL errors because "this.innerText" isn't defined. Reverse for 'db_search' with arguments '('',)' not found. 1 pattern(s) tried: ['database/(?P[^/]+)$'] Am I missing something? It seems like this should be pretty straightforward. -
Value error when trying to migrate models in Django
I am trying to run migrations on my models but keep running into a ValueError. Here is my models.py: class Vehicles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) make = models.CharField(max_length=128) model = models.CharField(max_length=128) cover_image = models.ImageField(default='vehicle_cover_pics/default.jpg', upload_to='vehicle_cover_pics') class Meta: verbose_name = 'Vehicles' verbose_name_plural = 'Vehicles' def __str__(self): return f"{self.user.username}'s {self.model}" def get_image_filename(instance, filename): id = instance.vehicle.id return f"vehicle_pics/{id}.jpg" class VehicleImages(models.Model): vehicle = models.OneToOneField(Vehicles, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, default=None) class Meta: verbose_name = 'Vehicle Images' verbose_name_plural = 'Vehicle Images' def __str__(self): return f"{self.vehicle.user.username}'s {self.vehicle.model} Image" And when I try to migrate the models i get the following error: C:\Users\T Smith\Documents\Python\garage>python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, home, sessions Running migrations: Applying accounts.0021_auto_20200508_1328... OK Applying home.0002_auto_20200507_1905...Traceback (most recent call last): File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1768, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'None' 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 17, in main execute_from_command_line(sys.argv) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 369, … -
How to extract folder from .gitignore?
Folks, I've deleted my own django project by accident and then cloned it from Github. But the problem is that before pushing I've added my virtual environment folder to .gitignore and now can't extract/use/activate it. What can I do sometimes ? -
Uncaught SyntaxError: Unexpected token '<' VUEJS-DJANGO
I am trying to up on an application, it is made with Django using Vue.js like templates. I have the Vue app in a folder inside to Django Project, the name is Frontend. I link the static files to dist/static inside to Frontend Vue app. In localhost it working correctly, with this configuration in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/dist/static/') ] MEDIA_ROOT = os.path.join(BASE_DIR,'MEDIA') MEDIA_URL = '/media/' TEMPLATES = [ ... 'DIRS': [os.path.join(BASE_DIR, 'frontend/dist')], ... ] But my server forces me to use this configuration, and nothing work. STATIC_URL = '/' STATIC_ROOT= '/home/usuario_cpanel/python/miapp/public/' When I tip my domain in Browser, it response a white page with this errors in console: Uncaught SyntaxError: Unexpected token '<' ---- vendor.109784b9586c18ebcb5e.js:1 Uncaught SyntaxError: Unexpected token '<'----- app.69d321f0d34cdfbb9e42.js:1 My urls.py urlpatterns = [...] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ url(r'^.*$', include(('articles.urls', 'articles'), namespace='articles')), ] And my config/index.js build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, useEslint: false, productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report }, I am not sure if this configuration is correct, but I tested some posibilities, and nothing work.