Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docx file downloaded from Django is corrupt
Im trying to take user input from a form and then using that data to create a document using python docx module. But the downloaded file is not opening in MS word. It says the file is corrupt. Can someone help me with this? def resume_form(request): form = forms.resume() if request.method == 'POST': form = forms.resume(request.POST) if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) f = io.BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' response['Content-Length'] = length #document.save(response) return response return render(request, 'sample_app/index.html', {'form' : form}) -
git server and django program inside nginx
I want to run a git server inside my django program. my nginx config is like this: server{ listen 192.168.1.250:80; root /var/www/html/git; location /server\.git { client_max_body_size 0; # Git pushes can be massive, just to make sure nginx doesn't suddenly cut the connection add this. auth_basic "Git Login"; # Whatever text will do. auth_basic_user_file "/var/www/html/git/htpasswd"; include /etc/nginx/fastcgi_params; # Include the default fastcgi configs fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend; # Tells fastcgi to pass the request to the git http backend executable fastcgi_param GIT_HTTP_EXPORT_ALL ""; fastcgi_param GIT_PROJECT_ROOT /var/www/html/git; # /var/www/git is the location of all of your git repositories. fastcgi_param REMOTE_USER $remote_user; fastcgi_param PATH_INFO $1; # Takes the capture group from our location directive and gives git that. fastcgi_pass unix:/var/run/fcgiwrap.socket; # Pass the request to fastcgi } location / { include proxy_params; proxy_pass http://192.168.1.250:8000; } } my django program run correctly, but for git server, I cannot open that. but when I change the location of django program, both of them work correctly. location /user { include proxy_params; proxy_pass http://192.168.1.250:8000; } I want to use just "/" and not to "/" + string. what should I do?? -
use pygobject in apache
I want to use NetworkManager in a module in a django project. for use this module I use this codes: import gi gi.require_version('NM', '1.0') from gi.repository import NM . .#the code that use NM . when I run this django project with "runserver" there is not any error and anything work correctly. but when I run with apache, it does not work. it stop at line "from gi.repository import NM". I check for apache accesability but it is not affect. beacuse NM (or any other modules form gi,for example GLib) is dynamic and in C language I can not debug it. my system is ubuntu server 16. anybody can help me what is wrong in apache? -
Django: namespace isn't unique
In Django 1, I used to have the following URL mappings: ... url(r'^main/', include('main.urls', namespace='main')), url(r'.*', include('main.urls')) The r'.*' mapping is always at the last line to take care of all kinds of URLs not mapped. In Django 2, the following mappings are used instead: path('main/', include('main.urls', namespace='main')), re_path('.*', include('main.urls')), Although it also works, yet Django complains: ?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace Giving the second mapping another namespace is not working. Any solutions? -
Get onclick url with request in django
I have a template like bellow: <a href={{j}}> <img src="{{k}}" class="img-responsive img-rounded" data-toggle="modal" data-target="#myModal" style="width:350px;height:200px;"> </a> Now i have a function like bellow: def finction_url(requerst): a=get_the_value_of_{{j}} ### how to get the value of {{j}} Now i want to send the {{j}} value to the function (function_url) when user clicks on the photo url . Kindly suggest , either with ajax or django -
AttributeError: module 'django.db.models' has no attribute 'DateTime'
I am new to Django and i'm struck in this error: AttributeError: module 'django.db.models' has no attribute 'DateTime' I don't know the module related to DateTime model -
NoReverseMatch error with password reset emails
I have been trying to create a system for password reset emails. I have been following this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html I am getting this error when I try to visit /password/reset/ : django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Here are the relevant url patterns in urls.py: urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^password/reset/$', auth_views.password_reset, name='reset_password'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'),] How do I make this page render correctly? -
Django url variable catching
I'm having trouble at having Django urlpatterns catch a variable as an variable and instead take it as a set URL. urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/', views.about), url(r'^views/available_products/', views.available_products), url(r'^views/productview/<int:product_id>/', views.productview) ] When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error. I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong. Here is an example error message from the debug page: Page not found (404) Request Method: GET Request URL: http://localhost:8000/views/productview/12/ Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order: ^admin/ ^about/ ^views/available_products/ ^views/productview/<int:product_id>/ The current path, views/productview/12/, didn't match any of these. And here is the same error message but where the URL I try with is the same as in urlpatterns: TypeError at /views/productview/<int:product_id>/ productview() missing 1 required positional argument: 'product_id' Request Method: GET Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/ Django Version: 1.11.8 Exception Type: TypeError Exception Value: productview() missing 1 required positional argument: 'product_id' Server time: Sat, 10 Feb 2018 12:25:21 … -
How to handle inefficiency of Django's Queryset?
I've seen other questions, but unfortunately i couldn't find similar problems yet. The size of information is approximately equal to 1 GB, but the amount of objects that i'm iterating through is very big. (I'm unable to find it out though, shell is automatically killed in minutes after i execute len(model.objects.all()). Considering that the process is killed just by trying to get its length, I knew searching through the objects would be negligible (and even searching through them by utilizing similarity algorithms). But i still tried it, I've used Cosine similarity to find out the best match, this is the code for search: zsim = ("", 0) for qst in Question.objects.all().iterator(): sim = cosine_similarity(qst.question, string) if zenith_sim[1] > 0.75: break elif sim > zenith_sim[1]: zenith_sim = (qst.answer, sim) return str(zenith_sim[0]) The code above searches for the string that is most similar to the string of the user, although to avoid insignificant iteration, if the similarity is above 75%, it breaks the loop. I've also used iterator() method hoping that it would save some memory. As expected, the process was killed few minutes later after its execution. I'm not sure how can this be improved. The machine itself is not slow, … -
Sending not only form input via a POST request but other data as well
I'm trying to "develop" an application that stores todo tasks in a table. These tasks are organised like sub tasks for a "head" task. The problem is that when submitting an input as a sub task via POST I need the name of the head-task as well. I can't figure out how to send the information have stored in my <h1>-label with the information I have in my <input>. Here is my code example: <h1>Taskheader</h1> <form action="/todo/task/" method="post"> <input type="text" name="Taskitem"> <input type="submit" value="Submit" /> </form> Is it possible to send this information off, without using overly complicated code for a beginner? -
i want user enter product name and quantity then using query show whether the stock available or no
please correct my code or guide me ho to do my funtion def productsearch(request): product=request.GET.get('product') quantity=request.GET.get('quantity') product_result=Product.objects.all().filter(product_id=product) if ('quantity') > product_result.quantity_onhand: print('stock is not available') return render(request,'product/productlocation.html',{'product_result' : product_result,'quantity_result':quantity_result, 'product': product,'quantity':quantity}) template... <body> {% if quantity_result %} {% for r in quantity_result %} {{r.quantity_onhand}} {% endfor %} {% else %} <h3>no results</h3> {% endif %} </body> -
Add reverse ForeignKey relation to existing instances from django admin
If I create a new model which is a ForeignKey of another, can I update existing instances of "another" to have the new ForeignKeys as I create them? i.e. without going through the individual edit page of each instance of "another"? Suppose that I have a Car model, and I create a bunch of Car instances filling their details in the django admin: # models.py from django.db import models class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) ... After a year I decide to start renting cars to customers: # models.py from django.db import models class Customer(models.Model): name = models.CharField(max_length=200) ... class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) rented_to = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) ... If I register Customer in the admin site, I can add new customers, edit their attributes and, using inlines, add new cars that are rented to that customer: #admin.py from django.contrib import admin from .models import Car, Customer class CarInline(admin.StackedInline): model = Car extra = 3 class CustomerAdmin(admin.ModelAdmin): inlines = [CarInline] admin.site.register(Customer, CustomerAdmin) Is there a way to add existing Car instances to a Customer from the Customer admin page, instead of clicking through all the cars and selecting … -
Django annotate count value of other class
Im new to Django. Im trying to display a total sum. Portfolio Model: # Create your models here. class Portfolio(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='portfolios', on_delete=models.PROTECT) def get_absolute_url(self): return reverse('portfolio:detail',kwargs={'pk': self.pk}) def __str__(self): return self.name class PortfolioItem(models.Model): portfolio = models.ForeignKey(Portfolio, related_name='items', on_delete=models.CASCADE) trade = models.ForeignKey(Trade, on_delete=models.CASCADE) Trade Model # Create your models here. class Trade(models.Model): quantity = models.FloatField() open_price = models.FloatField() commision = models.FloatField(null=True,blank=True) exchange_rate_usdsek = models.FloatField(null=True,blank=True) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) #portfolio = models.ForeignKey(Portfolio, related_name='trades', on_delete=models.PROTECT) open_date = models.DateTimeField(auto_now_add=True, null=True) def get_absolute_url(self): return reverse('trade:detail',kwargs={'pk': self.pk}) def __str__(self): return self.stock.name @property def profit(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return ((now - buy ) / buy)*100 def net_gain(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return now - buy Portfolio index.html {% extends 'user/layout.html' %} {% block body %} {% for portfolio in all_portfolios %} <h3>{{portfolio.name}}</h3> <p>Total: {{portfolio.total_amount}}</p> <table class="table"> <thead> <tr> <th>Stock</th> <th>Amount</th> <th>Open Price</th> <th>Net P/L %</th> <th>Net P/L</th> </tr> </thead> {% for item in portfolio.items.all %} <tr> <td>{{item.trade.stock.name}}</td> <td>{{item.trade.quantity}}</td> <td>€{{item.trade.open_price}}</td> <td>€{{item.trade.stock.current_price}}</td> <td>{{item.trade.profit|floatformat:"0"}}%</td> <td>€{{item.trade.net_gain|floatformat:"2"}}</td> </tr> {% endfor %} </table> {% endfor %} {% endblock %} Portfolio view class IndexView(generic.ListView): template_name … -
How to upload and read PDF files in Django
I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename)) TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile index.html <input type="file" name="fupload" multiple> view.py if request.method == 'POST': files = request.FILES.getlist('fupload') pdf_data = [] for filename in files: read_pdf = PyPDF2.PdfFileReader(open(filename)) page = read_pdf.getPage(0) page_content = page.extractText() pdf_data.append(page_content) Can any body tell me what I am doing wrong. Thanks in advance -
Django 2 production image upload results in 500 error
I am using Django 2.0.1 within a virtual environment in production mode with Apache 2.4. Whenever I try to upload an image from Django's admin panel I get a server error 500. The specific error is [Sat Feb 10 11:37:42.473376 2018] [mpm_event:notice] [pid 1311:tid 140525266585472] AH00491: caught SIGTERM, shutting down Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined The virtualhost file is <VirtualHost *:8000> ServerAdmin webdev@springspree.in ServerName www.springspree.in:8000 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/springspree/server/static <Directory /var/www/springspree/server/static> Require all granted </Directory> Alias /media /var/www/springspree/server/media <Directory /var/www/springspree/server/media> Require all granted </Directory> <Directory /var/www/springspree/server/springspree> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django-server python-path=/var/www/springspree/server python-home=/var/www/springspree/server/venv WSGIProcessGroup django-server WSGIScriptAlias / /var/www/springspree/server/springspree/wsgi.py </VirtualHost> The files are in /var/www directory owned by root. I tried uninstalling and installing Pillow but no use. -
How to display an alert/confirmation message in Django views function?
I have written a Django view function to delete a user from AWS DynamoDB. Below is my views python function snippet : def deluser(request): db=boto3.client('dynamodb', region_name='us-west-2') acc=request.GET.get('acc') uid=request.GET.get('uid') aname=request.GET.get('aname') db.delete_item( TableName='User-Account', Key={ 'UserId': {'S': uid}, 'AccountNum': {'S': acc} } ) messages.add_message(request, messages.INFO, 'User '+uid+' successfully removed from '+acc+' : '+aname) return useracc(request) I am deleting a userid based on account number in a DynamoDB table. I have used Django message to display that the user has been removed. However, I would like to include a confirmation message/ alert asking like "Do you really want to remove/delete the user ?" before deleting it. If the user clicks on Yes only then the user will be deleted otherwise No. How can I do this ? Thanks in advance. -
Extra conditional annotation breaks previous annotation
I have the following models in a game app I'm working on:- class Player(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players') class Game(models.Model): players = models.ManyToManyField(Player, through='GameMembership', related_name='games') class GameMembership(models.Model): game = models.ForeignKey(Game, related_name='memberships') player = models.ForeignKey(Player, related_name='memberships') team = models.ForeignKey(Team, null=True, related_name='memberships') selected = models.BooleanField(default=False) class Team(models.Model): game = models.ForeignKey(Game, related_name='teams') score = models.IntegerField(null=True) I want to get a list of all the Players along with the number of times they were selected, so I annotate the queryset like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1)))) which works exactly as expected. However, I also want the total number of goals that were scored in all the games each player was selected, so I annotate like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1))), total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score')))) which gives the right number for total_goals but for some reason, the value of the played count has doubled! All I did was add this annotation:- total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score'))) So what happened? I strongly suspect I need a distinct() call somewhere but I don't see why the extra annotation has an effect on the first one. Any ideas? -
Best Postgres/DB format for storing an array of strings with a boolean attached to them in Django?
I'm storing an array of URL links in my Postgres database like this: urls = ArrayField( models.CharField(max_length=250, blank=False) ) But I want to track if a URL has been visited or not, as a boolean. What is the best way to do this? -
Cannot redirect when djanog model class is mocked
I have a view here which adds a new List to the database and redirects to the List page. I have get_absolute_url configured in the model class. It seems to works perfectly. def new_list(request): form = ItemForm(request.POST) if form.is_valid(): list_ = List() list_.owner = request.user list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {'form': form}) But the problem happens when I try to mock the model class and the form class with patch from unitest.mock class TestMyLists(TestCase): @patch('lists.views.List') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated( self, mockItemFormClass, mockListClass ): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) When I run the test, I get error like this: Traceback (most recent call last): File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/BAC4BB93C4BB4FFD/codes/tdd/superlists/lists/views.py", line 36, in new_list return redirect(list_) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/shortcuts.py", line 58, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/http/response.py", line 407, in __init__ self['Location'] = iri_to_uri(redirect_to) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/utils/encoding.py", line 151, in iri_to_uri return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "/usr/local/lib/python3.6/urllib/parse.py", line 787, in quote return quote_from_bytes(string, safe) File "/usr/local/lib/python3.6/urllib/parse.py", line 812, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() … -
Advices for social-networking
I am a high school student and I like computing. I have bases with C#, R, Python and I have been developing a static website with Html5 and CSS. I'd like now to start a new project. A social network like for riders but I don't know at all which framework or language start with. I already heard about Django, Ruby on Rails, Go, that make alot of choices and I wanted to have advices from experts or connoisseurs in the domain. -
django-rest-framwork Got AttributeError when attempting to get a value for field
i want get all prodcut table values with join product_ratings table . i did somthing like this but this code give me AttributeError ... i did product_ratings = ProductRatingSerializer(many=True) in product serializer and used this value in field but it not work: its full error message: Got AttributeError when attempting to get a value for field `product_ratings` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'product_ratings'. view : class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs its serializer classes: class ProductRatingSerializer(ModelSerializer): class Meta: model = Product_ratings fields = [ 'p_id', 'commenter', 'comment', 'rating', 'created_date', ] read_only_fields = ['p_id'] class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'filepath', 'price', 'created_date', 'updated_date', 'product_ratings', ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author'] related model class : class Product(models.Model): product_id = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='cat_id') … -
Display output with out refresh using Django, Ajax
I am programming a simple basic calculator where I get the input from the user taking the input and do the calculation and display the output back on the same page I have a basic HTML form <form id="html_calc_form" action={%url 'calculation' %} method="post"> {% csrf_token %} First Number:<br> <input type="number" name="first number" value="0"> <br> Second Number:<br> <input type="number" name="second number" value="0"> <br> Operation:<br> <select name="operation" multiple> <option value="Addition">Addition</option> <option value="Subraction">Subraction</option> <option value="Muntiplication">Muntiplication</option> <option value="Division">Division</option> </select> <br><br> <input type="submit" name "submit" value="Submit"> <output name="result" ></output> </form> Ajax logic to prevent from refreshing the page $(document).ready(function(){ $('#html_calc_form').submit(function(event){ console.log(event); event.preventDefault() $.ajax({ url:'calc/', type:'POST', data:$(this).serialize(), success:function(response){ console.log(response); $('form')[0].reset(); } }); }) }) In django I have creates a model class Calculation(models.Model): first_digit = models.DecimalField(max_digits=7, decimal_places=3) second_digit = models.DecimalField(max_digits=7, decimal_places=3) CALCULATION_CHOICE = (('+', 'Addition'), ('-', 'Subraction'), ('*', 'Muntiplication'), ('/', 'Division')) calculate = models.CharField(max_length=1, choices=CALCULATION_CHOICE) And finaly my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) return JsonResponse(model_to_dict(value)) def index(request): return render(request, 'calculation/calculator.html') I want to pass the result to my HTML template and display … -
Django Jquery: Link (a-tag) to specific div on a different template does not work when this jQuery function is added
I have a link in a django template with the following characteristics: <a href="{% url 'rates:index' %}#our-services" class="accent-2">list</a> That link worked as intended until I used the JS code underneath in the same page as linked to above. This code lets the user select different tabs to display certain information. I am a novice when it comes to JS and therefore used a code snippet from Bourbon Refills. When I comment out the code the link works fine. Any suggestions on what part of the JS code affects the link? Any help would be greatly appreciated. $(function() { var containerSelector = '[data-tab-wrapper]'; var tabListSelector = '[data-tablist]'; var tabListItemSelector = '[data-tablist] > li'; var tabSelector = '[data-tablist] > li > a'; var tabPanelSelector = '[data-tabpanel]'; $(tabListSelector).attr('role', 'tablist'); $(tabListItemSelector).attr('role', 'presentation'); $(tabPanelSelector).attr('role', 'tabpanel'); // Setup: Wire up the anchors and their target tabPanels $(tabSelector).each(function(_, element) { $(element).attr({ 'role': 'tab', 'tabindex': '-1', 'aria-controls': getAnchor($(element)) }); }); // Setup: Set the tablist $(tabListSelector).attr('role', 'tablist'); // Setup: Select the first tab var firstTabLinkSelector = tabListItemSelector + ':first-child a'; select($(firstTabLinkSelector)); // Setup: Make each tabPanel focusable $(tabPanelSelector + ' > *:first-child').attr({'tabindex' : '0'}); // Setup: Hide all panels besides the first hide($(tabPanelSelector + ':not(:first-of-type)')); // When focused, … -
Check if user is part of a manytomany relationship django
I have this model for a Set: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') As you can see, the last field is a ManyToMany field. I need a queryset to get all the Sets that the user is part of. How would I do this? -
type char exceed 10485760 limit error still showing after I change the limit to something less than MAX
I have a django app, I'm migrating it's database from sqlite3 to postgres, i get the following error line since i got a field in one of the models set to 500000000 so i changed it to 10485750 and ran: python manage.py makemigrations app python manage.py sqlmigrate app 0001 python manage.py migrate but still got the following error django.db.utils.DataError: length for type varchar cannot exceed 10485760 LINE 1: ...ber" TYPE varchar(500000000) USING ........ how can I make it feel the change I made?